libjboss-common-java-0.0+svn2938.orig/0000755000175000017500000000000011105642377017420 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/0000755000175000017500000000000011105642366021634 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/0000755000175000017500000000000011105642362022417 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/0000755000175000017500000000000011105642362023376 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/0000755000175000017500000000000011105642361024316 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/0000755000175000017500000000000011105642361025105 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/0000755000175000017500000000000011105642361026225 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/0000755000175000017500000000000011105642361027204 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/0000755000175000017500000000000011105642361030161 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/0000755000175000017500000000000011105642362031141 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/0000755000175000017500000000000011105642361031740 5ustar twernertwerner././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/resolver/libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/resolve0000755000175000017500000000000011105642361033340 5ustar twernertwerner././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/resolver/JBossEntityResolverUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/resolve0000644000175000017500000001144110776055124033353 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.xml.resolver; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.jboss.util.xml.JBossEntityResolver; import org.xml.sax.InputSource; import junit.framework.TestCase; /** * A JBossEntityResolverUnitTestCase. * * @author Alexey Loubyansky * @version $Revision: 1.1 $ */ public class JBossEntityResolverUnitTestCase extends TestCase { public JBossEntityResolverUnitTestCase(String arg0) { super(arg0); } /** * The spcial thing about the resolution of xsd:redefine is that * the parser passes the namespace of the redefining schema as publicId * and the schema location of the redefined schema as systemId. Now, if * the redefining schema's namespace has already been mapped * to a schema location of the redefining schema then schema location * argument is ignored and the redefining schema is returned instead of the * redefined schema. * * @throws Exception */ public void testResolveRedefine() throws Exception { String baseName = getRootName() + "_" + getName() + "_"; String redefiningName = baseName + "redefining.xsd"; InputStream redefiningStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(redefiningName); assertNotNull("Expected to find " + redefiningName + " in the classpath", redefiningStream); int redefiningSize = bytesTotal(redefiningStream); String redefinedName = baseName + "redefined.xsd"; InputStream redefinedStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(redefinedName); assertNotNull("Expected to find " + redefinedName + " in the classpath", redefinedStream); int redefinedSize = bytesTotal(redefinedStream); assertTrue(redefiningSize != redefinedSize); JBossEntityResolver resolver = new JBossEntityResolver(); resolver.registerLocalEntity("urn:jboss:xml:test", redefiningName); InputSource resolvedSource = resolver.resolveEntity("urn:jboss:xml:test", redefinedName); assertNotNull(resolvedSource); InputStream resolvedStream = resolvedSource.getByteStream(); assertNotNull(resolvedStream); int resolvedSize = bytesTotal(resolvedStream); assertEquals("Schema sizes: redefined=" + redefinedSize + ", redefining=" + redefiningSize, redefinedSize, resolvedSize); } public void testSystemPropertyInSystemID() throws Exception { JBossEntityResolver resolver = new JBossEntityResolver(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL tstConfig = loader.getResource("tst-config_5.xsd"); assertNotNull(tstConfig); System.setProperty("tst.config_5.xsd", tstConfig.toExternalForm()); InputSource resolvedSource = resolver.resolveEntity("urn:jboss:xml:test", "${tst.config_5.xsd}"); assertNotNull(resolvedSource); InputStream resolvedStream = resolvedSource.getByteStream(); assertNotNull(resolvedStream); int resolvedSize = bytesTotal(resolvedStream); assertEquals(280, resolvedSize); } private int bytesTotal(InputStream redefinedStream) throws IOException { byte[] bytes = new byte[1024]; int redefinedSize = 0; try { for(int i = 0; (i = redefinedStream.read(bytes)) > 0; redefinedSize += i); } finally { redefinedStream.close(); } return redefinedSize; } protected String getRootName() { String longName = getClass().getName(); int dot = longName.lastIndexOf('.'); if (dot != -1) return longName.substring(dot + 1); return longName; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/DOMWriterTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/xml/DOMWrit0000644000175000017500000002324111044361066033154 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.xml; // $Id: DOMWriterTestCase.java 2891 2008-07-31 16:03:02Z thomas.diesler@jboss.com $ import java.io.ByteArrayInputStream; import java.io.StringWriter; import javax.xml.namespace.QName; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.stream.StreamSource; import junit.framework.TestCase; import org.jboss.util.xml.DOMUtils; import org.jboss.util.xml.DOMWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Test the DOMWriter * * @author Thomas.Diesler@jboss.org * @since 10-Aug-2006 */ public class DOMWriterTestCase extends TestCase { /** The element does not contain the required ns declaration. */ public void testNamespaceCompletionOne() throws Exception { String inStr = "" + "" + "" + "env:Client" + "Endpoint {http://webmethod.jsr181.ws.test.jboss.org/jaws}TestEndpointPort does not contain operation meta data for: {http://webmethod.jsr181.ws.test.jboss.org/jaws}noWebMethod" + "" + "" + ""; Element env = DOMUtils.parse(inStr); Element body = DOMUtils.getFirstChildElement(env); Element fault = DOMUtils.getFirstChildElement(body); String expStr = "" + "env:Client" + "Endpoint {http://webmethod.jsr181.ws.test.jboss.org/jaws}TestEndpointPort does not contain operation meta data for: {http://webmethod.jsr181.ws.test.jboss.org/jaws}noWebMethod" + ""; String wasStr = DOMWriter.printNode(fault, false); assertEquals(expStr, wasStr); } /** The element already contains the required ns declaration. */ public void testNamespaceCompletionTwo() throws Exception { String inStr = "" + "" + "" + "" + "" + "" + "" + ""; Element env = DOMUtils.parse(inStr); Element body = DOMUtils.getFirstChildElement(env); Element rpc = DOMUtils.getFirstChildElement(body); String expStr = "" + "" + "" + ""; String wasStr = DOMWriter.printNode(rpc, false); assertEquals(expStr, wasStr); } /** The element does not contain the required ns declaration, the child does. */ public void testNamespaceCompletionThree() throws Exception { String inStr = "" + "" + "" + "" + "" + "" + "" + ""; Element env = DOMUtils.parse(inStr); Element body = DOMUtils.getFirstChildElement(env); String expStr = "" + "" + "" + "" + "" + ""; String wasStr = DOMWriter.printNode(body, false); assertEquals(expStr, wasStr); } /** The envelope defines a default namespace */ public void testNamespaceCompletionDefault() throws Exception { String inStr = "" + "" + "" + "" + "" + "" + "" + ""; Element env = DOMUtils.parse(inStr); Element body = DOMUtils.getFirstChildElement(env); Element rpc = DOMUtils.getFirstChildElement(body); String expStr = "" + "" + "" + ""; String wasStr = DOMWriter.printNode(rpc, false); assertEquals(expStr, wasStr); } /** The element does not contain the required attribute ns declaration. */ public void testNamespaceCompletionAttribute() throws Exception { String inStr = "" + "" + "" + "" + "" + ""; Element env = DOMUtils.parse(inStr); Element header = DOMUtils.getFirstChildElement(env); Element headerElement = DOMUtils.getFirstChildElement(header); String expStr = ""; String wasStr = DOMWriter.printNode(headerElement, false); assertEquals(expStr, wasStr); } public void testEntity() throws Exception { String expStr = "" + "" + "" + "" + "" + ""; Element domEl = DOMUtils.parse(expStr); String wasStr = DOMWriter.printNode(domEl, false); assertEquals(expStr, wasStr); } // [JBWS-762] DOMUtils.parse skips peer comments on Document node public void testDocumentComments() throws Exception { String expStr = "" + "" + "" + "" + "some value" + ""; Document doc = DOMUtils.parse(expStr).getOwnerDocument(); StringWriter strwr = new StringWriter(); new DOMWriter(strwr, "UTF-8").print(doc); String wasStr = strwr.toString(); assertEquals(expStr, wasStr); } public void testElementNamespaceURIElementNS() throws Exception { String xmlIn = "World"; Element root = DOMUtils.createElement(new QName("http://somens", "Hello")); assertEquals("http://somens", root.getNamespaceURI()); Element child = (Element)root.appendChild(DOMUtils.createElement(new QName("Sub"))); child.appendChild(DOMUtils.createTextNode("World")); String xmlOut = DOMWriter.printNode(root, false); assertEquals(xmlIn, xmlOut); } public void testElementNamespaceURIDocumentParse() throws Exception { String xmlIn = "World"; Element root = DOMUtils.parse(xmlIn); assertEquals("http://somens", root.getNamespaceURI()); String xmlOut = DOMWriter.printNode(root, false); assertEquals(xmlIn, xmlOut); } public void testElementNamespaceURITransformer() throws Exception { String xmlIn = "World"; StreamSource source = new StreamSource(new ByteArrayInputStream(xmlIn.getBytes())); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMResult result = new DOMResult(); transformer.transform(source, result); Element root = ((Document)result.getNode()).getDocumentElement(); assertEquals("http://somens", root.getNamespaceURI()); String xmlOut = DOMWriter.printNode(root, false); assertEquals(xmlIn, xmlOut); } public void testWhiteSpaceRemove() throws Exception { String xmlIn = " World "; Element root = DOMUtils.parse(xmlIn); root.normalize(); StringWriter strwr = new StringWriter(); new DOMWriter(strwr).setIgnoreWhitespace(true).print(root); String xmlOut = strwr.toString(); assertEquals("World", xmlOut); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/graph/0000755000175000017500000000000011105642361032241 5ustar twernertwerner././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/graph/GraphTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/graph/Graph0000644000175000017500000002252610774222622033241 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.graph; import java.util.ArrayList; import java.util.Comparator; import junit.framework.TestCase; import org.jboss.util.graph.Graph; import org.jboss.util.graph.Edge; import org.jboss.util.graph.Vertex; import org.jboss.util.graph.Visitor; /** * Tests of the graph package * * @author Scott.Stark@jboss.org * @version $Revision: 1.1 $ */ @SuppressWarnings("unchecked") public class GraphTestCase extends TestCase { Vertex a = new Vertex("A", "x.ear"); Vertex b = new Vertex("B"); Vertex c = new Vertex("C"); Vertex d = new Vertex("D"); Vertex e = new Vertex("E"); Vertex f = new Vertex("F"); Vertex g = new Vertex("G"); Vertex h = new Vertex("H"); Vertex i = new Vertex("I"); Vertex ear = new Vertex("x", "x.ear"); Vertex e1 = new Vertex("e1", "e1.jar"); Vertex e2 = new Vertex("e2", "e2.jar"); Vertex w1 = new Vertex("w1", "w1.war"); public GraphTestCase(String name) { super(name); } /** Depth first search of digraph1 * @throws Exception */ public void testDFS() throws Exception { Graph graph = buildGraph1(); final ArrayList order = new ArrayList(); Visitor visitor = new Visitor() { public void visit(Graph g, Vertex v) { System.out.println("visit "+v.getName()); order.add(v); } }; graph.depthFirstSearch(a, visitor); assertTrue("Visted count == 8("+order.size()+")", order.size() == 8); // Validate the expected order and visited state for(int n = 0; n < order.size(); n ++) { Vertex v = (Vertex) order.get(n); System.out.println(v); assertTrue(v.getName()+" is visited", v.visited()); } String[] names = {"A", "B", "C", "H", "G", "I", "E", "F"}; for(int n = 0; n < order.size(); n ++) { Vertex v = (Vertex) order.get(n); assertTrue("#"+n+" is "+names[n]+"("+v.getName()+")", v.getName().equals(names[n])); } } /** Breadth first search of digraph1 * @throws Exception */ public void testBFS() throws Exception { Graph graph = buildGraph1(); final ArrayList order = new ArrayList(); Visitor visitor = new Visitor() { public void visit(Graph g, Vertex v) { System.out.println("visit "+v.getName()); order.add(v); } }; graph.breadthFirstSearch(a, visitor); assertTrue("Visted count == 8("+order.size()+")", order.size() == 8); // Validate the expected order and visited state for(int n = 0; n < order.size(); n ++) { Vertex v = order.get(n); System.out.println(v); assertTrue(v.getName()+" is visited", v.visited()); } String[] names = {"A", "B", "F", "C", "G", "E", "I", "H"}; for(int n = 0; n < order.size(); n ++) { Vertex v = order.get(n); assertTrue("#"+n+" is "+names[n]+"("+v.getName()+")", v.getName().equals(names[n])); } } public void testCycleDection() { Graph g = new Graph(); Vertex v0 = new Vertex("V0"); Vertex v1 = new Vertex("V1"); Vertex v2 = new Vertex("V2"); g.addVertex(v0); g.addVertex(v1); g.addVertex(v2); g.addEdge(v0, v1, 0); g.addEdge(v1, v2, 0); g.addEdge(v2, v0, 0); Edge[] cycleEdges = g.findCycles(); assertTrue("There is a cycle", cycleEdges.length == 1); for(int n = 0; n < cycleEdges.length; n ++) System.out.println(cycleEdges[n]); Edge e = cycleEdges[0]; Vertex vx = e.getFrom(); Vertex vy = e.getTo(); assertTrue("Cycle edge is V2->V0", vx.getName().equals("V2") && vy.getName().equals("V0")); } public void testEdges() { Graph g = new Graph(); assertTrue(g.addVertex(ear)); assertFalse(g.addVertex(ear)); assertEquals("size == 1", 1, g.size()); try { g.addEdge(ear, e1, 0); fail("Should have seen IllegalArgumentException"); } catch(IllegalArgumentException e) { System.out.println("Saw IAE as expected"); } assertTrue("Added e1", g.addVertex(e1)); assertTrue("Added E(ear, e1)", g.addEdge(ear, e1, 0)); assertFalse("Did not readded E(ear, e1)", g.addEdge(ear, e1, 0)); assertTrue("Added e2", g.addVertex(e2)); assertTrue("Added w1", g.addVertex(w1)); assertTrue("Added E(ear, e2)", g.addEdge(ear, e2, 0)); assertTrue("Added E(ear, w1)", g.addEdge(ear, w1, 0)); Edge[] cycles = g.findCycles(); assertEquals("cycles.length = 0", 0, cycles.length); } public void testFindByName() { Graph g = buildEarGraph(); Vertex v = g.findVertexByName("x"); assertEquals("x", ear, v); v = g.findVertexByName("e1"); assertEquals("e1", e1, v); v = g.findVertexByName("e2"); assertEquals("e2", e2, v); v = g.findVertexByName("w1"); assertEquals("w1", w1, v); v = g.findVertexByName("w1.war"); assertTrue("w1.war not found", v == null); } public void testFindByData() { Graph g = buildEarGraph(); Comparator SC = new Comparator() { public int compare(String s1, String s2) { int compare; if( s1 == s2 ) compare = 0; else if( s1 == null ) compare = 1; else if( s2 == null ) compare = -1; else compare = s1.compareTo(s2); return compare; } }; Vertex v = g.findVertexByData("x.ear", SC); assertEquals("x.ear", ear, v); v = g.findVertexByData("e1.jar", SC); assertEquals("e1.jar", e1, v); v = g.findVertexByData("e2.jar", SC); assertEquals("e2.jar", e2, v); v = g.findVertexByData("w1.war", SC); assertEquals("w1.war", w1, v); v = g.findVertexByData("w1", SC); assertTrue("w1 not found", v == null); } /** Build the following digraph: A : B, F B : C, G C : H D : E, H E : F : E, I G : A H : G, I I : E, G */ private Graph buildGraph1() { Graph graph = new Graph(); assertTrue("Added A", graph.addVertex(a)); assertTrue("Added B", graph.addVertex(b)); assertTrue("Added C", graph.addVertex(c)); assertTrue("Added D", graph.addVertex(d)); assertTrue("Added E", graph.addVertex(e)); assertTrue("Added F", graph.addVertex(f)); assertTrue("Added G", graph.addVertex(g)); assertTrue("Added H", graph.addVertex(h)); assertTrue("Added I", graph.addVertex(i)); // A : B, F assertTrue("Added A -> B", graph.addEdge(a, b, 0)); assertTrue("Added A -> F", graph.addEdge(a, f, 0)); // B : C, G assertTrue("Added B -> C", graph.addEdge(b, c, 0)); assertTrue("Added B -> G", graph.addEdge(b, g, 0)); // C : H assertTrue("Added C -> H", graph.addEdge(c, h, 0)); // D : E, H assertTrue("Added D -> E", graph.addEdge(d, e, 0)); assertTrue("Added D -> H", graph.addEdge(d, h, 0)); // F : E, I assertTrue("Added F -> E", graph.addEdge(f, e, 0)); assertTrue("Added F -> I", graph.addEdge(f, i, 0)); // G : A assertTrue("Added G -> A", graph.addEdge(g, a, 0)); // H : G, I assertTrue("Added H -> G", graph.addEdge(h, g, 0)); assertTrue("Added H -> I", graph.addEdge(h, i, 0)); // I : E, G assertTrue("Added I -> E", graph.addEdge(i, e, 0)); assertTrue("Added I -> G", graph.addEdge(i, g, 0)); assertTrue("Graph has 9 verticies", graph.size() == 9); return graph; } /** Build the following digraph: x.ear : e1.jar, e2.jar, w1.war */ private Graph buildEarGraph() { Graph g = new Graph(); assertTrue(g.addVertex(ear)); assertFalse(g.addVertex(ear)); assertTrue("Added e1", g.addVertex(e1)); assertTrue("Added E(ear, e1)", g.addEdge(ear, e1, 0)); assertTrue("Added e2", g.addVertex(e2)); assertTrue("Added w1", g.addVertex(w1)); assertTrue("Added E(ear, e2)", g.addEdge(ear, e2, 0)); assertTrue("Added E(ear, w1)", g.addEdge(ear, w1, 0)); return g; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/protocol/0000755000175000017500000000000011105642361033001 5ustar twernertwerner././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/protocol/FileURLConnectionTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/protocol/Fi0000644000175000017500000001547311023722741033274 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.protocol; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import junit.framework.TestCase; import org.jboss.net.protocol.file.FileURLConnection; import org.jboss.util.file.Files; /** * Tests of the expected jdk file: url connection protocol handler behaviors. * * @author Scott.Stark@jboss.org * @author Dimitris.Andreadis@jboss.org * @version $Revision:$ */ public class FileURLConnectionTestCase extends TestCase { public void testLastModified() throws Exception { File tmp = File.createTempFile("testLastModified", ""); tmp.deleteOnExit(); long lastModified = tmp.lastModified(); System.out.println("Created file: " + tmp.getAbsolutePath() + ", lastModified:" + lastModified); URL tmpURL = tmp.toURL(); // Test JDK's provided FileURLConnection checkLastModified(tmpURL.openConnection(), lastModified); // Test JBoss's FileURLConnection checkLastModified(new FileURLConnection(tmpURL), lastModified); } public void testContentLength() throws Exception { File tmp = File.createTempFile("testContentLength", ""); tmp.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmp); fos.write("testLength".getBytes()); fos.close(); long expectedLength = tmp.length(); URL tmpURL = tmp.toURL(); checkContentLength(tmpURL.openConnection(), expectedLength); checkContentLength(new FileURLConnection(tmpURL), expectedLength); } public void testContentType() throws Exception { File tmp = File.createTempFile("testContentType", ".txt"); tmp.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmp); fos.write("A text file".getBytes()); fos.close(); String expectedContentType = "text/plain"; URL tmpURL = tmp.toURL(); checkContentType(tmpURL.openConnection(), expectedContentType); checkContentType(new FileURLConnection(tmpURL), expectedContentType); File dir = tmp.getParentFile(); URL dirURL = dir.toURL(); checkContentType(dirURL.openConnection(), expectedContentType); checkContentType(new FileURLConnection(dirURL), expectedContentType); } public void testDirectoryListing() throws Exception { // create a test directory structure // TMPDIR/testDirectoryList39558 // TMPDIR/testDirectoryList39558/test.txt // TMPDIR/testDirectoryList39558/test.dir File rootDir = File.createTempFile("testDirectoryList", ""); try { rootDir.delete(); rootDir.mkdir(); System.out.println(rootDir); File tmpFile = new File(rootDir, "test.txt"); tmpFile.createNewFile(); System.out.println(tmpFile); FileOutputStream fos = new FileOutputStream(tmpFile); fos.write("this is a test file".getBytes()); fos.close(); File tmpDir = new File(rootDir, "test.dir"); tmpDir.mkdir(); System.out.println(tmpDir); String[] expectedList = { "test.dir", "test.txt", null }; URL rootURL = rootDir.toURL(); // Check JDK FileURLConnection impl checkDirectoryListing(rootURL.openConnection(), expectedList); // Test JBoss FileURLConnection impl checkDirectoryListing(new FileURLConnection(rootURL), expectedList); } finally { // cleanup Files.delete(rootDir); } } private void checkLastModified(URLConnection conn, long expectedLastModified) { System.out.println("Got URLConnection of type: " + conn.getClass().getName()); assertEquals(expectedLastModified, conn.getLastModified()); long lastModifiedHdr = conn.getHeaderFieldDate("last-modified", 0); System.out.println(conn.getURL() + ", last-modified header: "+lastModifiedHdr); // the last-modified header is expected to strip the milliseconds to // comply with the (dd MMM yyyy HH:mm:ss) format, so the following assertions // is invalid on windows that provide millisecond accuracy to File.lastModified() // see, http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504473 // assertEquals(expectedLastModified, lastModifiedHdr); } private void checkContentLength(URLConnection conn, long expectedLength) { System.out.println("Got URLConnection of type: " + conn.getClass().getName()); int length = conn.getContentLength(); System.out.println(conn.getURL() + ", content-length:" + length); assertEquals(expectedLength, length); int lengthHdr = conn.getHeaderFieldInt("content-length", 0); assertEquals(expectedLength, lengthHdr); } private void checkContentType(URLConnection conn, String expectedType) { System.out.println("Got URLConnection of type: " + conn.getClass().getName()); String type = conn.getContentType(); System.out.println(conn.getURL() + ", content-type: " + type); assertEquals(type, expectedType); } private void checkDirectoryListing(URLConnection conn, String[] expectedFiles) throws IOException { System.out.println("Got URLConnection of type: " + conn.getClass().getName()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { // verify the sorted directory list for (int i = 0; i < expectedFiles.length; i++) { String msg = "directory entry #" + i; System.out.println(msg + " : " + expectedFiles[i]); assertEquals(msg, expectedFiles[i], in.readLine()); } } finally { in.close(); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/threadpool/libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/threadpool/0000755000175000017500000000000011105642361033301 5ustar twernertwerner././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/threadpool/BasicThreadPoolTCCLTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/threadpool/0000644000175000017500000001127210774161402033311 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.threadpool; import junit.framework.TestCase; import org.jboss.util.loading.ClassLoaderSource; import org.jboss.util.threadpool.BasicThreadPool; /** * Tests thread context classloader management by BasicThreadPool. * * @author Brian Stansberry */ public class BasicThreadPoolTCCLTestCase extends TestCase { protected ClassLoader origCl; /** * @param name */ public BasicThreadPoolTCCLTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); origCl = Thread.currentThread().getContextClassLoader(); } @Override protected void tearDown() throws Exception { try { super.tearDown(); } finally { Thread.currentThread().setContextClassLoader(origCl); } } public void testNullClassLoaderSource() throws Exception { ClassLoader existing = origCl == null ? getExtendedClassLoader() : origCl; Thread.currentThread().setContextClassLoader(existing); runClassLoaderSourceTest(null, existing); Thread.currentThread().setContextClassLoader(null); runClassLoaderSourceTest(null, null); } public void testConfiguredClassLoaderSource() throws Exception { ClassLoaderSource source = new TestClassLoaderSource(); runClassLoaderSourceTest(source, source.getClassLoader()); } private void runClassLoaderSourceTest(ClassLoaderSource source, ClassLoader expected) throws Exception { ThreadGroup group = new ThreadGroup("Test"); BasicThreadPool pool = new BasicThreadPool("Test", group); // Only one thread so we can use it twice to confirm // it gets cleaned after the first task pool.setMaximumPoolSize(1); pool.setClassLoaderSource(source); Task task = new Task(); pool.run(task); // Wait for task completion synchronized (task) { if (!task.done) { task.wait(); } } // ClassLoader expected = source == null ? null : source.getClassLoader(); assertEquals(expected, task.incomingCl); Task task2 = new Task(); pool.run(task2); // Wait for task completion synchronized (task2) { if (!task2.done) { task2.wait(); } } assertSame(expected, task.incomingCl); assertEquals("Pool size limited", 1, pool.getPoolSize()); } private ClassLoader getExtendedClassLoader() { return new ExtendedClassLoader(origCl); } private class ExtendedClassLoader extends ClassLoader { ExtendedClassLoader(ClassLoader parent) { super(parent); } } private class Task implements Runnable { private ClassLoader incomingCl; private boolean done; public void run() { incomingCl = Thread.currentThread().getContextClassLoader(); // Deliberately pollute the TCCL ClassLoader leakedCl = BasicThreadPoolTCCLTestCase.this.getExtendedClassLoader(); Thread.currentThread().setContextClassLoader(leakedCl); // Wake up the test thread synchronized (this) { done = true; notifyAll(); } } } private class TestClassLoaderSource implements ClassLoaderSource { private ClassLoader cl; TestClassLoaderSource() { cl = BasicThreadPoolTCCLTestCase.this.getExtendedClassLoader(); } public ClassLoader getClassLoader() { return cl; } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/0000755000175000017500000000000011105642362033323 5ustar twernertwerner././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/ThreadPoolRunnableUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/0000644000175000017500000002773110774222622033343 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.concurrent; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.ArrayList; import org.jboss.util.threadpool.BasicThreadPool; import org.jboss.util.threadpool.ThreadPoolFullException; import org.jboss.util.threadpool.BlockingMode; import org.jboss.logging.Logger; import junit.framework.TestCase; /** * Tests of thread pool with Runnables added to the pool * * @see org.jboss.util.threadpool.ThreadPool * @author Adrian.Brock * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class ThreadPoolRunnableUnitTestCase extends TestCase { private static Logger log = Logger.getLogger(ThreadPoolRunnableUnitTestCase.class); /** Basic test */ static final int BASIC = 0; /** Hold the thread after start */ static final int HOLD_START = 1; /** The started runnables */ HashSet startedRunnables = new HashSet(); /** The started releases */ HashSet startedReleases = new HashSet(); /** The finished runnables */ HashSet finishedRunnables = new HashSet(); /** The thread names */ HashMap threadNames = new HashMap(); /** * Create a new ThreadPoolRunnableUnitTestCase * * @param name the test to run */ public ThreadPoolRunnableUnitTestCase(String name) { super(name); } public void testBasic() throws Exception { log.debug("testBasic"); BasicThreadPool pool = new BasicThreadPool(); try { pool.run(new TestRunnable(BASIC, "test")); waitFinished(1); HashSet expected = makeExpected(new Object[] {"test"}); assertEquals(expected, finishedRunnables); } finally { pool.stop(true); } } public void testMultipleBasic() throws Exception { log.debug("testMultipleBasic"); BasicThreadPool pool = new BasicThreadPool(); try { pool.run(new TestRunnable(BASIC, "test1")); pool.run(new TestRunnable(BASIC, "test2")); pool.run(new TestRunnable(BASIC, "test3")); waitFinished(3); HashSet expected = makeExpected(new Object[] {"test1", "test2", "test3"}); assertEquals(expected, finishedRunnables); } finally { pool.stop(true); } } public void testSimplePooling() throws Exception { log.debug("testSimplePooling"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumPoolSize(1); try { pool.run(new TestRunnable(BASIC, "test1")); waitFinished(1); pool.run(new TestRunnable(BASIC, "test2")); waitFinished(2); assertEquals(threadNames.get("test1"), threadNames.get("test2")); } finally { pool.stop(true); } } public void testMultiplePooling() throws Exception { log.debug("testMultiplePooling"); BasicThreadPool pool = new BasicThreadPool(); try { pool.run(new TestRunnable(HOLD_START, "test1")); waitStarted(1); pool.run(new TestRunnable(BASIC, "test2")); waitFinished(1); releaseStarted("test1"); waitFinished(2); assertTrue("Shouldn't run on the same thread", threadNames.get("test1").equals(threadNames.get("test2")) == false); } finally { pool.stop(true); } } public void testMaximumPool() throws Exception { log.debug("testMaximumPool"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumPoolSize(1); try { pool.run(new TestRunnable(HOLD_START, "test1")); waitStarted(1); pool.run(new TestRunnable(BASIC, "test2")); Thread.sleep(1000); assertEquals(0, finishedRunnables.size()); releaseStarted("test1"); waitFinished(2); assertEquals(makeExpected(new Object[] {"test1", "test2"}), finishedRunnables); } finally { pool.stop(true); } } public void testMaximumQueue() throws Exception { log.debug("testMaximumQueue"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { pool.run(new TestRunnable(HOLD_START, "test1")); waitStarted(1); pool.run(new TestRunnable(BASIC, "test2")); boolean caught = false; try { pool.run(new TestRunnable(BASIC, "test3")); } catch (ThreadPoolFullException expected) { caught = true; } assertTrue("Expected ThreadPoolFullException", caught); releaseStarted("test1"); waitFinished(2); assertEquals(makeExpected(new Object[] {"test1", "test2"}), finishedRunnables); } finally { pool.stop(true); } } public void testRunnableTimeout() throws Exception { log.debug("testRunnableTimeout"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { TestRunnable test = new TestRunnable(HOLD_START, "test1", 12*1000); pool.run(test, 0, 10*1000); waitStarted(1); releaseStarted("test1"); waitFinished(1); assertEquals(makeExpected(new Object[] {"test1"}), finishedRunnables); } finally { pool.stop(true); } } public void testRunnableTimeoutWithSpinLoop() throws Exception { log.debug("testRunnableTimeoutWithSpinLoop"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { TestRunnable test = new TestRunnable(HOLD_START, "test1", Long.MAX_VALUE); pool.run(test, 0, 8*1000); waitStarted(1); releaseStarted("test1"); Thread.sleep(12*1000); // Run another task to validate the previous thread has been cleared pool.run(new TestRunnable(BASIC, "test2")); waitStarted(1); releaseStarted("test2"); waitFinished(1); assertEquals(makeExpected(new Object[] {"test2"}), finishedRunnables); } finally { pool.stop(true); } } public void testRunnableTimeoutWithSpinLoop2() throws Exception { log.debug("testRunnableTimeoutWithSpinLoop2"); BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); pool.setBlockingMode(BlockingMode.RUN); try { TestRunnable test = new TestRunnable(BASIC, "testx", Long.MAX_VALUE); pool.run(test, 0, 1*1000); // Run another task to validate the previous thread has been cleared ArrayList tmp = new ArrayList(); for(int n = 0; n < 10; n ++) { String name = "test"+n; pool.run(new TestRunnable(BASIC, name)); tmp.add(name); } Thread.sleep(3000); assertEquals(makeExpected(tmp.toArray()), finishedRunnables); } finally { pool.stop(true); } } /** * Save the thread name * * @param data the test data * @param name the thread name */ public synchronized void saveRunnableThreadName(String data, String name) { threadNames.put(data, name); } public synchronized void waitStarted(int target) throws InterruptedException { log.info("waitStarted, target="+target); while (startedRunnables.size() < target) wait(); } /** * Release in waiting for start * * @param data the thread to start */ public synchronized void releaseStarted(String data) { log.info("releaseStarted, data="+data); startedReleases.add(data); notifyAll(); } public synchronized void waitForReleaseStarted(String data) { try { log.info("waitForReleaseStarted, data="+data); while (startedReleases.contains(data) == false) wait(); } catch (InterruptedException ignored) { } } public synchronized void notifyStarted(String data) { log.info("notifyStarted, data="+data); startedRunnables.add(data); notifyAll(); } /** * Clear started */ public synchronized void clearStarted() { log.info("clearStarted"); startedRunnables.clear(); } public synchronized void waitFinished(int target) throws InterruptedException { log.info("waitFinished, target="+target); while (finishedRunnables.size() < target) wait(); } public synchronized void notifyFinished(String data) { log.info("notifyFinished, data="+data); finishedRunnables.add(data); notifyAll(); } /** * Clear finished */ public synchronized void clearFinished() { log.info("clearFinished"); finishedRunnables.clear(); } /** * Make the expected result * * @param expected the results as an object array * @return the expected result */ public HashSet makeExpected(Object[] expected) { return new HashSet(Arrays.asList(expected)); } /** * Test runnable */ public class TestRunnable implements Runnable { /** The test to run */ private int test; /** The data for the test */ private String data; private long runSleepTime; /** * Create a new TestRunnable * * @param test the test * @param data the test data */ public TestRunnable(int test, String data) { this(test, data, 0); } public TestRunnable(int test, String data, long runSleepTime) { this.test = test; this.data = data; this.runSleepTime = runSleepTime; } /** * Runnable implementation */ public void run() { log.info("Begin run"); saveThreadName(); started(); if( runSleepTime > 0 ) { log.info("Begin spin loop"); if( runSleepTime == Long.MAX_VALUE ) { while( true ) ; } else { log.info("Begin sleep"); try { Thread.sleep(runSleepTime); } catch(InterruptedException e) { } } } finished(); log.info("End run"); } /** * Save the thread */ public void saveThreadName() { saveRunnableThreadName(data, Thread.currentThread().getName()); } /** * The test is finished */ public void started() { notifyStarted(data); if (test == HOLD_START) waitForReleaseStarted(data); } /** * The test is finished */ public void finished() { notifyFinished(data); } } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/ThreadPoolTaskUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/0000644000175000017500000003757710774222622033354 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.concurrent; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import org.jboss.util.threadpool.BasicThreadPool; import org.jboss.util.threadpool.Task; import org.jboss.logging.Logger; import junit.framework.TestCase; /** * Tests of thread pool with Tasks added to the pool * * @see org.jboss.util.threadpool.ThreadPool * @author Adrian.Brock * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class ThreadPoolTaskUnitTestCase extends TestCase { private static Logger log = Logger.getLogger(ThreadPoolTaskUnitTestCase.class); /** Basic test */ static final int BASIC = 0; /** Hold the thread after start */ static final int HOLD_START = 1; /** The accepted stats */ Stats accepted = new Stats("Accepted"); /** The rejected stats */ Stats rejected = new Stats("Rejected"); /** The started stats */ Stats started = new Stats("Started"); /** The completed stats */ Stats completed = new Stats("Completed"); /** The stopped stats */ Stats stopped = new Stats("Stopped"); /** The thread names */ HashMap threadNames = new HashMap(); /** * Create a new ThreadPoolTaskUnitTestCase * * @param name the test to run */ public ThreadPoolTaskUnitTestCase(String name) { super(name); } protected void setUp() throws Exception { log.debug("====> Starting test: " + getName()); } protected void tearDown() throws Exception { log.debug("=====> Stopping test: " + getName()); } public void testBasic() throws Exception { BasicThreadPool pool = new BasicThreadPool(); try { pool.runTask(new TestTask(BASIC, "test")); completed.wait(1); HashSet expected = makeExpected(new Object[] {"test"}); assertEquals(expected, accepted.tasks); assertEquals(expected, started.tasks); assertEquals(expected, completed.tasks); } finally { pool.stop(true); } } public void testMultipleBasic() throws Exception { BasicThreadPool pool = new BasicThreadPool(); try { pool.runTask(new TestTask(BASIC, "test1")); pool.runTask(new TestTask(BASIC, "test2")); pool.runTask(new TestTask(BASIC, "test3")); completed.wait(3); HashSet expected = makeExpected(new Object[] {"test1", "test2", "test3"}); assertEquals(expected, accepted.tasks); assertEquals(expected, started.tasks); assertEquals(expected, completed.tasks); } finally { pool.stop(true); } } public void testSimplePooling() throws Exception { BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumPoolSize(1); try { pool.runTask(new TestTask(BASIC, "test1")); completed.wait(1); pool.runTask(new TestTask(BASIC, "test2")); completed.wait(2); assertEquals(threadNames.get("test1"), threadNames.get("test2")); } finally { pool.stop(true); } } public void testMultiplePooling() throws Exception { BasicThreadPool pool = new BasicThreadPool(); try { pool.runTask(new TestTask(HOLD_START, "test1")); started.wait(1); pool.runTask(new TestTask(BASIC, "test2")); completed.wait(1); started.release("test1"); completed.wait(2); assertTrue("Shouldn't run on the same thread", threadNames.get("test1").equals(threadNames.get("test2")) == false); } finally { pool.stop(true); } } public void testMaximumPool() throws Exception { BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumPoolSize(1); try { pool.runTask(new TestTask(HOLD_START, "test1")); started.wait(1); pool.runTask(new TestTask(BASIC, "test2")); Thread.sleep(1000); assertEquals(0, completed.tasks.size()); started.release("test1"); completed.wait(2); assertEquals(makeExpected(new Object[] {"test1", "test2"}), completed.tasks); } finally { pool.stop(true); } } public void testMaximumQueue() throws Exception { BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { pool.runTask(new TestTask(HOLD_START, "test1")); started.wait(1); pool.runTask(new TestTask(BASIC, "test2")); assertEquals(0, rejected.tasks.size()); pool.runTask(new TestTask(BASIC, "test3")); assertEquals(makeExpected(new Object[] {"test3"}), rejected.tasks); started.release("test1"); completed.wait(2); assertEquals(makeExpected(new Object[] {"test1", "test2"}), completed.tasks); } finally { pool.stop(true); } } public void testCompleteTimeout() throws Exception { BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { /* Test that a task with a timeout that completes within its timeout works as expected */ TestTask task = new TestTask(HOLD_START, "test1", 0, 10*1000, Task.WAIT_NONE); pool.runTask(task); started.wait(1); started.release("test1"); completed.wait(1); /* Test a task with a timeout that does not complete within its timeout is stopped */ task = new TestTask(HOLD_START, "test2", 0, 10*1000, Task.WAIT_NONE); task.setRunSleepTime(12*1000); pool.runTask(task); started.wait(1); started.release("test2"); stopped.wait(1); completed.wait(1); // Test that another valid task completes as expected task = new TestTask(HOLD_START, "test3", 0, 0, Task.WAIT_NONE); pool.runTask(task); started.wait(1); started.release("test3"); completed.wait(1); /* Test a task with a timeout that does not complete within its timeout is stopped */ task = new TestTask(HOLD_START, "test4", 0, 10*1000, Task.WAIT_NONE); task.setRunSleepTime(12*1000); pool.runTask(task); started.wait(1); started.release("test4"); stopped.wait(1); completed.wait(1); } finally { pool.stop(true); } } public void testCompleteTimeoutWithSpinLoop() throws Exception { BasicThreadPool pool = new BasicThreadPool(); pool.setMaximumQueueSize(1); pool.setMaximumPoolSize(1); try { /* Test that a task with a timeout that completes within its timeout works as expected */ TestTask task = new TestTask(HOLD_START, "test1", 0, 10*1000, Task.WAIT_NONE); task.setRunSleepTime(Long.MAX_VALUE); pool.runTask(task); started.wait(1); started.release("test1"); stopped.wait(1); completed.wait(1); } finally { pool.stop(true); } } /** * Save the thread name * * @param data the test data * @param name the thread name */ public synchronized void saveRunnableThreadName(String data, String name) { threadNames.put(data, name); } /** * Make the expected result * * @param expected the results as an object array * @return the expected result */ public HashSet makeExpected(Object[] expected) { return new HashSet(Arrays.asList(expected)); } /** * Test task */ public class TestTask implements Task { /** The test to run */ private int test; /** The data for the test */ private String data; /** The start timeout */ private long startTimeout; /** The completion timeout */ private long completionTimeout; /** The time to sleep in execute */ private long runSleepTime; /** The wait type */ private int waitType; /** * Create a new TestTask * * @param test the test * @param data the test data */ public TestTask(int test, String data) { this(test, data, 0, Task.WAIT_NONE); } /** * Create a new TestTask * * @param test the test * @param data the test data * @param startTimeout the start timeout * @param waitType the wait type */ public TestTask(int test, String data, long startTimeout, int waitType) { this(test, data, startTimeout, 0, waitType); } public TestTask(int test, String data, long startTimeout, long completionTimeout, int waitType) { this.test = test; this.data = data; this.startTimeout = startTimeout; this.completionTimeout = completionTimeout; this.waitType = waitType; } public void execute() { saveThreadName(); log.info("Start execute"); if( runSleepTime > 0 ) { log.info("Begin spin loop"); if( runSleepTime == Long.MAX_VALUE ) { while( true ) ; } else { log.info("Begin sleep"); try { Thread.sleep(runSleepTime); } catch(InterruptedException e) { } } } log.info("End execute"); } public void saveThreadName() { saveRunnableThreadName(data, Thread.currentThread().getName()); } public void accepted(long time) { accepted.notify(data, time); } public void rejected(long time, Throwable throwable) { rejected.notify(data, time, throwable); } public void started(long time) { started.notify(data, time); if (test == HOLD_START) started.waitForRelease(data); } public void completed(long time, Throwable throwable) { completed.notify(data, time, throwable); } public long getCompletionTimeout() { return completionTimeout; } public int getPriority() { return Thread.NORM_PRIORITY; } public long getStartTimeout() { return startTimeout; } public int getWaitType() { return waitType; } public void stop() { stopped.notify(data); } public void setRunSleepTime(long runSleepTime) { this.runSleepTime = runSleepTime; } } public class Stats { /** * The name */ String name; /** The tasks */ HashSet tasks = new HashSet(); /** The times */ HashMap times = new HashMap(); /** The errors */ HashMap errors = new HashMap(); /** The releases */ HashSet releases = new HashSet(); public Stats(String name) { this.name = name; } public void wait(int target) throws InterruptedException { log.debug(Thread.currentThread().getName() + ": Waiting for " + name + " target=" + target); synchronized (ThreadPoolTaskUnitTestCase.this) { while (tasks.size() < target) ThreadPoolTaskUnitTestCase.this.wait(); log.debug(Thread.currentThread().getName() + ": Waited for " + name + " target=" + target); } } /** * Release in waiting * * @param data the thread */ public void release(String data) { log.debug(Thread.currentThread().getName() + ": Releasing " + name + " data=" + data); synchronized (ThreadPoolTaskUnitTestCase.this) { releases.add(data); ThreadPoolTaskUnitTestCase.this.notifyAll(); log.debug(Thread.currentThread().getName() + ": Released " + name + " data=" + data); } } public void waitForRelease(String data) { log.debug(Thread.currentThread().getName() + ": Waiting for release " + name + " data=" + data); synchronized (ThreadPoolTaskUnitTestCase.this) { try { while (releases.contains(data) == false) ThreadPoolTaskUnitTestCase.this.wait(); } catch (InterruptedException ignored) { } log.debug(Thread.currentThread().getName() + ": Waited for release " + name + " data=" + data); } } public void notify(String data) { log.debug(Thread.currentThread().getName() + ": Notifying " + name + " data=" + data); synchronized (ThreadPoolTaskUnitTestCase.this) { tasks.add(data); ThreadPoolTaskUnitTestCase.this.notifyAll(); log.debug(Thread.currentThread().getName() + ": Notified " + name + " data=" + data); } } public void notify(String data, long time) { log.debug(Thread.currentThread().getName() + ": Notifying " + name + " data=" + data + " time=" + time); synchronized (ThreadPoolTaskUnitTestCase.this) { tasks.add(data); times.put(data, new Long(time)); ThreadPoolTaskUnitTestCase.this.notifyAll(); } log.debug(Thread.currentThread().getName() + ": Notified " + name + " data=" + data + " time=" + time); } public void notify(String data, long time, Throwable throwable) { if (throwable != null) log.debug(Thread.currentThread().getName() + ": Notifying " + name + " data=" + data + " time=" + time, throwable); else log.debug(Thread.currentThread().getName() + ": Notifying " + name + " data=" + data + " time=" + time + " throwable=null"); synchronized (ThreadPoolTaskUnitTestCase.this) { tasks.add(data); times.put(data, new Long(time)); errors.put(data, throwable); ThreadPoolTaskUnitTestCase.this.notifyAll(); } if (throwable != null) log.debug(Thread.currentThread().getName() + ": Notified " + name + " data=" + data + " time=" + time + " throwable=" + throwable.getMessage()); else log.debug(Thread.currentThread().getName() + ": Notified " + name + " data=" + data + " time=" + time + " throwable=null"); } /** * Clear */ public void clear() { log.debug(Thread.currentThread().getName() + ": Clearing " + name); synchronized (ThreadPoolTaskUnitTestCase.this) { tasks.clear(); log.debug(Thread.currentThread().getName() + ": Cleared " + name); } } } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/TimeoutFactoryTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/0000644000175000017500000001344410614235027033333 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.concurrent; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.jboss.util.threadpool.BasicThreadPool; import org.jboss.util.threadpool.BlockingMode; import org.jboss.util.timeout.Timeout; import org.jboss.util.timeout.TimeoutFactory; import org.jboss.util.timeout.TimeoutTarget; /** * Unit tests for TimeoutFactory class. * * @author Elias Ross * @author Dimitris Andreadis * @version $Revision: 2393 $ */ public class TimeoutFactoryTestCase extends TestCase { public TimeoutFactoryTestCase(String name) { super(name); } CountDownLatch count; public void testBlocking() throws Exception { final int times = 5000; count = new CountDownLatch(times); TT tt = new TT(); for (int i = 0; i < times; i++) { TimeoutFactory.createTimeout(0, tt); } count.await(60, TimeUnit.SECONDS); assertEquals(0, count.getCount()); } public void testDefaultCtr() throws Exception { final int times = 5000; count = new CountDownLatch(times); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(); for (int i = 0; i < times; i++) { tf.schedule(0, (Runnable)tt); } count.await(60, TimeUnit.SECONDS); assertEquals(0, count.getCount()); } public void testConsecutiveTimeouts() throws Exception { final int times = 1000; count = new CountDownLatch(times); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(); long now = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 100; j++) { tf.schedule(now + i*50, (TimeoutTarget)tt); } } count.await(10, TimeUnit.SECONDS); assertEquals(0, count.getCount()); } public void testCancel() throws Exception { final int times = 100; count = new CountDownLatch(times); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(); long at = System.currentTimeMillis() + 300; for (int i = 0; i < times; i++) { Timeout t = tf.schedule(at, (TimeoutTarget)tt); t.cancel(); } count.await(5, TimeUnit.SECONDS); assertEquals(times, count.getCount()); } public void testCancelFactory() throws Exception { final int times = 100; count = new CountDownLatch(times); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(); long at = System.currentTimeMillis() + 300; for (int i = 0; i < times; i++) { tf.schedule(at, (TimeoutTarget)tt); } tf.cancel(); count.await(5, TimeUnit.SECONDS); assertEquals(times, count.getCount()); } public void testBlockingSmallThreadPool() throws Exception { final int times = 100; count = new CountDownLatch(times); BasicThreadPool tp = new BasicThreadPool(); tp.setMaximumQueueSize(1); tp.setMaximumPoolSize(1); tp.setBlockingMode(BlockingMode.RUN); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(tp); for (int i = 0; i < times; i++) { tf.schedule(0, (TimeoutTarget)tt); } count.await(10, TimeUnit.SECONDS); assertEquals(0, count.getCount()); } public void testAbortingSmallThreadPool() throws Exception { final int times = 50; count = new CountDownLatch(times); BasicThreadPool tp = new BasicThreadPool(); tp.setMaximumQueueSize(1); tp.setMaximumPoolSize(1); TT tt = new TT(); TimeoutFactory tf = new TimeoutFactory(tp); for (int i = 0; i < times; i++) { tf.schedule(0, (TimeoutTarget)tt); } count.await(5, TimeUnit.SECONDS); assertTrue("Executed " + count.getCount() + " < scheduled " + times, count.getCount() < times); } public void testFailedTarget() throws Exception { final int times = 50; count = new CountDownLatch(times); TimeoutFactory tf = new TimeoutFactory(); TT tt = new TT(); tt.fail = true; for (int i = 0; i < times; i++) { tf.schedule(0, (TimeoutTarget)tt); } Thread.sleep(500); assertEquals(times, count.getCount()); } class TT implements TimeoutTarget, Runnable { boolean fail; public void timedOut(Timeout timeout) { assertTrue(timeout != null); run(); } public void run() { if (fail) throw new Error("Fail"); try { Thread.sleep(10); } catch (InterruptedException e) { } count.countDown(); } } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/ThreadPoolInterruptedThreadUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/concurrent/0000644000175000017500000000426210774225552033342 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.concurrent; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.jboss.util.threadpool.BasicThreadPool; /** * Tests of thread pool with Tasks added to the pool * * @see org.jboss.util.threadpool.ThreadPool * @author Adrian.Brock * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ public class ThreadPoolInterruptedThreadUnitTestCase extends TestCase { public ThreadPoolInterruptedThreadUnitTestCase(String name) { super(name); } public static class TestRunnable implements Runnable { public CountDownLatch latch = new CountDownLatch(1); public void run() { latch.countDown(); } } public void testInterruptedExecute() throws Exception { BasicThreadPool pool = new BasicThreadPool(); TestRunnable runnable = new TestRunnable(); Thread.currentThread().interrupt(); try { pool.run(runnable); } finally { assertTrue(Thread.interrupted()); } assertTrue(runnable.latch.await(10, TimeUnit.SECONDS)); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000755000175000017500000000000011105642362033274 5ustar twernertwerner././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/AbstractSetUnitTest.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000125111042105117033265 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Iterator; import java.util.Set; import junit.framework.TestCase; /** * Unit tests for WeakSet * * @author Sven Meier * @author Ales Justin * @version $Revision: 43534 $ */ @SuppressWarnings("unchecked") public abstract class AbstractSetUnitTest extends TestCase { protected abstract Set createSet(); public void testMultipleHasNext() { Set set = createSet(); set.add(new Object()); Iterator iterator = set.iterator(); assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); } }././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/WeakSetUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000073611042105117033274 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Set; import org.jboss.util.collection.WeakSet; /** * Unit tests for WeakSet * * @author Sven Meier * @author Ales Justin * @version $Revision: 43534 $ */ @SuppressWarnings("unchecked") public class WeakSetUnitTestCase extends AbstractNullableSetUnitTest { protected Set createSet() { return new WeakSet(); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/AbstractMapUnitTest.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000435211103542066033300 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Collections; import java.util.Date; import java.util.Map; import junit.framework.TestCase; /** * Unit tests for custom maps. * * @author Ales Justin */ public abstract class AbstractMapUnitTest extends TestCase { protected abstract Map createEmptyMap(); @SuppressWarnings("unchecked") public void testBasicOperations() throws Exception { Map map = createEmptyMap(); assertTrue(map.isEmpty()); assertEquals(0, map.size()); String key1 = "date1"; Date value1 = new Date(); map.put(key1, value1); assertTrue(map.containsKey(key1)); assertTrue(map.containsValue(value1)); assertEquals(1, map.size()); String key2 = "date2"; Date value2 = new Date(); map.put(key2, value2); assertTrue(map.containsKey(key2)); assertTrue(map.containsValue(value2)); assertEquals(2, map.size()); String key3 = "date3"; Date value3 = new Date(); map.put(key3, value3); assertTrue(map.containsKey(key1)); assertTrue(map.containsValue(value1)); assertEquals(3, map.size()); map.clear(); assertTrue(map.isEmpty()); key1 = "date1"; value1 = new Date(); map.put(key1, value1); map.remove(key1); assertTrue(map.isEmpty()); map.putAll(Collections.singletonMap(key1, value1)); assertEquals(value1, map.get(key1)); assertEquals(Collections.singletonMap(key1, value1), map); // iterables Iterable keys = map.keySet(); assertIterable(keys, String.class); Iterable values = map.values(); assertIterable(values, Date.class); Iterable entries = map.entrySet(); Map.Entry entry = assertIterable(entries, Map.Entry.class); assertEquals(key1, entry.getKey()); assertEquals(value1, entry.getValue()); } protected T assertIterable(Iterable iter, Class clazz) { assertTrue(iter.iterator().hasNext()); T next = iter.iterator().next(); assertTrue("Next " + next + " is not instance of " + clazz.getName(), clazz.isInstance(next)); assertNotNull(next); return next; } }././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/LazySetUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000063711103542066033302 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Set; import org.jboss.util.collection.CollectionsFactory; /** * Unit tests for ConcurrentSet * * @author Ales Justin */ @SuppressWarnings("unchecked") public class LazySetUnitTestCase extends AbstractSetUnitTest { protected Set createSet() { return CollectionsFactory.createLazySet(); } }././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/SoftValueTreeMapUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000260211103262257033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.collection; import java.util.Map; import org.jboss.util.collection.SoftValueTreeMap; /** * SoftValueTreeMap test. * * @author Ales Justin */ public class SoftValueTreeMapUnitTestCase extends AbstractMapUnitTest { protected Map createEmptyMap() { return new SoftValueTreeMap(); } }././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/WeakValueHashMapUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000260211103262257033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.collection; import java.util.Map; import org.jboss.util.collection.WeakValueHashMap; /** * WeakValueHashMap test. * * @author Ales Justin */ public class WeakValueHashMapUnitTestCase extends AbstractMapUnitTest { protected Map createEmptyMap() { return new WeakValueHashMap(); } }././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/SoftValueHashMapUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000260511103262257033300 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.collection; import java.util.Map; import org.jboss.util.collection.SoftValueHashMap; /** * SoftValueHashMap test. * * @author Ales Justin */ public class SoftValueHashMapUnitTestCase extends AbstractMapUnitTest { protected Map createEmptyMap() { return new SoftValueHashMap(); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/LazyMapUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000260711103542066033301 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.collection; import java.util.Map; import org.jboss.util.collection.CollectionsFactory; /** * SoftValueHashMap test. * * @author Ales Justin */ public class LazyMapUnitTestCase extends AbstractMapUnitTest { protected Map createEmptyMap() { return CollectionsFactory.createLazyMap(); } }././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/WeakValueTreeMapUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000260211103262257033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.collection; import java.util.Map; import org.jboss.util.collection.WeakValueTreeMap; /** * WeakValueTreeMap test. * * @author Ales Justin */ public class WeakValueTreeMapUnitTestCase extends AbstractMapUnitTest { protected Map createEmptyMap() { return new WeakValueTreeMap(); } }././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/ConcurrentSetUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000062111042105117033265 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Set; import org.jboss.util.collection.ConcurrentSet; /** * Unit tests for ConcurrentSet * * @author Ales Justin */ @SuppressWarnings("unchecked") public class ConcurrentSetUnitTestCase extends AbstractSetUnitTest { protected Set createSet() { return new ConcurrentSet(); } }././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/AbstractNullableSetUnitTest.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/collection/0000644000175000017500000000131211042105117033263 0ustar twernertwernerpackage org.jboss.test.util.test.collection; import java.util.Iterator; import java.util.Set; /** * Unit tests for WeakSet * * @author Sven Meier * @author Ales Justin * @version $Revision: 43534 $ */ @SuppressWarnings("unchecked") public abstract class AbstractNullableSetUnitTest extends AbstractSetUnitTest { protected abstract Set createSet(); public void testNullElement() { Set set = createSet(); set.add(null); assertEquals(1, set.size()); Iterator iterator = set.iterator(); assertTrue(iterator.hasNext()); iterator.next(); assertFalse(iterator.hasNext()); } }libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/stream/0000755000175000017500000000000011105642362032434 5ustar twernertwerner././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/stream/MarshallValueStreamTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/stream/Mars0000644000175000017500000000302111054755361033264 0ustar twernertwernerpackage org.jboss.test.util.test.stream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import junit.framework.TestCase; import org.jboss.util.stream.MarshalledValueInputStream; import org.jboss.util.stream.MarshalledValueOutputStream; /** * Test MarshalledValueInput/OutputStream * * @see org.jboss.util.propertyeditor.PropertyEditors * * @author Jason.Greene@jboss.org * @version $Revision: 2904 $ */ public class MarshallValueStreamTestCase extends TestCase { public void testArrayMarshall() throws Exception { Byte[] bytes = new Byte[] {1, 2, 3}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); MarshalledValueOutputStream os = new MarshalledValueOutputStream(baos); os.writeObject(bytes); os.flush(); MarshalledValueInputStream is = new MarshalledValueInputStream(new ByteArrayInputStream(baos.toByteArray())); assertTrue(Arrays.equals(bytes, (Byte[]) is.readObject())); } public void testPrimitive() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(int.class); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); MarshalledValueInputStream mvis = new MarshalledValueInputStream(bais); Object o = mvis.readObject(); assertNotNull(o); assertEquals(o, int.class); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/ObjectsUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/ObjectsUnit0000644000175000017500000000531011103542066033312 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test; import java.util.Date; import junit.framework.TestCase; import org.jboss.util.Objects; /** * @author Ales Justin */ public class ObjectsUnitTestCase extends TestCase { public void testEquals() throws Exception { assertTrue(Objects.equals("123", "123")); Object first = new String[]{"123", "321"}; Object second = new String[]{"123", "321"}; assertTrue(Objects.equals(first, second)); first = new String[][]{{"1", "2"}, {"1", "2"}}; second = new String[][]{{"1", "2"}, {"1", "2"}}; assertTrue(Objects.equals(first, second)); assertFalse(Objects.equals("129", "123")); first = new String[]{"123", "324"}; second = new String[]{"123", "321"}; assertFalse(Objects.equals(first, second)); first = new String[][]{{"1", "6"}, {"1", "2"}}; second = new String[][]{{"1", "2"}, {"1", "2"}}; assertFalse(Objects.equals(first, second)); first = new int[]{1, 2, 3}; second = new int[]{1, 2, 3}; assertTrue(Objects.equals(first, second)); first = new int[][]{{1, 2}, {1, 2}}; second = new int[][]{{1, 2}, {1, 2}}; assertTrue(Objects.equals(first, second)); first = new int[]{1, 2, 4}; second = new int[]{1, 2, 3}; assertFalse(Objects.equals(first, second)); first = new int[][]{{1, 6}, {1, 2}}; second = new int[][]{{1, 2}, {1, 2}}; assertFalse(Objects.equals(first, second)); assertFalse(Objects.equals("123", new int[]{1, 2, 3})); assertFalse(Objects.equals(new int[]{1, 2, 3}, "123")); assertFalse(Objects.equals(new Date(), 123)); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/ClassesUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/ClassesUnit0000644000175000017500000000211010774222622033317 0ustar twernertwernerpackage org.jboss.test.util.test; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.jboss.util.Classes; /** * Unit tests for org.jboss.util.Classes utility * * @author Dimitris.Andreadis@jboss.org * @version $Revision: 43534 $ */ public class ClassesUnitTestCase extends TestCase { public void testGetAllInterfaces() { List> list = new ArrayList>(); Classes.getAllInterfaces(list, ExtendedClass.class); assertEquals(3, list.size()); assertEquals(Interface1.class, list.get(0)); assertEquals(Interface1.class, list.get(1)); assertEquals(Interface2.class, list.get(2)); } public void testGetAllUniqueInterfaces() { Class[] interfaces = Classes.getAllUniqueInterfaces(ExtendedClass.class); assertEquals(2, interfaces.length); } public interface Interface1 {} public interface Interface2 {} public static class BaseClass implements Interface1, Interface2 {} public static class ExtendedClass extends BaseClass implements Interface1 {} } libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/0000755000175000017500000000000011105642362032556 5ustar twernertwerner././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/ConstructorTCCLClassLoaderSourceUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/Con0000644000175000017500000000431310774222622033225 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.loading; import org.jboss.util.loading.ClassLoaderSource; import org.jboss.util.loading.ConstructorTCCLClassLoaderSource; /** * Unit tests of {@link ConstructorTCCLClassLoaderSource}. * * @author Brian Stansberry */ public class ConstructorTCCLClassLoaderSourceUnitTestCase extends ClassLoaderSourceTestBase { public ConstructorTCCLClassLoaderSourceUnitTestCase(String name) { super(name); } @Override protected ClassLoaderSource createClassLoaderSource() { return new ConstructorTCCLClassLoaderSource(); } @Override protected ClassLoader getExpectedClassLoader(ClassLoader tccl) { return tccl; } /** * Tests that the ClassLoaderSource does not prevent garbage collection of * the classloader. */ public void testGarbageCollectedClassLoader() { ClassLoader cl = getExtendedClassLoader(); Thread.currentThread().setContextClassLoader(cl); ClassLoaderSource cls = createClassLoaderSource(); Thread.currentThread().setContextClassLoader(origCl); cl = null; System.gc(); assertNull("ClassLoader garbage collected", cls.getClassLoader()); } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/ClassLoaderSourceTestBase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/Cla0000644000175000017500000000675710774161402033221 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.loading; import junit.framework.TestCase; import org.jboss.util.loading.ClassLoaderSource; /** * Base class for testing {@link ClassLoaderSource} implementations. * * @author Brian Stansberry */ public abstract class ClassLoaderSourceTestBase extends TestCase { protected ClassLoader origCl; /** * @param name */ public ClassLoaderSourceTestBase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); origCl = Thread.currentThread().getContextClassLoader(); } @Override protected void tearDown() throws Exception { try { super.tearDown(); } finally { Thread.currentThread().setContextClassLoader(origCl); } } protected abstract ClassLoaderSource createClassLoaderSource(); protected abstract ClassLoader getExpectedClassLoader(ClassLoader tccl); /** * Tests that the ClassLoaderSource returns the expected classloader * when the TCCL is null. */ public void testNullTCCL() { checkCorrectClassLoaderSource(null); } /** * Tests that the ClassLoaderSource returns the expected classloader * when the TCCL is the basic one in place when this test is executed. */ public void testOriginalTCCL() { checkCorrectClassLoaderSource(origCl); } /** * Tests that the ClassLoaderSource returns the expected classloader * when the TCCL is the CLS impl's own classloader. */ public void testImplClassLoader() { checkCorrectClassLoaderSource(createClassLoaderSource().getClass().getClassLoader()); } /** * Tests that the ClassLoaderSource returns the expected classloader * when the TCCL is a child classloader. */ public void testDifferentTCCL() { checkCorrectClassLoaderSource(getExtendedClassLoader()); } protected void checkCorrectClassLoaderSource(ClassLoader tccl) { Thread.currentThread().setContextClassLoader(tccl); ClassLoaderSource cls = createClassLoaderSource(); assertSame("ClassLoaderSource returned expected cl", getExpectedClassLoader(tccl), cls.getClassLoader()); } protected ClassLoader getExtendedClassLoader() { return new ExtendedClassLoader(origCl); } private class ExtendedClassLoader extends ClassLoader { ExtendedClassLoader(ClassLoader parent) { super(parent); } } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/MyClassLoaderClassLoaderSourceUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/loading/MyC0000644000175000017500000000334710772776222033214 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.loading; import org.jboss.util.loading.ClassLoaderSource; import org.jboss.util.loading.MyClassLoaderClassLoaderSource; /** * Unit tests of {@link MyClassLoaderClassLoaderSource}. * * @author Brian Stansberry */ public class MyClassLoaderClassLoaderSourceUnitTestCase extends ClassLoaderSourceTestBase { public MyClassLoaderClassLoaderSourceUnitTestCase(String name) { super(name); } @Override protected ClassLoaderSource createClassLoaderSource() { return new MyClassLoaderClassLoaderSource(); } @Override protected ClassLoader getExpectedClassLoader(ClassLoader tccl) { return MyClassLoaderClassLoaderSource.class.getClassLoader(); } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/StringPropertyReplacerUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/StringPrope0000644000175000017500000002251711103042136033336 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test; import java.util.Properties; import junit.framework.TestCase; import static org.jboss.util.StringPropertyReplacer.replaceProperties; /** * A StringPropertyReplacerUnitTestCase. * * @author Brian Stansberry * @version $Revision$ */ public class StringPropertyReplacerUnitTestCase extends TestCase { private static final String PROP_A = "string.prop.replace.test.a"; private static final String PROP_B = "string.prop.replace.test.b"; private static final String PROP_C = "string.prop.replace.test.c"; private static final String PROP_D = "string.prop.replace.test.d"; private static final String DEFAULT = "DEFAULT"; private static final String VALUE = "VALUE"; private static final String WRAPPER = "wrapper"; @Override protected void tearDown() throws Exception { super.tearDown(); System.clearProperty(PROP_A); System.clearProperty(PROP_B); System.clearProperty(PROP_C); System.clearProperty(PROP_D); } private static Properties setupProperties() { Properties props = new Properties(); props.put(PROP_A, VALUE); props.put(PROP_C, VALUE); return props; } private static void setupSystemProperties() { System.setProperty(PROP_A, VALUE); System.setProperty(PROP_C, VALUE); } public void testNullInput() { try { assertNull(replaceProperties(null)); fail("NPE expected with null input"); } catch (NullPointerException good) {} try { assertNull(replaceProperties(null, setupProperties())); fail("NPE expected with null input"); } catch (NullPointerException good) {} } public void testBasicReplacement() { basicReplacementTest(false); } public void testBasicReplacementFromSystemProps() { basicReplacementTest(true); } private void basicReplacementTest(boolean useSysProps) { String input = "${"+PROP_A+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(VALUE, output); } public void testWrappedReplacement() { wrappedReplacementTest(false); } public void testWrappedReplacementFromSystemProps() { wrappedReplacementTest(true); } private void wrappedReplacementTest(boolean useSysProps) { String input = WRAPPER+"${"+PROP_A+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(WRAPPER+VALUE, output); input = "${"+PROP_A+"}"+WRAPPER; output = null; if (useSysProps) { output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(VALUE+WRAPPER, output); input = WRAPPER+"${"+PROP_A+"}"+WRAPPER; output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(WRAPPER+VALUE+WRAPPER, output); } public void testMissingProperty() { missingPropertyTest(false); } public void testMissingPropertyFromSystemProps() { missingPropertyTest(true); } private void missingPropertyTest(boolean useSysProps) { String input = WRAPPER+"${"+PROP_B+"}"+WRAPPER; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(input, output); } public void testWrappedMissingProperty() { wrappedMissingPropertyTest(false); } public void testWrappedMissingPropertyFromSystemProps() { wrappedMissingPropertyTest(true); } private void wrappedMissingPropertyTest(boolean useSysProps) { String input = WRAPPER+"${"+PROP_B+"}"+WRAPPER; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(input, output); } public void testDefaultValue() { defaultValueTest(false); } public void testDefaultValueFromSystemProps() { defaultValueTest(true); } private void defaultValueTest(boolean useSysProps) { String input = "${"+PROP_B+":"+DEFAULT+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(DEFAULT, output); } public void testSecondaryProperty() { secondaryPropertyTest(false); } public void testSecondaryPropertyFromSystemProps() { secondaryPropertyTest(true); } private void secondaryPropertyTest(boolean useSysProps) { String input = "${"+PROP_B+","+PROP_C+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(VALUE, output); } public void testSecondaryPropertyAndDefault() { secondaryPropertyAndDefaultTest(false); } public void testSecondaryPropertyAndDefaultFromSystemProps() { secondaryPropertyAndDefaultTest(true); } private void secondaryPropertyAndDefaultTest(boolean useSysProps) { String input = "${"+PROP_B+","+PROP_D+":"+DEFAULT+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(DEFAULT, output); } public void testSecondaryPropertyAndMissing() { secondaryPropertyAndMissingTest(false); } public void testSecondaryPropertyAndMissingFromSystemProps() { secondaryPropertyAndMissingTest(true); } private void secondaryPropertyAndMissingTest(boolean useSysProps) { String input = "${"+PROP_B+","+PROP_D+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(input, output); } public void testMultipleReplacements() { multipleReplacementTest(false); } public void testMultipleReplacementsFromSystemProps() { multipleReplacementTest(true); } private void multipleReplacementTest(boolean useSysProps) { String input = "${"+PROP_A+"}${"+PROP_C+"}"; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(VALUE+VALUE, output); } public void testPartialMissing() { partialMissingTest(false); } public void testPartialMissingFromSystemProps() { partialMissingTest(true); } private void partialMissingTest(boolean useSysProps) { String badinput = "${"+PROP_B+"}"; String input = WRAPPER+"${"+PROP_A+"}"+badinput+"${"+PROP_C+"}"+WRAPPER; String output = null; if (useSysProps) { setupSystemProperties(); output = replaceProperties(input); } else { output = replaceProperties(input, setupProperties()); } assertEquals(WRAPPER+VALUE+badinput+VALUE+WRAPPER, output); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/propertyeditor/libjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/propertyedi0000755000175000017500000000000011105642362033430 5ustar twernertwerner././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/propertyeditor/PropertyEditorsUnitTestCase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/test/java/org/jboss/test/util/test/propertyedi0000644000175000017500000004575311103542066033446 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util.test.propertyeditor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.io.File; import java.net.InetAddress; import java.net.URI; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.Locale; import java.util.Properties; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import junit.framework.TestCase; import org.jboss.logging.Logger; import org.jboss.util.propertyeditor.DateEditor; import org.jboss.util.propertyeditor.DocumentEditor; import org.jboss.util.propertyeditor.ElementEditor; import org.jboss.util.propertyeditor.PropertyEditors; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Unit tests for the custom JBoss property editors * * @see org.jboss.util.propertyeditor.PropertyEditors * * @author Scott.Stark@jboss.org * @author Dimitris.Andreadis@jboss.org * @author Ales.Justin@jboss.org * @version $Revision: 43534 $ */ @SuppressWarnings("unchecked") public class PropertyEditorsUnitTestCase extends TestCase { private static Logger log = Logger.getLogger(PropertyEditorsUnitTestCase.class); Calendar calendar = Calendar.getInstance(); private Locale locale; /** Augment the PropertyEditorManager search path to incorporate the JBoss specific editors. This simply references the PropertyEditors.class to invoke its static initialization block. */ static { PropertyEditors.init(); String[] paths = PropertyEditorManager.getEditorSearchPath(); log.info(Arrays.asList(paths)); } static class StringArrayComparator implements Comparator { public int compare(Object o1, Object o2) { String[] a1 = (String[]) o1; String[] a2 = (String[]) o2; int compare = a1.length - a2.length; for(int n = 0; n < a1.length; n ++) compare += a1[n].compareTo(a2[n]); return compare; } } static class ClassArrayComparator implements Comparator { public int compare(Object o1, Object o2) { Class[] a1 = (Class[]) o1; Class[] a2 = (Class[]) o2; int compare = a1.length - a2.length; for(int n = 0; n < a1.length; n ++) { int hash1 = a1[n].hashCode(); int hash2 = a2[n].hashCode(); compare += hash1 - hash2; } return compare; } } static class IntArrayComparator implements Comparator { public int compare(Object o1, Object o2) { int[] a1 = (int[]) o1; int[] a2 = (int[]) o2; int compare = a1.length - a2.length; for(int n = 0; n < a1.length; n ++) compare += a1[n] - a2[n]; return compare; } } static class NumberComparator implements Comparator { public int compare(Number o1, Number o2) { return o1.intValue() - o2.intValue(); } } static class ToStringComparator implements Comparator { public int compare(Object o1, Object o2) { String s1 = o1.toString(); String s2 = o2.toString(); return s1.compareTo(s2); } } public PropertyEditorsUnitTestCase(String name) { super(name); } protected void setUp() throws Exception { locale = Locale.getDefault(); Locale.setDefault(Locale.US); super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); Locale.setDefault(locale); } public void testEditorSearchPath() throws Exception { log.debug("+++ testEditorSearchPath"); String[] searchPath = PropertyEditorManager.getEditorSearchPath(); boolean foundJBossPath = false; for(int p = 0; p < searchPath.length; p ++) { String path = searchPath[p]; log.debug("path["+p+"]="+path); foundJBossPath |= path.equals("org.jboss.util.propertyeditor"); } assertTrue("Found org.jboss.util.propertyeditor in search path", foundJBossPath); } /** The mechanism for mapping java.lang.* variants of the primative types misses editors for java.lang.Boolean and java.lang.Integer. Here we test the java.lang.* variants we expect editors for. * @throws Exception **/ public void testJavaLangEditors() throws Exception { log.debug("+++ testJavaLangEditors"); // The supported java.lang.* types Class[] types = { Boolean.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Byte.class, Character.class, }; // The input string data for each type String[][] inputData = { {"true", "false", "TRUE", "FALSE", "tRuE", "FaLsE", null}, {"1", "-1", "0", "0x1A"}, {"1", "-1", "0", "0xA0"}, {"1", "-1", "0", "0xA0"}, {"1", "-1", "0", "1000"}, {"1", "-1", "0", "1000.1"}, {"1", "-1", "0", "1000.1"}, {"0x1", "-#1", "0"}, {"A", "a", "Z", "z"}, }; // The expected java.lang.* instance for each inputData value Object[][] expectedData = { {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null}, {Byte.valueOf("1"), Byte.valueOf("-1"), Byte.valueOf("0"), Byte.decode("0x1A")}, {Short.valueOf("1"), Short.valueOf("-1"), Short.valueOf("0"), Short.decode("0xA0")}, {Integer.valueOf("1"), Integer.valueOf("-1"), Integer.valueOf("0"), Integer.decode("0xA0")}, {Long.valueOf("1"), Long.valueOf("-1"), Long.valueOf("0"), Long.valueOf("1000")}, {Float.valueOf("1"), Float.valueOf("-1"), Float.valueOf("0"), Float.valueOf("1000.1")}, {Double.valueOf("1"), Double.valueOf("-1"), Double.valueOf("0"), Double.valueOf("1000.1")}, {Byte.valueOf("1"), Byte.valueOf("-1"), Byte.valueOf("0")}, {new Character('A'), new Character('a'), new Character('Z'), new Character('z')}, }; // The expected string output from getAsText() String[][] expectedStringData = { {"true", "false", "true", "false", "true", "false", "null"}, {"1", "-1", "0", "26"}, {"1", "-1", "0", "160"}, {"1", "-1", "0", "160"}, {"1", "-1", "0", "1000"}, {"1.0", "-1.0", "0.0", "1000.1"}, {"1.0", "-1.0", "0.0", "1000.1"}, {"1", "-1", "0"}, {"A", "a", "Z", "z"}, }; Comparator[] comparators = new Comparator[types.length]; doTests(types, inputData, expectedData, expectedStringData, comparators); } /** Test custom JBoss property editors. * @throws Exception */ public void testJBossEditors() throws Exception { log.debug("+++ testJBossEditors"); Class[] types = { java.io.File.class, java.net.URL.class, java.net.URI.class, java.lang.String.class, java.lang.Class.class, InetAddress.class, String[].class, Class[].class, int[].class, Date.class, java.util.Properties.class, Locale.class, AtomicInteger.class, AtomicLong.class, AtomicBoolean.class, }; // The input string data for each type String[][] inputData = { // java.io.File.class {"/tmp/test1", "/tmp/subdir/../test2"}, // java.net.URL.class {"http://www.jboss.org", "file:/path with space/tst.xml"}, // java.net.URI.class {"http://www.jboss.org", "file:/path with space/tst.xml"}, // java.lang.String.class {"JBoss, Home of Professional Open Source"}, // java.lang.Class.class {"java.util.Arrays"}, // InetAddress.class, localhost must be defined for this to work {"127.0.0.1", "localhost"}, // String[].class {"1,2,3", "a,b,c", "", "#,%,\\,,.,_$,\\,v"}, // Class[].class {"java.lang.Integer,java.lang.Float"}, // int[].class {"0,#123,-123"}, // Date.class {"Jan 4, 2005", "Tue Jan 4 23:38:21 PST 2005", "Tue, 04 Jan 2005 23:38:48 -0800"}, // java.util.Properties.class {"prop1=value1\nprop2=value2\nprop3=value3\nprop32=${prop3}\nprop4=${user.home}\nprop5=${some.win32.path}"}, {Locale.getDefault().toString(), "ja_JP"}, {"-1", "0", "1"}, {"-1", "0", "1"}, {"true", "false"}, }; // The expected instance for each inputData value calendar.set(2005, 0, 4, 0, 0, 0); calendar.set(Calendar.MILLISECOND, 0); Date date1 = calendar.getTime(); calendar.setTimeZone(TimeZone.getTimeZone("PST")); calendar.set(2005, 0, 4, 23, 38, 21); Date date2 = calendar.getTime(); calendar.set(2005, 0, 4, 23, 38, 48); Date date3 = calendar.getTime(); Properties props = new Properties(); props.setProperty("prop1", "value1"); props.setProperty("prop2", "value2"); props.setProperty("prop3", "value3"); props.setProperty("prop32", "value3"); props.setProperty("prop4", System.getProperty("user.home")); System.setProperty("some.win32.path", "C:\\disk1\\root\\"); props.setProperty("prop5", "C:\\disk1\\root\\"); Object[][] expectedData = { {new File("/tmp/test1").getCanonicalFile(), new File("/tmp/test2").getCanonicalFile()}, {new URL("http://www.jboss.org"), new File("/path with space/tst.xml").getCanonicalFile().toURI().toURL()}, {new URI("http://www.jboss.org"), new File("/path with space/tst.xml").getCanonicalFile().toURI()}, {new String("JBoss, Home of Professional Open Source")}, {java.util.Arrays.class}, {InetAddress.getByName("127.0.0.1"), InetAddress.getByName("localhost")}, {new String[]{"1", "2", "3"}, new String[] {"a", "b", "c"}, new String[]{}, new String[]{"#","%",",",".","_$", ",v"}}, {new Class[]{Integer.class, Float.class}}, {new int[]{0, 0x123, -123}}, {date1, date2, date3}, {props}, {Locale.getDefault(), Locale.JAPAN}, {new AtomicInteger(-1), new AtomicInteger(0), new AtomicInteger(1)}, {new AtomicLong(-1), new AtomicLong(0), new AtomicLong(1)}, {new AtomicBoolean(true), new AtomicBoolean(false)}, }; // The expected string output from getAsText() String[][] expectedStringData = { // java.io.File.class {"/tmp/test1", "/tmp/subdir/../test2"}, // java.net.URL.class {"http://www.jboss.org", "file:/path with space/tst.xml"}, // java.net.URI.class {"http://www.jboss.org", "file:/path with space/tst.xml"}, // java.lang.String.class {"JBoss, Home of Professional Open Source"}, // java.lang.Class.class {"java.util.Arrays"}, // InetAddress.class, localhost must be defined for this to work {"127.0.0.1", "localhost"}, // String[].class {"1,2,3", "a,b,c", "", "#,%,\\,,.,_$,,v"}, // Class[].class {"java.lang.Integer,java.lang.Float"}, // int[].class {"0,291,-123"}, // Date.class {"Jan 4, 2005", "Tue Jan 4 23:38:21 PST 2005", "Tue, 04 Jan 2005 23:38:48 -0800"}, // java.util.Properties.class {props.toString()}, {Locale.getDefault().toString(), Locale.JAPAN.toString()}, {"-1", "0", "1"}, {"-1", "0", "1"}, {"true", "false"}, }; // The Comparator for non-trival types Comparator[] comparators = { null, // File null, // URL null, // URI null, // String null, // Class null, // InetAddress new StringArrayComparator(), // String[] new ClassArrayComparator(), // Class[] new IntArrayComparator(), // int[] null, // Date null, // Properties null, // Locale new NumberComparator(), new NumberComparator(), new ToStringComparator(), }; doTests(types, inputData, expectedData, expectedStringData, comparators); } public void testDateEditor() throws Exception { log.debug("+++ testDateEditor"); Locale locale = Locale.getDefault(); try { // Use the default locale log.debug("Current Locale: " + Locale.getDefault()); // An important date String text = "Fri, 25 Jun 1971 00:30:00 +0200"; DateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); Date date = format.parse(text); PropertyEditor editor = new DateEditor(); editor.setAsText(text); log.debug("setAsText('" + text + "') --> getValue() = '" + editor.getValue() + "'"); assertTrue("Compare date1: " + date + ", date2: " + editor.getValue(), date.compareTo((Date)editor.getValue()) == 0); editor.setValue(date); log.debug("setValue('" + date + "') --> getAsText() - '" + editor.getAsText() + "'"); Date date2 = format.parse(editor.getAsText()); assertTrue("Compare date1: " + date + ", date2: " + date2, date.compareTo(date2) == 0); // Try in French Locale.setDefault(Locale.FRENCH); log.debug("Current Locale: " + Locale.getDefault()); DateEditor.initialize(); // An important date text = "ven., 25 juin 1971 00:30:00 +0200"; format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); date = format.parse(text); editor = new DateEditor(); editor.setAsText(text); log.debug("setAsText('" + text + "') --> getValue() = '" + editor.getValue() + "'"); assertTrue("Compare date1: " + date + ", date2: " + editor.getValue(), date.compareTo((Date)editor.getValue()) == 0); editor.setValue(date); log.debug("setValue('" + date + "') --> getAsText() = '" + editor.getAsText() + "'"); date2 = format.parse(editor.getAsText()); assertTrue("Compare date1: " + date + ", date2: " + date2, date.compareTo(date2) == 0); } finally { // reset locale Locale.setDefault(locale); DateEditor.initialize(); } } /** * Tests the DOM Document and Element editors. */ public void testDocumentElementEditors() { log.debug("+++ testDocumentElementEditors"); DocumentEditor de = new DocumentEditor(); // Comments can appear outside of a document String s = ""; log.debug("setAsText '" + s + "'"); de.setAsText(s); log.debug("Parsed XML document:"); log((Node)de.getValue(), " "); log.debug("getAsText '" + de.getAsText() + "'"); assertTrue("Document :\n" + de.getAsText(), de.getAsText().trim().endsWith(s)); assertTrue(de.getValue() instanceof org.w3c.dom.Document); // Test whitespace preservation s = "\n\n testing\n\n"; de.setAsText(s); assertTrue("Document :\n" + de.getAsText() + "\nvs\n" + s, de.getAsText().trim().endsWith(s)); ElementEditor ee = new ElementEditor(); s = "text"; ee.setAsText(s); assertEquals(s, ee.getAsText()); assertTrue(ee.getValue() instanceof org.w3c.dom.Element); } private void doTests(Class[] types, String[][] inputData, Object[][] expectedData, String[][] expectedStringData, Comparator[] comparators) { for(int t = 0; t < types.length; t ++) { Class type = types[t]; log.debug("Checking property editor for: "+type); PropertyEditor editor = PropertyEditorManager.findEditor(type); assertTrue("Found property editor for: "+type, editor != null); log.debug("Found property editor for: "+type+", editor="+editor.getClass().getName()); assertEquals(editor+" input length", inputData[t].length, expectedData[t].length); for(int i = 0; i < inputData[t].length; i ++) { String input = inputData[t][i]; editor.setAsText(input); Object expected = expectedData[t][i]; Object output = editor.getValue(); Comparator c = comparators[t]; boolean equals = false; if (c == null) { equals = output != null ? output.equals(expected) : expected == null; } else { equals = c.compare(output, expected) == 0; } if( equals == false ) System.err.println(output+" != "+input); assertTrue("Transform("+editor+") of "+input+" equals "+expected+", output="+output, equals); String expectedStringOutput = expectedStringData[t][i]; String stringOutput = editor.getAsText(); log.debug("setAsText '" + logString(input) + "'"); log.debug("getAsText '" + logString(stringOutput) + "'"); if( type != Properties.class ) { // We can't meaningfully compare the PropertiesEditor string output String msg = "PropertyEditor: " + editor.getClass().getName() + ", getAsText() == expectedStringOutput '"; assertEquals(msg, expectedStringOutput, stringOutput); } } } } /** * Log a Node hierarchy */ private void log(Node node, String indent) { String name = node.getNodeName(); String value = node.getNodeValue(); log.debug(indent + "Name=" + name + ", Value=" + value); NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) log(list.item(i), indent + indent); } private static String logString(String s) { return s != null ? s : ""; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/0000755000175000017500000000000011105642362025410 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/tst-config_5.xsd0000644000175000017500000000043010776055124030435 0ustar twernertwerner ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/JBossEntityResolverUnitTestCase_testResolveRedefine_redefining.xsdlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/JBossEntityResolverUnitTestCase0000644000175000017500000000112510767467017033604 0ustar twernertwerner ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/JBossEntityResolverUnitTestCase_testResolveRedefine_redefined.xsdlibjboss-common-java-0.0+svn2938.orig/common-core/src/test/resources/JBossEntityResolverUnitTestCase0000644000175000017500000000130110767467017033600 0ustar twernertwerner The elements that use this type designate the name of a Java class or interface. The name is in the form of a "binary name", as defined in the JLS and as used in Class.forName(). libjboss-common-java-0.0+svn2938.orig/common-core/src/main/0000755000175000017500000000000011105642362023343 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/0000755000175000017500000000000011105642362024264 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/0000755000175000017500000000000011105642362025053 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/0000755000175000017500000000000011105642362026173 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/0000755000175000017500000000000011105642362026761 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/0000755000175000017500000000000011105642362030622 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/0000755000175000017500000000000011105642362031541 5ustar twernertwerner././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/Handler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/Handler.0000644000175000017500000000332211023535625033121 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.file; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * A protocol handler for the 'file' protocol. * * @version $Revision: 2859 $ * @author Jason Dillon * @author Dimitris Andreadis */ public class Handler extends URLStreamHandler { public URLConnection openConnection(final URL url) throws IOException { return new FileURLConnection(url); } protected void parseURL(final URL url, final String s, final int i, final int j) { super.parseURL(url, s.replace(java.io.File.separatorChar, '/'), i, j); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/FileURLConnection.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/FileURLC0000644000175000017500000001456211023722741033040 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.file; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.security.Permission; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Provides local file access via URL semantics, correctly returning * the last modified time of the underlying file. * * @author Jason Dillon * @author Scott Stark * @author Dimitris Andreadis * @version $Revision: 2866 $ */ public class FileURLConnection extends URLConnection { static boolean decodeFilePaths = true; static { String flag = System.getProperty("org.jboss.net.protocol.file.decodeFilePaths"); if (flag != null) { decodeFilePaths = Boolean.valueOf(flag).booleanValue(); } } /** The underlying file */ protected File file; public FileURLConnection(final URL url) throws MalformedURLException, IOException { super(url); String path = url.getPath(); if (decodeFilePaths) { path = URLDecoder.decode(path, "UTF-8"); } // Convert the url '/' to the os file separator file = new File(path.replace('/', File.separatorChar).replace('|', ':')); super.doOutput = false; } /** * Returns the underlying file for this connection. * @return the file */ public File getFile() { return file; } /** * Checks if the underlying file for this connection exists. * * @throws FileNotFoundException */ public void connect() throws IOException { if (connected) return; if (!file.exists()) { throw new FileNotFoundException(file.getPath()); } connected = true; } public InputStream getInputStream() throws IOException { connect(); if (file.isDirectory()) { // return a sorted list of the directory contents String[] files = file.list(); Arrays.sort(files); StringBuilder sb = new StringBuilder(); for (int i = 0; i < files.length; i++) { sb.append(files[i]).append("\n"); } return new ByteArrayInputStream(sb.toString().getBytes()); } else { return new FileInputStream(file); } } // We should probably disallow this? public OutputStream getOutputStream() throws IOException { connect(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for write access FilePermission p = new FilePermission(file.getPath(), "write"); sm.checkPermission(p); } return new FileOutputStream(file); } /** * Provides support for the following headers: * * last-modified * content-length * content-type * date */ public String getHeaderField(final String name) { String headerField = null; if (name.equalsIgnoreCase("last-modified")) { long lastModified = getLastModified(); if (lastModified != 0) { // return the last modified date formatted according to RFC 1123 Date modifiedDate = new Date(lastModified); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); headerField = sdf.format(modifiedDate); } } else if (name.equalsIgnoreCase("content-length")) { headerField = String.valueOf(file.length()); } else if (name.equalsIgnoreCase("content-type")) { if (file.isDirectory()) { headerField = "text/plain"; } else { headerField = getFileNameMap().getContentTypeFor(file.getName()); if (headerField == null) { try { InputStream is = getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); headerField = URLConnection.guessContentTypeFromStream(bis); bis.close(); } catch(IOException e) { // ignore } } } } else if (name.equalsIgnoreCase("date")) { headerField = String.valueOf(getLastModified()); } else { // This always returns null currently headerField = super.getHeaderField(name); } return headerField; } /** * Return a permission for reading of the file */ public Permission getPermission() throws IOException { return new FilePermission(file.getPath(), "read"); } /** * Returns the last modified time of the underlying file. */ public long getLastModified() { return file.lastModified(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/FileURLLister.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/file/FileURLL0000644000175000017500000001350210774222622033047 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.file; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import org.jboss.logging.Logger; import org.jboss.net.protocol.URLListerBase; /** * FileURLLister * * @author jboynes@users.sf.net * @author Dimitris Andreadis * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class FileURLLister extends URLListerBase { /** The Logger */ private static final Logger log = Logger.getLogger(FileURLLister.class); // Public -------------------------------------------------------- public Collection listMembers(URL baseUrl, URLFilter filter) throws IOException { return listMembers(baseUrl, filter, false); } public Collection listMembers(URL baseUrl, URLFilter filter, boolean scanNonDottedSubDirs) throws IOException { // Make sure this is a directory URL String baseUrlString = baseUrl.toString(); if (!baseUrlString.endsWith("/")) { throw new IOException("Does not end with '/', not a directory url: " + baseUrlString); } // Verify the directory actually exists File dir = new File(baseUrl.getPath()); if (!dir.isDirectory()) { throw new FileNotFoundException("Not pointing to a directory, url: " + baseUrlString); } // The list of URLs to return ArrayList resultList = new ArrayList(); // Do the actual job listFiles(baseUrl, filter, scanNonDottedSubDirs, resultList); // Done return resultList; } // Private ------------------------------------------------------- /** * Starting from baseUrl, that should point to a directory, populate the * resultList with the contents that pass the filter (in the form of URLs) * and possibly recurse into subdris not containing a '.' in their name. */ private void listFiles(final URL baseUrl, final URLFilter filter, boolean scanNonDottedSubDirs, ArrayList resultList) throws IOException { // List the files at the current dir level, using the provided filter final File baseDir = new File(baseUrl.getPath()); String[] filenames = baseDir.list(new FilenameFilter() { public boolean accept(File dir, String name) { try { return filter.accept(baseUrl, name); } catch (Exception e) { log.debug("Unexpected exception filtering entry '" + name + "' in directory '" + baseDir + "'", e); return true; } } }); if (filenames == null) { // This happens only when baseDir not a directory (but this is already // checked by the caller) or some unknown IOException happens internally // (e.g. run out of file descriptors?). Unfortunately the File API // doesn't provide a way to know. throw new IOException("Could not list directory '" + baseDir + "', reason unknown"); } else { String baseUrlString = baseUrl.toString(); for (int i = 0; i < filenames.length; i++) { String filename = filenames[i]; // Find out if this is a directory File file = new File(baseDir, filename); boolean isDir = file.isDirectory(); // The subUrl URL subUrl = createURL(baseUrlString, filename, isDir); // If scanning subdirs and we have a directory, not containing a '.' in // the name, recurse into it. This is to allow recursing into grouping // dirs like ./deploy/jms, ./deploy/management, etc., avoiding // at the same time exploded packages, like .sar, .war, etc. if (scanNonDottedSubDirs && isDir && (filename.indexOf('.') == -1)) { // recurse into it listFiles(subUrl, filter, scanNonDottedSubDirs, resultList); } else { // just add to the list resultList.add(subUrl); } } } } /** * Create a URL by concatenating the baseUrlString that should end at '/', * the filename, and a trailing slash, if it points to a directory */ private URL createURL(String baseUrlString, String filename, boolean isDirectory) { try { return new URL(baseUrlString + filename + (isDirectory ? "/" : "")); } catch (MalformedURLException e) { // shouldn't happen throw new IllegalStateException(); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/http/0000755000175000017500000000000011105642362031601 5ustar twernertwerner././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/http/DavURLLister.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/http/DavURLLi0000644000175000017500000000750710774222622033123 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.http; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpURL; import org.apache.webdav.lib.WebdavResource; import org.jboss.net.protocol.URLListerBase; @SuppressWarnings("unchecked") public class DavURLLister extends URLListerBase { public Collection listMembers (URL baseUrl, URLFilter filter) throws IOException { return listMembers (baseUrl, filter, false); } public Collection listMembers (URL baseUrl, URLFilter filter, boolean scanNonDottedSubDirs) throws IOException { WebdavResource resource = null; try { resource = new WebdavResource (baseUrl.toString ()); WebdavResource[] resources = resource.listWebdavResources (); List urls = new ArrayList(resources.length); for (int i = 0; i < resources.length; i++) { WebdavResource member = resources[i]; HttpURL httpURL = member.getHttpURL (); if (filter.accept (baseUrl, httpURL.getName ())) { String uri = httpURL.getURI(); if (member.isCollection ()) { if (! uri.endsWith ("/")) uri += "/"; // it is a directory: do we have to recursively list its content? String path = httpURL.getPath(); if (scanNonDottedSubDirs && getFilePartFromUrl(path).indexOf (".") == -1) { URL subUrl = new URL (uri) ; urls.addAll (listMembers (subUrl, filter, scanNonDottedSubDirs)); } else { urls.add (new URL (uri)); } } else { urls.add (new URL (uri)); } } } return urls; } catch (HttpException e) { throw new IOException (e.getMessage ()); } catch (MalformedURLException e) { // should not happen throw new IllegalStateException (e.getMessage ()); } finally { if (resource != null) { resource.close (); } } } protected static final String getFilePartFromUrl (String name) { int length = name.length (); if (name.charAt (length - 1) == '/') { int start = name.lastIndexOf ("/", length - 2); return name.substring (start, length -2); } else { int start = name.lastIndexOf ("/"); return name.substring (start); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/0000755000175000017500000000000011105642362032451 5ustar twernertwerner././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/Handler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/Hand0000644000175000017500000000306210470642610033247 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.resource; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * A protocol handler for the 'resource' protocol. Provides * access to system resources. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class Handler extends URLStreamHandler { public URLConnection openConnection(final URL url) throws IOException { return new ResourceURLConnection(url); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/ResourceURLConnection.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/Reso0000644000175000017500000000542710470642610033314 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.resource; import java.io.IOException; import java.io.FileNotFoundException; import java.net.URL; import java.net.MalformedURLException; import org.jboss.net.protocol.DelegatingURLConnection; import org.jboss.logging.Logger; /** * Provides access to system resources as a URLConnection. * * @version $Revision: 1958 $ * @author Jason Dillon * @author Scott.Stark@jboss.org */ public class ResourceURLConnection extends DelegatingURLConnection { private static final Logger log = Logger.getLogger(ResourceURLConnection.class); public ResourceURLConnection(final URL url) throws MalformedURLException, IOException { super(url); } protected URL makeDelegateUrl(final URL url) throws MalformedURLException, IOException { String name = url.getHost(); String file = url.getFile(); if (file != null && !file.equals("")) { name += file; } // first try TCL and then SCL ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL target = cl.getResource(name); if (target == null) { cl = ClassLoader.getSystemClassLoader(); target = cl.getResource(name); } if (target == null) throw new FileNotFoundException("Could not locate resource: " + name); if (log.isTraceEnabled()) { log.trace("Target resource URL: " + target); try { log.trace("Target resource URL connection: " + target.openConnection()); } catch (Exception ignore) { } } // Return a new URL as the cl version does not use the JB stream factory return new URL(target.toExternalForm()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/resource/pack0000644000175000017500000000155010470642610033313 0ustar twernertwerner

Provides a system 'resource' access protocol handler.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/njar/0000755000175000017500000000000011105642362031554 5ustar twernertwerner././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/njar/Handler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/njar/Handler.0000644000175000017500000001326010774222622033140 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol.njar; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.jboss.logging.Logger; import org.jboss.util.stream.Streams; import org.jboss.util.ThrowableHandler; /** * A protocol handler for the n(ested)jar protocol. * *

* This is class allows you to use the njar: URL protocol. It is very * similar to it's jar: cusin. The difference being that jars can be * nested. * *

* An example of how to use this class is: *

 *
 *    URL url = new URL("njar:njar:file:c:/test1.zip^/test2.zip^/hello.txt");
 *    url.openStream();
 *
 * 
* *

* Please be aware that the njar protocol caches it's jar in temporary * storage when connections are opened into them. So for the above * example, 2 files would cached a temp files names similar to nested-xxxx.jar * * @todo Add accessors so that the cache can be flushed. * * @version $Revision: 2787 $ * @author Hiram Chirino */ @SuppressWarnings("unchecked") public class Handler extends URLStreamHandler { // URL protocol designations public static final String PROTOCOL = "njar"; public static final String NJAR_SEPARATOR = "^/"; public static final String JAR_SEPARATOR = "!/"; private static final Logger log = Logger.getLogger(Handler.class); protected Map savedJars = new HashMap(); public URLConnection openConnection(final URL url) throws IOException { String file = url.getFile(); String embeddedURL = file; String jarPath = ""; boolean trace = log.isTraceEnabled(); int pos = file.lastIndexOf(NJAR_SEPARATOR); if (pos >= 0) { embeddedURL = file.substring(0, pos); if (file.length() > pos + NJAR_SEPARATOR.length()) jarPath = file.substring(pos + NJAR_SEPARATOR.length()); } if (embeddedURL.startsWith(PROTOCOL)) { if (trace) log.trace("Opening next nested jar: " + embeddedURL); File tempJar = (File) savedJars.get(embeddedURL); if (tempJar == null) { URLConnection embededDataConnection = new URL(embeddedURL).openConnection(); if (trace) log.trace("Content length: " + embededDataConnection.getContentLength()); InputStream embededData = embededDataConnection.getInputStream(); tempJar = File.createTempFile("nested-", ".jar"); tempJar.deleteOnExit(); if (trace) log.trace("temp file location : " + tempJar); OutputStream output = new FileOutputStream(tempJar); try { // copyb will buffer the streams for us long bytes = Streams.copyb(embededData, output); if (trace) log.trace("copied " + bytes + " bytes"); } finally { Streams.flush(output); // close an pass errors to throwable handler (we don't care about them) Streams.close(embededData); Streams.close(output); } savedJars.put(embeddedURL, tempJar); } String t = tempJar.getCanonicalFile().toURL().toExternalForm(); if (trace) log.trace("file URL : " + t); t = "njar:" + t + NJAR_SEPARATOR + jarPath; if (trace) log.trace("Opening saved jar: " + t); URL u = new URL(t); if (trace) log.trace("Using URL: " + u); return u.openConnection(); } else { if (trace) log.trace("Opening final nested jar: " + embeddedURL); URL u = new URL("jar:" + embeddedURL + JAR_SEPARATOR + jarPath); if (trace) log.trace("Using URL: " + u); return u.openConnection(); } } public static URL njarToFile(URL url) { if (url.getProtocol().equals(PROTOCOL)) { try { // force the resource we are after to be unpacked - thanks // Jan & David...! URL dummy=new URL(PROTOCOL+":"+url.toString()+NJAR_SEPARATOR+"dummy.jar"); String tmp=dummy.openConnection().getURL().toString(); tmp=tmp.substring("jar:".length()); tmp=tmp.substring(0, tmp.length()-(JAR_SEPARATOR+"dummy.jar").length()); return new URL(tmp); } catch (Exception ignore) { ThrowableHandler.addWarning(ignore); } } return url; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/njar/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/njar/package.0000644000175000017500000000154310470642610033153 0ustar twernertwerner

Provides a nested jar ('njar') protocol handler.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLListerBase.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLListerBase0000644000175000017500000000611710774222622033176 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol; import java.util.Arrays; import java.util.HashSet; import java.util.Collection; import java.util.StringTokenizer; import java.net.URL; import java.io.IOException; /** * Support class for URLLister's providing protocol independent functionality. * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public abstract class URLListerBase implements URLLister { public Collection listMembers (URL baseUrl, String patterns, boolean scanNonDottedSubDirs) throws IOException { // @todo, externalize the separator? StringTokenizer tokens = new StringTokenizer (patterns, ","); String[] members = new String[tokens.countTokens ()]; for (int i=0; tokens.hasMoreTokens (); i++) { String token = tokens.nextToken (); // Trim leading/trailing spaces as its unlikely they are meaningful members[i] = token.trim(); } URLFilter filter = new URLFilterImpl (members); return listMembers (baseUrl, filter, scanNonDottedSubDirs); } public Collection listMembers (URL baseUrl, String patterns) throws IOException { return listMembers (baseUrl, patterns, false); } /** * Inner class representing Filter criteria to be applied to the members * of the returned Collection */ public static class URLFilterImpl implements URLFilter { protected boolean allowAll; protected HashSet constants; public URLFilterImpl (String[] patterns) { constants = new HashSet (Arrays.asList (patterns)); allowAll = constants.contains ("*"); } public boolean accept (URL baseUrl, String name) { if (allowAll) { return true; } if (constants.contains (name)) { return true; } return false; } } protected static final URLFilter acceptAllFilter = new URLFilter () { public boolean accept (URL baseURL, String memberName) { return true; } }; } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLLister.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLLister.jav0000644000175000017500000000746210774222622033166 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol; import java.io.IOException; import java.net.URL; import java.util.Collection; /** * Interface defining methods that can be used to list the contents of a URL * collection irrespective of the protocol. */ @SuppressWarnings("unchecked") public interface URLLister { /** * List the members of the given collection URL that match the patterns * supplied and, if it contains directory that contains NO dot in the name and * scanNonDottedSubDirs is true, recursively finds URL in these directories. * @param baseUrl the URL to list; must end in "/" * @param patterns the patterns to match (separated by ',') * @param scanNonDottedSubDirs enables recursive search for directories containing no dots * @return a Collection of URLs that match * @throws IOException if there was a problem getting the list */ Collection listMembers(URL baseUrl, String patterns, boolean scanNonDottedSubDirs) throws IOException; /** * List the members of the given collection URL that match the patterns * supplied. Doesn't recursively list files contained in directories. * @param baseUrl the URL to list; must end in "/" * @param patterns the patterns to match (separated by ',') * @return a Collection of URLs that match * @throws IOException if there was a problem getting the list */ Collection listMembers(URL baseUrl, String patterns) throws IOException; /** * List the members of the given collection that are accepted by the filter * @param baseUrl the URL to list; must end in "/" * @param filter a filter that is called to determine if a member should * be returned * @param scanNonDottedSubDirs enables recursive search for directories containing no dots * @return a Collection of URLs that match * @throws IOException if there was a problem getting the list */ Collection listMembers(URL baseUrl, URLFilter filter, boolean scanNonDottedSubDirs) throws IOException; /** * List the members of the given collection that are accepted by the filter * @param baseUrl the URL to list; must end in "/" * @param filter a filter that is called to determine if a member should * be returned * @return a Collection of URLs that match * @throws IOException if there was a problem getting the list */ Collection listMembers(URL baseUrl, URLFilter filter) throws IOException; /** * Interface defining a filter for listed members. */ public interface URLFilter { /** * Determine whether the supplied memberName should be accepted * @param baseURL the URL of the collection * @param memberName the member of the collection * @return true to accept */ boolean accept(URL baseURL, String memberName); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/package.html0000644000175000017500000000151710470642610033107 0ustar twernertwerner

URL protocol stream helpers.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLStreamHandlerFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLStreamHand0000644000175000017500000002026411023535625033164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol; import java.net.URL; import java.net.URLStreamHandler; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import org.jboss.logging.Logger; /** * A factory for loading URL protocol handlers. This is based * on Sun's URL mechanism, in that Handler classes will be * searched for in the packages specified by the java.protocol.handler.pkgs * property are searched for classes matching the protocol + ".Handler" * classname. The default JBoss package "org.jboss.net.protocol" is searched * even if not specified in the java.protocol.handler.pkgs property. * *

This factory is installed by the default server implementaion * to ensure that protocol handlers not in the system classpath are * located. The thread context class is used first followed by the * Class.forName method. *

* * @version $Revision: 2859 $ * @author Jason Dillon * @author Scott.Stark@jboss.org */ @SuppressWarnings("unchecked") public class URLStreamHandlerFactory implements java.net.URLStreamHandlerFactory { /** Class logger. */ private static final Logger log = Logger.getLogger(URLStreamHandlerFactory.class); /** The package prefix where JBoss protocol handlers live. */ public static final String PACKAGE_PREFIX = "org.jboss.net.protocol"; /** A map of protocol names to handlers. Since there can only be one URLStreamHandlerFactory installed, this is a static map that may be cleared. */ private static Map handlerMap = Collections.synchronizedMap(new HashMap()); /** This thread local is used to prevent recursion in the * createURLStreamHandler method. Resolving the protocol handler * class can end up creating a new URL which can loop back into * this factory with a stack like: *
      URLStreamHandlerFactory that use the TCL. See bug#669043
      createURLStreamHandler():146, URLStreamHandlerFactory.java
      getURLStreamHandler():1057, URL.java
      ():405, URL.java
      ():329, URL.java
      ():321, URL.java
      ():540, URLClassPath.java
      run():319, URLClassPath.java
      doPrivileged():-1, AccessController.java
      getLoader():308, URLClassPath.java
      getLoader():285, URLClassPath.java
      findResource():136, URLClassPath.java
      run():351, URLClassLoader.java
      doPrivileged():-1, AccessController.java
      findResource():348, URLClassLoader.java
      getResource():780, ClassLoader.java
      getResourceLocally():250, UnifiedClassLoader.java
      getResourceFromClassLoader():333, UnifiedLoaderRepository3.java
      getResource():243, UnifiedLoaderRepository3.java
      getResource():228, UnifiedClassLoader3.java
     
So we detect recursion based on the protocol value matches the current createURLStreamHandlerProtocol setting. */ private static ThreadLocal createURLStreamHandlerProtocol = new ThreadLocal(); /** The current packages prefixes determined from the java.protocol.handler.pkgs property + the org.jboss.net.protocol default package. */ private String[] handlerPkgs = {PACKAGE_PREFIX}; /** The last java.protocol.handler.pkgs value. Used to determine if the java.protocol.handler.pkgs property has changed since handlerPkgs was last built. */ private String lastHandlerPkgs = PACKAGE_PREFIX; /** A list of JBoss specific protocols for preloading. */ public static final String PROTOCOLS[] = { "file", "resource" }; /** * Preload the JBoss specific protocol handlers, so that URL knows about * them even if the handler factory is changed. */ @SuppressWarnings("unused") public static void preload() { for (int i = 0; i < PROTOCOLS.length; i ++) { try { URL url = new URL(PROTOCOLS[i], "", -1, ""); log.trace("Loaded protocol: " + PROTOCOLS[i]); } catch (Exception e) { log.warn("Failed to load protocol: " + PROTOCOLS[i], e); } } } /** Clear the current protocol to handler map. The map will be rebuilt as protocol handlers are requested. */ public static void clear() { handlerMap.clear(); } /** Search the handlerPkgs for URLStreamHandler classes matching the * pkg + protocol + ".Handler" naming convention. * * @param protocol The protocol to create a stream handler for * @return The protocol handler or null if not found */ public URLStreamHandler createURLStreamHandler(final String protocol) { // Check the handler map URLStreamHandler handler = (URLStreamHandler) handlerMap.get(protocol); if( handler != null ) return handler; // Validate that createURLStreamHandler is not recursing String prevProtocol = (String) createURLStreamHandlerProtocol.get(); if( prevProtocol != null && prevProtocol.equals(protocol) ) return null; createURLStreamHandlerProtocol.set(protocol); // See if the handler pkgs definition has changed checkHandlerPkgs(); // Search the handlerPkgs for a matching protocol handler ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader(); for(int p = 0; p < handlerPkgs.length; p ++) { try { // Form the standard protocol handler class name String classname = handlerPkgs[p] + "." + protocol + ".Handler"; Class type = null; try { type = ctxLoader.loadClass(classname); } catch(ClassNotFoundException e) { // Try our class loader type = Class.forName(classname); } if( type != null ) { handler = (URLStreamHandler) type.newInstance(); handlerMap.put(protocol, handler); log.trace("Found protocol:"+protocol+" handler:"+handler); } } catch (Throwable ignore) { } } createURLStreamHandlerProtocol.set(null); return handler; } /** See if the java.protocol.handler.pkgs system property has changed and if it has, parse it to update the handlerPkgs array. */ private synchronized void checkHandlerPkgs() { String handlerPkgsProp = System.getProperty("java.protocol.handler.pkgs"); if( handlerPkgsProp != null && handlerPkgsProp.equals(lastHandlerPkgs) == false ) { // Update the handlerPkgs[] from the handlerPkgsProp StringTokenizer tokeninzer = new StringTokenizer(handlerPkgsProp, "|"); ArrayList tmp = new ArrayList(); while( tokeninzer.hasMoreTokens() ) { String pkg = tokeninzer.nextToken().intern(); if( tmp.contains(pkg) == false ) tmp.add(pkg); } // Include the JBoss default protocol handler pkg if( tmp.contains(PACKAGE_PREFIX) == false ) tmp.add(PACKAGE_PREFIX); handlerPkgs = new String[tmp.size()]; tmp.toArray(handlerPkgs); lastHandlerPkgs = handlerPkgsProp; } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/DelegatingURLConnection.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/DelegatingURL0000644000175000017500000001370510774222622033205 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLConnection; import java.net.URL; import java.net.MalformedURLException; import java.security.Permission; /** * An delegating URLConnection support class. * * @todo resolve 1.4 specific issues. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class DelegatingURLConnection extends URLConnection { protected URL delegateUrl; protected URLConnection delegateConnection; public DelegatingURLConnection(final URL url) throws MalformedURLException, IOException { super(url); delegateUrl = makeDelegateUrl(url); delegateConnection = makeDelegateUrlConnection(delegateUrl); } protected URL makeDelegateUrl(final URL url) throws MalformedURLException, IOException { return url; } protected URLConnection makeDelegateUrlConnection(final URL url) throws IOException { return url.openConnection(); } public void connect() throws IOException { delegateConnection.connect(); } public URL getURL() { return delegateConnection.getURL(); } public int getContentLength() { return delegateConnection.getContentLength(); } public String getContentType() { return delegateConnection.getContentType(); } public String getContentEncoding() { return delegateConnection.getContentEncoding(); } public long getExpiration() { return delegateConnection.getExpiration(); } public long getDate() { return delegateConnection.getDate(); } public long getLastModified() { return delegateConnection.getLastModified(); } public String getHeaderField(String name) { return delegateConnection.getHeaderField(name); } /* This is specific to 1.4 public Map getHeaderFields() { return delegateConnection.getHeaderFields(); } */ public int getHeaderFieldInt(String name, int _default) { return delegateConnection.getHeaderFieldInt(name, _default); } public long getHeaderFieldDate(String name, long _default) { return delegateConnection.getHeaderFieldDate(name, _default); } public String getHeaderFieldKey(int n) { return delegateConnection.getHeaderFieldKey(n); } public String getHeaderField(int n) { return delegateConnection.getHeaderField(n); } public Object getContent() throws IOException { return delegateConnection.getContent(); } public Object getContent(Class[] classes) throws IOException { return delegateConnection.getContent(classes); } public Permission getPermission() throws IOException { return delegateConnection.getPermission(); } public InputStream getInputStream() throws IOException { return delegateConnection.getInputStream(); } public OutputStream getOutputStream() throws IOException { return delegateConnection.getOutputStream(); } public String toString() { return super.toString() + "{ " + delegateConnection + " }"; } public void setDoInput(boolean doinput) { delegateConnection.setDoInput(doinput); } public boolean getDoInput() { return delegateConnection.getDoInput(); } public void setDoOutput(boolean dooutput) { delegateConnection.setDoOutput(dooutput); } public boolean getDoOutput() { return delegateConnection.getDoOutput(); } public void setAllowUserInteraction(boolean allowuserinteraction) { delegateConnection.setAllowUserInteraction(allowuserinteraction); } public boolean getAllowUserInteraction() { return delegateConnection.getAllowUserInteraction(); } public void setUseCaches(boolean usecaches) { delegateConnection.setUseCaches(usecaches); } public boolean getUseCaches() { return delegateConnection.getUseCaches(); } public void setIfModifiedSince(long ifmodifiedsince) { delegateConnection.setIfModifiedSince(ifmodifiedsince); } public long getIfModifiedSince() { return delegateConnection.getIfModifiedSince(); } public boolean getDefaultUseCaches() { return delegateConnection.getDefaultUseCaches(); } public void setDefaultUseCaches(boolean defaultusecaches) { delegateConnection.setDefaultUseCaches(defaultusecaches); } public void setRequestProperty(String key, String value) { delegateConnection.setRequestProperty(key, value); } /* This is specific to 1.4 public void addRequestProperty(String key, String value) { delegateConnection.addRequestProperty(key, value); } */ public String getRequestProperty(String key) { return delegateConnection.getRequestProperty(key); } /* This is specific to 1.4 public Map getRequestProperties() { return delegateConnection.getRequestProperties(); } */ } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLListerFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/protocol/URLListerFact0000644000175000017500000000660710774222622033205 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.protocol; import java.net.URL; import java.net.MalformedURLException; import java.util.HashMap; @SuppressWarnings("unchecked") public class URLListerFactory { private static HashMap defaultClasses = new HashMap(); static { defaultClasses.put("file", "org.jboss.net.protocol.file.FileURLLister"); defaultClasses.put("http", "org.jboss.net.protocol.http.DavURLLister"); defaultClasses.put("https", "org.jboss.net.protocol.http.DavURLLister"); } private HashMap classes; /** * Create a URLLister with default listers defined for file and http * protocols. */ public URLListerFactory() { classes = (HashMap) defaultClasses.clone(); } /** * Create a URL lister using the protocol from the URL * @param url the url defining the protocol * @return a URLLister capable of listing URLs of that protocol * @throws MalformedURLException if no lister could be found for the protocol */ public URLLister createURLLister(URL url) throws MalformedURLException { return createURLLister(url.getProtocol()); } /** * Create a URL lister for the supplied protocol * @param protocol the protocol * @return a URLLister capable of listing URLs of that protocol * @throws MalformedURLException if no lister could be found for the protocol */ public URLLister createURLLister(String protocol) throws MalformedURLException { try { String className = (String) classes.get(protocol); if (className == null) { throw new MalformedURLException("No lister class defined for protocol "+protocol); } Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); return (URLLister) clazz.newInstance(); } catch (ClassNotFoundException e) { throw new MalformedURLException(e.getMessage()); } catch (InstantiationException e) { throw new MalformedURLException(e.getMessage()); } catch (IllegalAccessException e) { throw new MalformedURLException(e.getMessage()); } } /** * Register a URLLister class for a given protocol * @param protocol the protocol this class will handle * @param className the URLLister implementation to instanciate */ public void registerListener(String protocol, String className) { classes.put(protocol, className); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/ssl/0000755000175000017500000000000011105642362027562 5ustar twernertwerner././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/ssl/SSLSocketFactoryBuilder.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/ssl/SSLSocketFactoryBu0000644000175000017500000000247110470642610033142 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.ssl; import javax.net.ssl.SSLSocketFactory; /** A simple builder for creating SSLSocketFactory instances. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public interface SSLSocketFactoryBuilder { SSLSocketFactory getSocketFactory() throws Exception; } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/0000755000175000017500000000000011105642362030434 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocket.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocket0000644000175000017500000000226210470642610033174 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; public interface RMIMultiSocket extends java.rmi.Remote { public Object invoke (long methodHash, Object[] args) throws Exception; } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutSocket.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutSocket.0000644000175000017500000001212510470642610033235 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.net.Socket; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.SocketChannel; /** A Socket that overrides the getInputStream to return a InterruptableInputStream * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class TimeoutSocket extends Socket { private Socket s; public TimeoutSocket(Socket s) { this.s = s; } public InetAddress getInetAddress() { return s.getInetAddress(); } public InetAddress getLocalAddress() { return s.getLocalAddress(); } public int getPort() { return s.getPort(); } public int getLocalPort() { return s.getLocalPort(); } public SocketAddress getRemoteSocketAddress() { return s.getRemoteSocketAddress(); } public SocketAddress getLocalSocketAddress() { return s.getLocalSocketAddress(); } public SocketChannel getChannel() { return s.getChannel(); } public InputStream getInputStream() throws IOException { InputStream is = s.getInputStream(); InterruptableInputStream iis = new InterruptableInputStream(is); return iis; } public OutputStream getOutputStream() throws IOException { return s.getOutputStream(); } public void setTcpNoDelay(boolean on) throws SocketException { s.setTcpNoDelay(on); } public boolean getTcpNoDelay() throws SocketException { return s.getTcpNoDelay(); } public void setSoLinger(boolean on, int linger) throws SocketException { s.setSoLinger(on, linger); } public int getSoLinger() throws SocketException { return s.getSoLinger(); } public void sendUrgentData(int data) throws IOException { s.sendUrgentData(data); } public void setOOBInline(boolean on) throws SocketException { s.setOOBInline(on); } public boolean getOOBInline() throws SocketException { return s.getOOBInline(); } public synchronized void setSoTimeout(int timeout) throws SocketException { s.setSoTimeout(1000); } public synchronized int getSoTimeout() throws SocketException { return s.getSoTimeout(); } public synchronized void setSendBufferSize(int size) throws SocketException { s.setSendBufferSize(size); } public synchronized int getSendBufferSize() throws SocketException { return s.getSendBufferSize(); } public synchronized void setReceiveBufferSize(int size) throws SocketException { s.setReceiveBufferSize(size); } public synchronized int getReceiveBufferSize() throws SocketException { return s.getReceiveBufferSize(); } public void setKeepAlive(boolean on) throws SocketException { s.setKeepAlive(on); } public boolean getKeepAlive() throws SocketException { return s.getKeepAlive(); } public void setTrafficClass(int tc) throws SocketException { s.setTrafficClass(tc); } public int getTrafficClass() throws SocketException { return s.getTrafficClass(); } public void setReuseAddress(boolean on) throws SocketException { s.setReuseAddress(on); } public boolean getReuseAddress() throws SocketException { return s.getReuseAddress(); } public synchronized void close() throws IOException { s.close(); } public void shutdownInput() throws IOException { s.shutdownInput(); } public void shutdownOutput() throws IOException { s.shutdownOutput(); } public String toString() { return s.toString(); } public boolean isConnected() { return s.isConnected(); } public boolean isBound() { return s.isBound(); } public boolean isClosed() { return s.isClosed(); } public boolean isInputShutdown() { return s.isInputShutdown(); } public boolean isOutputShutdown() { return s.isOutputShutdown(); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/DefaultClientSocketFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/DefaultClientS0000644000175000017500000000706110506015670033231 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.IOException; import java.io.Serializable; import java.rmi.server.RMIClientSocketFactory; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /** * A RMIClientSocketFactory that adds a bind address override of the server * host to control what the address the client uses. * * @author Scott.Stark@jboss.org * @version $Revision: 30203 $ */ public class DefaultClientSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = -920483051658660269L; /** An override of the server address */ private InetAddress bindAddress; public DefaultClientSocketFactory() { } public String getBindAddress() { String address = null; if( bindAddress != null ) address = bindAddress.getHostAddress(); return address; } public void setBindAddress(String host) throws UnknownHostException { bindAddress = InetAddress.getByName(host); } /** * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception java.io.IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public Socket createSocket(String host, int port) throws IOException { InetAddress addr = null; if( bindAddress != null ) addr = bindAddress; else addr = InetAddress.getByName(host); Socket s = new Socket(addr, port); return s; } public boolean equals(Object obj) { boolean equals = obj instanceof DefaultClientSocketFactory; if( equals && bindAddress != null ) { DefaultClientSocketFactory dcsf = (DefaultClientSocketFactory) obj; InetAddress dcsfa = dcsf.bindAddress; if( dcsfa != null ) equals = bindAddress.equals(dcsfa); else equals = false; } return equals; } public int hashCode() { int hashCode = getClass().getName().hashCode(); if( bindAddress != null ) hashCode += bindAddress.toString().hashCode(); return hashCode; } public String toString() { StringBuffer tmp = new StringBuffer(super.toString()); tmp.append('['); tmp.append("bindAddress="); tmp.append(bindAddress); tmp.append(']'); return tmp.toString(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocketServer.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocket0000644000175000017500000000716710774222622033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.rmi.server.UnicastRemoteObject; import java.rmi.Remote; import java.lang.reflect.Proxy; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.RemoteException; import java.lang.reflect.Method; import java.util.HashMap; import java.rmi.NoSuchObjectException; /** * * @author bill@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class RMIMultiSocketServer { private static HashMap handlermap = new HashMap(); private static HashMap stubmap = new HashMap(); public static Remote exportObject(Remote obj, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf, Class[] interfaces, int numSockets) throws RemoteException { Remote[] stubs = new Remote[numSockets]; Method[] methods = obj.getClass().getMethods(); HashMap invokerMap = new HashMap(); for (int i = 0; i < methods.length; i++) { Long methodkey = new Long(MethodHash.calculateHash(methods[i])); invokerMap.put(methodkey, methods[i]); } RMIMultiSocketHandler[] handlers = new RMIMultiSocketHandler[numSockets]; for (int i = 0; i < numSockets; i++) { int theport = (port == 0) ? 0 : port + i; handlers[i] = new RMIMultiSocketHandler(obj, invokerMap); stubs[i] = UnicastRemoteObject.exportObject(handlers[i], theport, csf, ssf); } Remote remote = (Remote)Proxy.newProxyInstance( obj.getClass().getClassLoader(), interfaces, new RMIMultiSocketClient(stubs)); stubmap.put(remote, stubs); handlermap.put(remote, handlers); return remote; } public static Remote exportObject(Remote obj, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf, int numSockets) throws RemoteException { return exportObject(obj, port, csf, ssf, obj.getClass().getInterfaces(), numSockets); } public static boolean unexportObject(Remote obj, boolean force) throws NoSuchObjectException { handlermap.remove(obj); Remote[] stubs = (Remote[])stubmap.remove(obj); for (int i = 0; i < stubs.length; i++) { UnicastRemoteObject.unexportObject(stubs[i], force); } return true; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/MethodHash.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/MethodHash.jav0000644000175000017500000001076510774222622033177 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.util.WeakHashMap; import java.util.Map; import java.lang.reflect.Method; import java.util.HashMap; import java.io.DataOutputStream; import java.io.ByteArrayOutputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; @SuppressWarnings("unchecked") public class MethodHash { // Static -------------------------------------------------------- static Map hashMap = new WeakHashMap(); /** * Calculate method hashes. This algo is taken from RMI. * * @param intf * @return the map */ public static Map getInterfaceHashes(Class intf) { // Create method hashes Method[] methods = intf.getMethods(); HashMap map = new HashMap(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; Class[] parameterTypes = method.getParameterTypes(); String methodDesc = method.getName()+"("; for(int j = 0; j < parameterTypes.length; j++) { methodDesc += getTypeString(parameterTypes[j]); } methodDesc += ")"+getTypeString(method.getReturnType()); try { long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); MessageDigest messagedigest = MessageDigest.getInstance("SHA"); DataOutputStream dataoutputstream = new DataOutputStream(new DigestOutputStream(bytearrayoutputstream, messagedigest)); dataoutputstream.writeUTF(methodDesc); dataoutputstream.flush(); byte abyte0[] = messagedigest.digest(); for(int j = 0; j < Math.min(8, abyte0.length); j++) hash += (long)(abyte0[j] & 0xff) << j * 8; map.put(method.toString(), new Long(hash)); } catch (Exception e) { e.printStackTrace(); } } return map; } static String getTypeString(Class cl) { if (cl == Byte.TYPE) { return "B"; } else if (cl == Character.TYPE) { return "C"; } else if (cl == Double.TYPE) { return "D"; } else if (cl == Float.TYPE) { return "F"; } else if (cl == Integer.TYPE) { return "I"; } else if (cl == Long.TYPE) { return "J"; } else if (cl == Short.TYPE) { return "S"; } else if (cl == Boolean.TYPE) { return "Z"; } else if (cl == Void.TYPE) { return "V"; } else if (cl.isArray()) { return "["+getTypeString(cl.getComponentType()); } else { return "L"+cl.getName().replace('.','/')+";"; } } /* * The use of hashCode is not enough to differenciate methods * we override the hashCode * * The hashes are cached in a static for efficiency * RO: WeakHashMap needed to support undeploy */ public static long calculateHash(Method method) { Map methodHashes = (Map)hashMap.get(method.getDeclaringClass()); if (methodHashes == null) { methodHashes = getInterfaceHashes(method.getDeclaringClass()); // Copy and add WeakHashMap newHashMap = new WeakHashMap(); newHashMap.putAll(hashMap); newHashMap.put(method.getDeclaringClass(), methodHashes); hashMap = newHashMap; } return ((Long)methodHashes.get(method.toString())).longValue(); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutClientSocketFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutClientS0000644000175000017500000000442310613563514033276 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.IOException; import java.io.Serializable; import java.rmi.server.RMIClientSocketFactory; import java.net.Socket; /** * A RMIClientSocketFactory that installs a InterruptableInputStream to be * responsive to thead interruption events. * * @author Scott.Stark@jboss.org * @version $Revision: 2391 $ */ public class TimeoutClientSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = -920483051658660269L; public TimeoutClientSocketFactory() { } /** * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception java.io.IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public Socket createSocket(String host, int port) throws IOException { Socket s = new Socket(host, port); s.setSoTimeout(1000); TimeoutSocket ts = new TimeoutSocket(s); return ts; } public boolean equals(Object obj) { return obj instanceof TimeoutClientSocketFactory; } public int hashCode() { return getClass().getName().hashCode(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/DefaultSocketFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/DefaultSocketF0000644000175000017500000001150510774222622033230 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.rmi.server.RMIServerSocketFactory; import javax.net.ServerSocketFactory; /** An implementation of RMIServerSocketFactory that supports backlog and * bind address settings * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ public class DefaultSocketFactory extends ServerSocketFactory implements RMIServerSocketFactory, Serializable { static final long serialVersionUID = -7626239955727142958L; private transient InetAddress bindAddress; private int backlog = 200; /** Create a socket factory that binds on any address with a default * backlog of 200 */ public DefaultSocketFactory() { this(null, 200); } /** Create a socket factory with the given bind address * @param bindAddress */ public DefaultSocketFactory(InetAddress bindAddress) { this(bindAddress, 200); } /** Create a socket factory with the given backlog * @param backlog */ public DefaultSocketFactory(int backlog) { this(null, backlog); } /** Create a socket factory with the given bind address and backlog * @param bindAddress * @param backlog */ public DefaultSocketFactory(InetAddress bindAddress, int backlog) { this.bindAddress = bindAddress; this.backlog = backlog; } public String getBindAddress() { String address = null; if( bindAddress != null ) address = bindAddress.getHostAddress(); return address; } public void setBindAddress(String host) throws UnknownHostException { bindAddress = InetAddress.getByName(host); } /** * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public ServerSocket createServerSocket(int port) throws IOException { return createServerSocket(port, backlog, bindAddress); } /** * @param port - the port to listen to * @param backlog - how many connections are queued * @return A ServerSocket * @throws IOException */ public ServerSocket createServerSocket(int port, int backlog) throws IOException { return createServerSocket(port, backlog, null); } /** * @param port - the port to listen to * @param backlog - how many connections are queued * @param inetAddress - the network interface address to use * @return the server socket * @throws IOException */ public ServerSocket createServerSocket(int port, int backlog, InetAddress inetAddress) throws IOException { ServerSocket activeSocket = new ServerSocket(port, backlog, bindAddress); return activeSocket; } public boolean equals(Object obj) { boolean equals = obj instanceof DefaultSocketFactory; if( equals && bindAddress != null ) { DefaultSocketFactory dsf = (DefaultSocketFactory) obj; InetAddress dsfa = dsf.bindAddress; if( dsfa != null ) equals = bindAddress.equals(dsfa); else equals = false; } return equals; } public int hashCode() { int hashCode = getClass().getName().hashCode(); if( bindAddress != null ) hashCode += bindAddress.toString().hashCode(); return hashCode; } public String toString() { StringBuffer tmp = new StringBuffer(super.toString()); tmp.append('['); tmp.append("bindAddress="); tmp.append(bindAddress); tmp.append(']'); return tmp.toString(); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/QueuedClientSocketFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/QueuedClientSo0000644000175000017500000000542510613563514033262 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.IOException; import java.rmi.server.RMIClientSocketFactory; import java.net.Socket; import java.util.concurrent.Semaphore; /** * * @author Scott.Stark@jboss.org * @version $Revision: 2391 $ */ public class QueuedClientSocketFactory implements RMIClientSocketFactory, java.io.Externalizable { private transient Semaphore permits; private long numPermits; public QueuedClientSocketFactory() { } public QueuedClientSocketFactory(long nPermits) { permits = new Semaphore((int)nPermits, true); numPermits = nPermits; } /** * Create a server socket on the specified port (port 0 indicates * an anonymous port). * @param port the port number * @return the server socket on the specified port * @exception IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public Socket createSocket(String host, int port) throws IOException { try { permits.acquire(); return new Socket(host, port); } catch (InterruptedException ex) { throw new IOException("Failed to acquire FIFOSemaphore for ClientSocketFactory"); } finally { permits.release(); } } public boolean equals(Object obj) { return obj instanceof QueuedClientSocketFactory; } public int hashCode() { return getClass().getName().hashCode(); } public void writeExternal(java.io.ObjectOutput out) throws IOException { out.writeLong(numPermits); } public void readExternal(java.io.ObjectInput in) throws IOException, ClassNotFoundException { numPermits = in.readLong(); permits = new Semaphore((int)numPermits, true); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutServerSocket.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutServerS0000644000175000017500000000361110470642610033320 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.net.ServerSocket; import java.net.Socket; import java.net.InetAddress; import java.io.IOException; /** A ServerSocket that returns a TimeoutSocket from the overriden accept. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class TimeoutServerSocket extends ServerSocket { public TimeoutServerSocket(int port) throws IOException { this(port, 50); } public TimeoutServerSocket(int port, int backlog) throws IOException { this(port, backlog, null); } public TimeoutServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { super(port, backlog, bindAddr); } public Socket accept() throws IOException { Socket s = super.accept(); s.setSoTimeout(1000); TimeoutSocket ts = new TimeoutSocket(s); return ts; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/InterruptableInputStream.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/InterruptableI0000644000175000017500000000535210470642610033315 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.InputStream; import java.io.IOException; import java.net.SocketTimeoutException; /** An InputStream that uses the SocketTimeoutException thrown during read * timeouts to check if the thread has been interrupted. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class InterruptableInputStream extends InputStream { private InputStream is; public InterruptableInputStream(InputStream is) { this.is = is; } public int read() throws IOException { byte[] b = {}; int count = internalRead(b, 0, 1); return count > 0 ? b[0] : -1; } public int read(byte[] b) throws IOException { return internalRead(b, 0, b.length); } public int read(byte[] b, int off, int len) throws IOException { return internalRead(b, off, len); } public long skip(long n) throws IOException { return is.skip(n); } public int available() throws IOException { return is.available(); } public void close() throws IOException { is.close(); } public synchronized void mark(int readlimit) { is.mark(readlimit); } public synchronized void reset() throws IOException { is.reset(); } public boolean markSupported() { return is.markSupported(); } private int internalRead(byte[] b, int off, int len) throws IOException { int n = -1; while( true ) { try { n = is.read(b, off, len); return n; } catch(SocketTimeoutException e) { // Test for thread interrupt if( Thread.interrupted() ) throw e; } } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocketHandler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocket0000644000175000017500000000317410774222622033203 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.lang.reflect.Method; import java.util.Map; /** * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class RMIMultiSocketHandler implements RMIMultiSocket { Object target; Map invokerMap; public RMIMultiSocketHandler(Object target, Map invokerMap) { this.target = target; this.invokerMap = invokerMap; } public Object invoke (long methodHash, Object[] args) throws Exception { Method method = (Method)invokerMap.get(new Long(methodHash)); return method.invoke(target, args); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocketClient.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/RMIMultiSocket0000644000175000017500000000417310776226110033201 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.lang.reflect.Method; import java.lang.reflect.InvocationHandler; import java.io.Serializable; import java.util.Random; import java.rmi.Remote; /** * * @author Scott.Stark@jboss.org * @version $Revision: 2800 $ */ public class RMIMultiSocketClient implements InvocationHandler, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = -945837789475428529L; protected Remote[] stubs; protected Random random; public RMIMultiSocketClient(Remote[] stubs) { this.stubs = stubs; random = new Random(); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("hashCode")) { return new Integer(stubs[0].hashCode()); } if (method.getName().equals("equals")) { return new Boolean(stubs[0].equals(args[0])); } int i = random.nextInt(stubs.length); long hash = MethodHash.calculateHash(method); RMIMultiSocket target = (RMIMultiSocket)stubs[i]; return target.invoke(hash, args); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutServerSocketFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/net/sockets/TimeoutServerS0000644000175000017500000000712710774222622033332 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.net.sockets; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.rmi.server.RMIServerSocketFactory; /** * A RMIServerSocketFactory that installs a InterruptableInputStream to be * responsive to thead interruption events. * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ public class TimeoutServerSocketFactory implements RMIServerSocketFactory, Serializable { /** @since 3.2.6 */ static final long serialVersionUID = 7006964274840965634L; protected transient InetAddress bindAddress; protected int backlog = 200; /** * Create a socket factory that binds on any address with a default * backlog of 200 */ public TimeoutServerSocketFactory() { this(null, 200); } /** * Create a socket factory with the given bind address * @param bindAddress */ public TimeoutServerSocketFactory(InetAddress bindAddress) { this(bindAddress, 200); } /** * Create a socket factory with the given backlog * @param backlog */ public TimeoutServerSocketFactory(int backlog) { this(null, backlog); } /** * Create a socket factory with the given bind address and backlog * @param bindAddress * @param backlog */ public TimeoutServerSocketFactory(InetAddress bindAddress, int backlog) { this.bindAddress = bindAddress; this.backlog = backlog; } public String getBindAddress() { String address = null; if (bindAddress != null) address = bindAddress.getHostAddress(); return address; } public void setBindAddress(String host) throws UnknownHostException { bindAddress = InetAddress.getByName(host); } public void setBindAddress(InetAddress bindAddress) { this.bindAddress = bindAddress; } /** * Create a server socket on the specified port (port 0 indicates * an anonymous port). * * @param port the port number * @return the server socket on the specified port * @throws java.io.IOException if an I/O error occurs during server socket * creation * @since 1.2 */ public ServerSocket createServerSocket(int port) throws IOException { ServerSocket activeSocket = new TimeoutServerSocket(port, backlog, bindAddress); return activeSocket; } public boolean equals(Object obj) { return obj instanceof TimeoutServerSocketFactory; } public int hashCode() { return getClass().getName().hashCode(); } }libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/0000755000175000017500000000000011105642366027154 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/0000755000175000017500000000000011105642362030443 5ustar twernertwerner././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/IMarshalledValue.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/IMarshalledVal0000644000175000017500000000240210470642610033214 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.IOException; /** * Tag interface for MarshalledValues * @author Clebert Suconic */ public interface IMarshalledValue { public Object get() throws IOException, ClassNotFoundException; } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/CRLFPrintWriter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/CRLFPrintWrite0000644000175000017500000000477710470642610033163 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.IOException; import java.io.PrintWriter; import java.io.OutputStream; import java.io.InterruptedIOException; import java.io.Writer; /** * A PrintWriter that ends lines with a carriage return-line feed * (CRLF). * *

Concurrency

* This class is as synchronized as PrintWriter. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class CRLFPrintWriter extends PrintWriter { protected boolean autoFlush = false; public CRLFPrintWriter(final Writer out) { super(out); } public CRLFPrintWriter(final Writer out, final boolean autoFlush) { super(out, autoFlush); this.autoFlush = autoFlush; } public CRLFPrintWriter(final OutputStream out) { super(out); } public CRLFPrintWriter(final OutputStream out, final boolean autoFlush) { super(out, autoFlush); this.autoFlush = autoFlush; } protected void ensureOpen() throws IOException { if (out == null) throw new IOException("Stream closed"); } public void println() { try { synchronized (lock) { ensureOpen(); out.write("\r\n"); if (autoFlush) { out.flush(); } } } catch (InterruptedIOException e) { Thread.currentThread().interrupt(); } catch (IOException e) { setError(); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/StreamListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/StreamListener0000644000175000017500000000264410470642610033335 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; /** * A stream listener * * @version $Revision: 1958 $ * @author Adrian Brock */ public interface StreamListener { /** * Invoked by notifiying streams * * @param source the stream * @param size the number of bytes since the last notification */ void onStreamNotification(Object source, int size); } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/NotifyingBufferedInputStream.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/NotifyingBuffe0000644000175000017500000000635310470642610033313 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.IOException; /** * A buffered input stream that notifies every "chunk" * * @version $Revision: 1958 $ * @author Adrian Brock */ public class NotifyingBufferedInputStream extends BufferedInputStream { /** * The number of bytes between notifications */ int chunkSize; /** * The number of bytes read in the current chunk */ int chunk = 0; /** * The listener notified every chunk */ StreamListener listener; /** * Construct a notifying buffered inputstream. * The listener is notified once every chunk. * * @param is the input stream to be buffered * @param size the buffer size * @param chunkSize the chunk size * @param listener the listener to notify * @exception IllegalArgumentException for a size <= 0 or chunkSize <= size */ public NotifyingBufferedInputStream(InputStream is, int size, int chunkSize, StreamListener listener) { super(is, size); if (chunkSize <= size) throw new IllegalArgumentException("chunkSize must be bigger than the buffer"); this.chunkSize = chunkSize; this.listener = listener; } public void setStreamListener(StreamListener listener) { this.listener = listener; } public int read() throws IOException { int result = super.read(); if (result == -1) return result; checkNotification(result); return result; } public int read(byte[] b, int off, int len) throws IOException { int result = super.read(b, off, len); if (result == -1) return result; checkNotification(result); return result; } /** * Checks whether a notification is required and * notifies as appropriate * * @param result the number of bytes read */ public void checkNotification(int result) { // Is a notification required? chunk += result; if (chunk >= chunkSize) { if (listener != null) listener.onStreamNotification(this, chunk); // Start a new chunk chunk = 0; } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/MarshalledValueInputStream.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/MarshalledValu0000644000175000017500000000714411054755361033307 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.util.HashMap; import java.util.Map; /** * An ObjectInputStream subclass used by the MarshalledValue class to * ensure the classes and proxies are loaded using the thread context * class loader. * * @author Scott.Stark@jboss.org * @version $Revision: 37406 $ */ public class MarshalledValueInputStream extends ObjectInputStream { private static final Map primClasses = new HashMap(8, 1.0F); static { primClasses.put("boolean", boolean.class); primClasses.put("byte", byte.class); primClasses.put("char", char.class); primClasses.put("short", short.class); primClasses.put("int", int.class); primClasses.put("long", long.class); primClasses.put("float", float.class); primClasses.put("double", double.class); primClasses.put("void", void.class); } /** * Creates a new instance of MarshalledValueOutputStream * * @param is * @throws IOException */ public MarshalledValueInputStream(InputStream is) throws IOException { super(is); } /** * Use the thread context class loader to resolve the class * * @throws java.io.IOException Any exception thrown by the underlying OutputStream. */ protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String className = v.getName(); try { // JDK 6, by default, only supports array types (ex. [[B) using Class.forName() return Class.forName(className, false, loader); } catch (ClassNotFoundException cnfe) { Class cl = primClasses.get(className); if (cl == null) throw cnfe; else return cl; } } protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { // Load the interfaces from the thread context class loader ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class[] ifaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { ifaceClasses[i] = loader.loadClass(interfaces[i]); } return java.lang.reflect.Proxy.getProxyClass(loader, ifaceClasses); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/NotifyingBufferedOutputStream.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/NotifyingBuffe0000644000175000017500000000613310774222622033313 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; /** * A buffered output stream that notifies every "chunk" * * @version $Revision: 2787 $ * @author Adrian Brock */ public class NotifyingBufferedOutputStream extends BufferedOutputStream { /** * The number of bytes between notifications */ int chunkSize; /** * The number of bytes written in the current chunk */ int chunk = 0; /** * The listener notified every chunk */ StreamListener listener; /** * Construct a notifying buffered outputstream.
* The listener is notified once every chunk. * * @param os the output stream to be buffered * @param size the buffer size * @param chunkSize the chunk size * @param listener * @exception IllegalArgumentException for a size <= 0 or chunkSize <= size or a null listener */ public NotifyingBufferedOutputStream(OutputStream os, int size, int chunkSize, StreamListener listener) { super(os, size); if (chunkSize <= size) throw new IllegalArgumentException("chunkSize must be bigger than the buffer"); this.chunkSize = chunkSize; this.listener = listener; } public void setStreamListener(StreamListener listener) { this.listener = listener; } public void write(int b) throws IOException { super.write(b); checkNotification(1); } public void write(byte[] b, int off, int len) throws IOException { super.write(b, off, len); checkNotification(len); } /** * Checks whether a notification is required and * notifies as appropriate * * @param result the number of bytes written */ public void checkNotification(int result) { // Is a notification required? chunk += result; if (chunk >= chunkSize) { if (listener != null) listener.onStreamNotification(this, chunk); // Start a new chunk chunk = 0; } } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/MarshalledValueOutputStream.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/MarshalledValu0000644000175000017500000000612010774222622033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.rmi.Remote; import java.rmi.server.RemoteObject; import java.rmi.server.RemoteStub; /** * An ObjectOutputStream subclass used by the MarshalledValue class to * ensure the classes and proxies are loaded using the thread context * class loader. Currently this does not do anything as neither class or * proxy annotations are used. * * @author Scott.Stark@jboss.org * @version $Revision: 37406 $ */ public class MarshalledValueOutputStream extends ObjectOutputStream { /** Creates a new instance of MarshalledValueOutputStream If there is a security manager installed, this method requires a SerializablePermission("enableSubstitution") permission to ensure it's ok to enable the stream to do replacement of objects in the stream. * @param os * @throws IOException */ public MarshalledValueOutputStream(OutputStream os) throws IOException { super(os); enableReplaceObject(true); } /** * @throws java.io.IOException Any exception thrown by the underlying OutputStream. */ protected void annotateClass(Class cl) throws IOException { super.annotateClass(cl); } /** * @throws java.io.IOException Any exception thrown by the underlying OutputStream. */ protected void annotateProxyClass(Class cl) throws IOException { super.annotateProxyClass(cl); } /** Override replaceObject to check for Remote objects that are not RemoteStubs. */ protected Object replaceObject(Object obj) throws IOException { if( (obj instanceof Remote) && !(obj instanceof RemoteStub) ) { Remote remote = (Remote) obj; try { obj = RemoteObject.toStub(remote); } catch(IOException ignore) { // Let the Serialization layer try with the orignal obj } } return obj; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/stream/Streams.java0000644000175000017500000003421510470642610032731 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.stream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import org.jboss.logging.Logger; /** * A collection of stream related utility methods. * *

Exceptions that are thrown and not explicitly declared are ignored. * * @version $Revision: 1958 $ * @author Jason Dillon */ public final class Streams { private static final Logger log = Logger.getLogger(Streams.class); ///////////////////////////////////////////////////////////////////////// // Closing // ///////////////////////////////////////////////////////////////////////// /** * Attempt to close an InputStream. * * @param stream InputStream to attempt to close. * @return True if stream was closed (or stream was null), * or false if an exception was thrown. */ public static boolean close(final InputStream stream) { // do not attempt to close null stream, but return sucess if (stream == null) { return true; } boolean success = true; try { stream.close(); } catch (IOException e) { success = false; } return success; } /** * Attempt to close an OutputStream. * * @param stream OutputStream to attempt to close. * @return True if stream was closed (or stream was null), * or false if an exception was thrown. */ public static boolean close(final OutputStream stream) { // do not attempt to close null stream, but return sucess if (stream == null) { return true; } boolean success = true; try { stream.close(); } catch (IOException e) { success = false; } return success; } /** * Attempt to close an InputStream or OutputStream. * * @param stream Stream to attempt to close. * @return True if stream was closed (or stream was null), * or false if an exception was thrown. * * @throws IllegalArgumentException Stream is not an InputStream * or OuputStream. */ public static boolean close(final Object stream) { boolean success = false; if (stream instanceof InputStream) { success = close((InputStream)stream); } else if (stream instanceof OutputStream) { success = close((OutputStream)stream); } else { throw new IllegalArgumentException ("stream is not an InputStream or OutputStream"); } return success; } /** * Attempt to close an array of InputStreams. * * @param streams Array of InputStreams to attempt to close. * @return True if all streams were closed, or false * if an exception was thrown. */ public static boolean close(final InputStream[] streams) { boolean success = true; for (int i=0; iOutputStreams. * * @param streams Array of OutputStreams to attempt to close. * @return True if all streams were closed, or false * if an exception was thrown. */ public static boolean close(final OutputStream[] streams) { boolean success = true; for (int i=0; iInputStreama and/or * OutputStreams. * * @param streams Array of streams to attempt to close. * @return True if all streams were closed, or false * if an exception was thrown. * * @throws IllegalArgumentException Stream is not an InputStream * or OuputStream. Closing * stops at the last valid stream * object in this case. */ public static boolean close(final Object[] streams) { boolean success = true; for (int i=0; iOutputStream. * * @param stream OutputStream to attempt to flush and close. * @return True if stream was flushed and closed, or * false if an exception was thrown. */ public static boolean fclose(final OutputStream stream) { return flush(stream) && close(stream); } /** * Attempt to flush and close an array of OutputStreams. * * @param streams OutputStreams to attempt to flush and close. * @return True if all streams were flushed and closed, * or false if an exception was thrown. */ public static boolean fclose(final OutputStream[] streams) { boolean success = true; for (int i=0; iOutputStream. * * @param stream OutputStream to attempt to flush. * @return True if stream was flushed (or stream was null), * or false if an exception was thrown. */ public static boolean flush(final OutputStream stream) { // do not attempt to close null stream, but return sucess if (stream == null) { return true; } boolean success = true; try { stream.flush(); } catch (IOException e) { success = false; } return success; } /** * Attempt to flush an array of OutputStreams. * * @param streams OutputStreams to attempt to flush. * @return True if all streams were flushed, or false * if an exception was thrown. */ public static boolean flush(final OutputStream[] streams) { boolean success = true; for (int i=0; i

Stream related classes.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/0000755000175000017500000000000011105642363030252 5ustar twernertwerner././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/DFSVisitor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/DFSVisitor.java0000644000175000017500000000335010774222622033115 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; /** * A spanning tree visitor callback interface * * @see Graph#dfsSpanningTree(Vertex, DFSVisitor) * * @author Scott.Stark@jboss.org * @version $Revision$ * @param */ public interface DFSVisitor { /** * Called by the graph traversal methods when a vertex is first visited. * * @param g - the graph * @param v - the vertex being visited. */ public void visit(Graph g, Vertex v); /** * Used dfsSpanningTree to notify the visitor of each outgoing edge to * an unvisited vertex. * * @param g - the graph * @param v - the vertex being visited * @param e - the outgoing edge from v */ public void visit(Graph g, Vertex v, Edge e); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/Visitor.java0000644000175000017500000000257310774222622032566 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; /** * A graph visitor interface. * * @author Scott.Stark@jboss.org * @version $Revision$ * @param */ public interface Visitor { /** * Called by the graph traversal methods when a vertex is first visited. * * @param g - the graph * @param v - the vertex being visited. */ public void visit(Graph g, Vertex v); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/Graph.java0000644000175000017500000003300510774222622032162 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * A directed graph data structure. * * @author Scott.Stark@jboss.org * @version $Revision$ * @param */ @SuppressWarnings("unchecked") public class Graph { /** Color used to mark unvisited nodes */ public static final int VISIT_COLOR_WHITE = 1; /** Color used to mark nodes as they are first visited in DFS order */ public static final int VISIT_COLOR_GREY = 2; /** Color used to mark nodes after descendants are completely visited */ public static final int VISIT_COLOR_BLACK = 3; /** Vector of graph verticies */ private List> verticies; /** Vector of edges in the graph */ private List> edges; /** The vertex identified as the root of the graph */ private Vertex rootVertex; /** * Construct a new graph without any vertices or edges */ public Graph() { verticies = new ArrayList>(); edges = new ArrayList>(); } /** * Are there any verticies in the graph * @return true if there are no verticies in the graph */ public boolean isEmpty() { return verticies.size() == 0; } /** * Add a vertex to the graph * @param v the Vertex to add * @return true if the vertex was added, false if it was already in the graph. */ public boolean addVertex(Vertex v) { boolean added = false; if( verticies.contains(v) == false ) { added = verticies.add(v); } return added; } /** * Get the vertex count. * @return the number of verticies in the graph. */ public int size() { return verticies.size(); } /** * Get the root vertex * @return the root vertex if one is set, null if no vertex has been set as the root. */ public Vertex getRootVertex() { return rootVertex; } /** * Set a root vertex. If root does no exist in the graph it is added. * @param root - the vertex to set as the root and optionally add if it * does not exist in the graph. */ public void setRootVertex(Vertex root) { this.rootVertex = root; if( verticies.contains(root) == false ) this.addVertex(root); } /** * Get the given Vertex. * @param n the index [0, size()-1] of the Vertex to access * @return the nth Vertex */ public Vertex getVertex(int n) { return verticies.get(n); } /** * Get the graph verticies * * @return the graph verticies */ public List> getVerticies() { return this.verticies; } /** * Insert a directed, weighted Edge into the graph. * * @param from - the Edge starting vertex * @param to - the Edge ending vertex * @param cost - the Edge weight/cost * @return true if the Edge was added, false if from already has this Edge * @throws IllegalArgumentException if from/to are not verticies in * the graph */ public boolean addEdge(Vertex from, Vertex to, int cost) throws IllegalArgumentException { if( verticies.contains(from) == false ) throw new IllegalArgumentException("from is not in graph"); if( verticies.contains(to) == false ) throw new IllegalArgumentException("to is not in graph"); Edge e = new Edge(from, to, cost); if (from.findEdge(to) != null) return false; else { from.addEdge(e); to.addEdge(e); edges.add(e); return true; } } /** * Insert a bidirectional Edge in the graph * * @param from - the Edge starting vertex * @param to - the Edge ending vertex * @param cost - the Edge weight/cost * @return true if edges between both nodes were added, false otherwise * @throws IllegalArgumentException if from/to are not verticies in * the graph */ public boolean insertBiEdge(Vertex from, Vertex to, int cost) throws IllegalArgumentException { return addEdge(from, to, cost) && addEdge(to, from, cost); } /** * Get the graph edges * @return the graph edges */ public List> getEdges() { return this.edges; } /** * Remove a vertex from the graph * @param v the Vertex to remove * @return true if the Vertex was removed */ public boolean removeVertex(Vertex v) { if (!verticies.contains(v)) return false; verticies.remove(v); if( v == rootVertex ) rootVertex = null; // Remove the edges associated with v for(int n = 0; n < v.getOutgoingEdgeCount(); n ++) { Edge e = v.getOutgoingEdge(n); v.remove(e); Vertex to = e.getTo(); to.remove(e); edges.remove(e); } for(int n = 0; n < v.getIncomingEdgeCount(); n ++) { Edge e = v.getIncomingEdge(n); v.remove(e); Vertex predecessor = e.getFrom(); predecessor.remove(e); } return true; } /** * Remove an Edge from the graph * @param from - the Edge starting vertex * @param to - the Edge ending vertex * @return true if the Edge exists, false otherwise */ public boolean removeEdge(Vertex from, Vertex to) { Edge e = from.findEdge(to); if (e == null) return false; else { from.remove(e); to.remove(e); edges.remove(e); return true; } } /** * Clear the mark state of all verticies in the graph by calling * clearMark() on all verticies. * @see Vertex#clearMark() */ public void clearMark() { for (Vertex w : verticies) w.clearMark(); } /** * Clear the mark state of all edges in the graph by calling * clearMark() on all edges. */ public void clearEdges() { for (Edge e : edges) e.clearMark(); } /** * Perform a depth first serach using recursion. * @param v - the Vertex to start the search from * @param visitor - the vistor to inform prior to * @see Visitor#visit(Graph, Vertex) */ public void depthFirstSearch(Vertex v, final Visitor visitor) { VisitorEX wrapper = new VisitorEX() { public void visit(Graph g, Vertex v) throws RuntimeException { if (visitor != null) visitor.visit(g, v); } }; this.depthFirstSearch(v, wrapper); } /** * Perform a depth first serach using recursion. The search may * be cut short if the visitor throws an exception. * @param * * @param v - the Vertex to start the search from * @param visitor - the vistor to inform prior to * @see Visitor#visit(Graph, Vertex) * @throws E if visitor.visit throws an exception */ public void depthFirstSearch(Vertex v, VisitorEX visitor) throws E { if( visitor != null ) visitor.visit(this, v); v.visit(); for (int i = 0; i < v.getOutgoingEdgeCount(); i++) { Edge e = v.getOutgoingEdge(i); if (!e.getTo().visited()) { depthFirstSearch(e.getTo(), visitor); } } } /** * Perform a breadth first search of this graph, starting at v. * * @param v - the search starting point * @param visitor - the vistor whose vist method is called prior * to visting a vertex. */ public void breadthFirstSearch(Vertex v, final Visitor visitor) { VisitorEX wrapper = new VisitorEX() { public void visit(Graph g, Vertex v) throws RuntimeException { if (visitor != null) visitor.visit(g, v); } }; this.breadthFirstSearch(v, wrapper); } /** * Perform a breadth first search of this graph, starting at v. The * vist may be cut short if visitor throws an exception during * a vist callback. * @param * * @param v - the search starting point * @param visitor - the vistor whose vist method is called prior * to visting a vertex. * @throws E if vistor.visit throws an exception */ public void breadthFirstSearch(Vertex v, VisitorEX visitor) throws E { LinkedList> q = new LinkedList>(); q.add(v); if( visitor != null ) visitor.visit(this, v); v.visit(); while (q.isEmpty() == false) { v = q.removeFirst(); for (int i = 0; i < v.getOutgoingEdgeCount(); i++) { Edge e = v.getOutgoingEdge(i); Vertex to = e.getTo(); if (!to.visited()) { q.add(to); if( visitor != null ) visitor.visit(this, to); to.visit(); } } } } /** * Find the spanning tree using a DFS starting from v. * @param v - the vertex to start the search from * @param visitor - visitor invoked after each vertex * is visited and an edge is added to the tree. */ public void dfsSpanningTree(Vertex v, DFSVisitor visitor) { v.visit(); if( visitor != null ) visitor.visit(this, v); for (int i = 0; i < v.getOutgoingEdgeCount(); i++) { Edge e = v.getOutgoingEdge(i); if (!e.getTo().visited()) { if( visitor != null ) visitor.visit(this, v, e); e.mark(); dfsSpanningTree(e.getTo(), visitor); } } } /** * Search the verticies for one with name. * * @param name - the vertex name * @return the first vertex with a matching name, null if no * matches are found */ public Vertex findVertexByName(String name) { Vertex match = null; for(Vertex v : verticies) { if( name.equals(v.getName()) ) { match = v; break; } } return match; } /** * Search the verticies for one with data. * * @param data - the vertex data to match * @param compare - the comparator to perform the match * @return the first vertex with a matching data, null if no * matches are found */ public Vertex findVertexByData(T data, Comparator compare) { Vertex match = null; for(Vertex v : verticies) { if( compare.compare(data, v.getData()) == 0 ) { match = v; break; } } return match; } /** Search the graph for cycles. In order to detect cycles, we use * a modified depth first search called a colored DFS. All nodes are * initially marked white. When a node is encountered, it is marked * grey, and when its descendants are completely visited, it is * marked black. If a grey node is ever encountered, then there is * a cycle. * @return the edges that form cycles in the graph. The array will * be empty if there are no cycles. */ public Edge[] findCycles() { ArrayList> cycleEdges = new ArrayList>(); // Mark all verticies as white for(int n = 0; n < verticies.size(); n ++) { Vertex v = getVertex(n); v.setMarkState(VISIT_COLOR_WHITE); } for(int n = 0; n < verticies.size(); n ++) { Vertex v = getVertex(n); visit(v, cycleEdges); } Edge[] cycles = new Edge[cycleEdges.size()]; cycleEdges.toArray(cycles); return cycles; } private void visit(Vertex v, ArrayList> cycleEdges) { v.setMarkState(VISIT_COLOR_GREY); int count = v.getOutgoingEdgeCount(); for(int n = 0; n < count; n ++) { Edge e = v.getOutgoingEdge(n); Vertex u = e.getTo(); if( u.getMarkState() == VISIT_COLOR_GREY ) { // A cycle Edge cycleEdges.add(e); } else if( u.getMarkState() == VISIT_COLOR_WHITE ) { visit(u, cycleEdges); } } v.setMarkState(VISIT_COLOR_BLACK); } public String toString() { StringBuffer tmp = new StringBuffer("Graph["); for (Vertex v : verticies) tmp.append(v); tmp.append(']'); return tmp.toString(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/Edge.java0000644000175000017500000000565610774222622032000 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; /** * A directed, weighted edge in a graph * * @author Scott.Stark@jboss.org * @version $Revision$ * @param */ public class Edge { private Vertex from; private Vertex to; private int cost; private boolean mark; /** * Create a zero cost edge between from and to * @param from the starting vertex * @param to the ending vertex */ public Edge(Vertex from, Vertex to) { this(from, to, 0); } /** * Create an edge between from and to with the given cost. * * @param from the starting vertex * @param to the ending vertex * @param cost the cost of the edge */ public Edge(Vertex from, Vertex to, int cost) { this.from = from; this.to = to; this.cost = cost; mark = false; } /** * Get the ending vertex * @return ending vertex */ public Vertex getTo() { return to; } /** * Get the starting vertex * @return starting vertex */ public Vertex getFrom() { return from; } /** * Get the cost of the edge * @return cost of the edge */ public int getCost() { return cost; } /** * Set the mark flag of the edge * */ public void mark() { mark = true; } /** * Clear the edge mark flag * */ public void clearMark() { mark = false; } /** * Get the edge mark flag * @return edge mark flag */ public boolean isMarked() { return mark; } /** * String rep of edge * @return string rep with from/to vertex names and cost */ public String toString() { StringBuffer tmp = new StringBuffer("Edge[from: "); tmp.append(from.getName()); tmp.append(",to: "); tmp.append(to.getName()); tmp.append(", cost: "); tmp.append(cost); tmp.append("]"); return tmp.toString(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/VisitorEX.java0000644000175000017500000000301410774222622033012 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; /** * A graph visitor interface that can throw an exception during * a visit callback. * * @author Scott.Stark@jboss.org * @version $Revision$ * @param * @param */ public interface VisitorEX { /** * Called by the graph traversal methods when a vertex is first visited. * * @param g - the graph * @param v - the vertex being visited. * @throws E exception for any error */ public void visit(Graph g, Vertex v) throws E; } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/graph/Vertex.java0000644000175000017500000002100110774222622032367 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.graph; import java.util.ArrayList; import java.util.List; /** * A named graph vertex with optional data. * * @author Scott.Stark@jboss.org * @version $Revision$ * @param */ @SuppressWarnings("unchecked") public class Vertex { private List> incomingEdges; private List> outgoingEdges; private String name; private boolean mark; private int markState; private T data; /** * Calls this(null, null). */ public Vertex() { this(null, null); } /** * Create a vertex with the given name and no data * @param n */ public Vertex(String n) { this(n, null); } /** * Create a Vertex with name n and given data * @param n - name of vertex * @param data - data associated with vertex */ public Vertex(String n, T data) { incomingEdges = new ArrayList>(); outgoingEdges = new ArrayList>(); name = n; mark = false; this.data = data; } /** * @return the possibly null name of the vertex */ public String getName() { return name; } /** * @return the possibly null data of the vertex */ public T getData() { return this.data; } /** * @param data The data to set. */ public void setData(T data) { this.data = data; } /** * Add an edge to the vertex. If edge.from is this vertex, its an * outgoing edge. If edge.to is this vertex, its an incoming * edge. If neither from or to is this vertex, the edge is * not added. * * @param e - the edge to add * @return true if the edge was added, false otherwise */ public boolean addEdge(Edge e) { if (e.getFrom() == this) outgoingEdges.add(e); else if (e.getTo() == this) incomingEdges.add(e); else return false; return true; } /** * Add an outgoing edge ending at to. * * @param to - the destination vertex * @param cost the edge cost */ public void addOutgoingEdge(Vertex to, int cost) { Edge out = new Edge(this, to, cost); outgoingEdges.add(out); } /** * Add an incoming edge starting at from * * @param from - the starting vertex * @param cost the edge cost */ public void addIncomingEdge(Vertex from, int cost) { Edge out = new Edge(this, from, cost); incomingEdges.add(out); } /** * Check the vertex for either an incoming or outgoing edge * mathcing e. * * @param e the edge to check * @return true it has an edge */ public boolean hasEdge(Edge e) { if (e.getFrom() == this) return incomingEdges.contains(e); else if (e.getTo() == this) return outgoingEdges.contains(e); else return false; } /** * Remove an edge from this vertex * * @param e - the edge to remove * @return true if the edge was removed, false if the * edge was not connected to this vertex */ public boolean remove(Edge e) { if (e.getFrom() == this) incomingEdges.remove(e); else if (e.getTo() == this) outgoingEdges.remove(e); else return false; return true; } /** * * @return the count of incoming edges */ public int getIncomingEdgeCount() { return incomingEdges.size(); } /** * Get the ith incoming edge * @param i the index into incoming edges * @return ith incoming edge */ public Edge getIncomingEdge(int i) { return incomingEdges.get(i); } /** * Get the incoming edges * @return incoming edge list */ public List getIncomingEdges() { return this.incomingEdges; } /** * * @return the count of incoming edges */ public int getOutgoingEdgeCount() { return outgoingEdges.size(); } /** * Get the ith outgoing edge * @param i the index into outgoing edges * @return ith outgoing edge */ public Edge getOutgoingEdge(int i) { return outgoingEdges.get(i); } /** * Get the outgoing edges * @return outgoing edge list */ public List getOutgoingEdges() { return this.outgoingEdges; } /** * Search the outgoing edges looking for an edge whose's * edge.to == dest. * @param dest the destination * @return the outgoing edge going to dest if one exists, * null otherwise. */ public Edge findEdge(Vertex dest) { for (Edge e : outgoingEdges) { if (e.getTo() == dest) return e; } return null; } /** * Search the outgoing edges for a match to e. * * @param e - the edge to check * @return e if its a member of the outgoing edges, null * otherwise. */ public Edge findEdge(Edge e) { if (outgoingEdges.contains(e)) return e; else return null; } /** * What is the cost from this vertext to the dest vertex. * * @param dest - the destination vertex. * @return Return Integer.MAX_VALUE if we have no edge to dest, * 0 if dest is this vertex, the cost of the outgoing edge * otherwise. */ public int cost(Vertex dest) { if (dest == this) return 0; Edge e = findEdge(dest); int cost = Integer.MAX_VALUE; if (e != null) cost = e.getCost(); return cost; } /** * Is there an outgoing edge ending at dest. * * @param dest - the vertex to check * @return true if there is an outgoing edge ending * at vertex, false otherwise. */ public boolean hasEdge(Vertex dest) { return (findEdge(dest) != null); } /** * Has this vertex been marked during a visit * @return true is visit has been called */ public boolean visited() { return mark; } /** * Set the vertex mark flag. * */ public void mark() { mark = true; } /** * Set the mark state to state. * * @param state the state */ public void setMarkState(int state) { markState = state; } /** * Get the mark state value. * @return the mark state */ public int getMarkState() { return markState; } /** * Visit the vertex and set the mark flag to true. * */ public void visit() { mark(); } /** * Clear the visited mark flag. * */ public void clearMark() { mark = false; } /** * @return a string form of the vertex with in and out * edges. */ public String toString() { StringBuffer tmp = new StringBuffer("Vertex("); tmp.append(name); tmp.append(", data="); tmp.append(data); tmp.append("), in:["); for (int i = 0; i < incomingEdges.size(); i++) { Edge e = incomingEdges.get(i); if( i > 0 ) tmp.append(','); tmp.append('{'); tmp.append(e.getFrom().name); tmp.append(','); tmp.append(e.getCost()); tmp.append('}'); } tmp.append("], out:["); for (int i = 0; i < outgoingEdges.size(); i++) { Edge e = outgoingEdges.get(i); if( i > 0 ) tmp.append(','); tmp.append('{'); tmp.append(e.getTo().name); tmp.append(','); tmp.append(e.getCost()); tmp.append('}'); } tmp.append(']'); return tmp.toString(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/JBossInterface.java0000644000175000017500000000350310470642610032655 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Clone the object without throwing a typed exception. * * @author Adrian Brock * @version $Revision: 1958 $ */ public interface JBossInterface extends Cloneable { // Constants ----------------------------------------------------- // Public -------------------------------------------------------- /** * Clone the object * * @return a clone of the object */ Object clone(); /** * Print a short version of the object * * @return the short string */ String toShortString(); /** * Append the key class properties to the buffer * * @param buffer the buffer */ void toShortString(JBossStringBuilder buffer); // Inner classes ------------------------------------------------- } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/LongCounter.java0000644000175000017500000001546710776226110032271 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; /** * A long integer counter class. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class LongCounter implements Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = 1615297462859270139L; /** The current count */ private long count; /** * Construct a LongCounter with a starting value. * * @param count Starting value for counter. */ public LongCounter(final long count) { this.count = count; } /** * Construct a LongCounter. */ public LongCounter() {} /** * Increment the counter. (Optional operation) * * @return The incremented value of the counter. */ public long increment() { return ++count; } /** * Decrement the counter. (Optional operation) * * @return The decremented value of the counter. */ public long decrement() { return --count; } /** * Return the current value of the counter. * * @return The current value of the counter. */ public long getCount() { return count; } /** * Reset the counter to zero. (Optional operation) */ public void reset() { this.count = 0; } /** * Check if the given object is equal to this. * * @param obj Object to test equality with. * @return True if object is equal to this. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { return ((LongCounter)obj).count == count; } return false; } /** * Return a string representation of this. * * @return A string representation of this. */ public String toString() { return String.valueOf(count); } /** * Return a cloned copy of this object. * * @return A cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ///////////////////////////////////////////////////////////////////////// // Wrappers // ///////////////////////////////////////////////////////////////////////// /** * Base wrapper class for other wrappers. */ private static class Wrapper extends LongCounter { /** The serialVersionUID */ private static final long serialVersionUID = 6720507617603163762L; /** The wrapped counter */ protected final LongCounter counter; public Wrapper(final LongCounter counter) { this.counter = counter; } public long increment() { return counter.increment(); } public long decrement() { return counter.decrement(); } public long getCount() { return counter.getCount(); } public void reset() { counter.reset(); } public boolean equals(final Object obj) { return counter.equals(obj); } public String toString() { return counter.toString(); } public Object clone() { return counter.clone(); } } /** * Return a synchronized counter. * * @param counter LongCounter to synchronize. * @return Synchronized counter. */ public static LongCounter makeSynchronized(final LongCounter counter) { return new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 8903330696503363758L; public synchronized long increment() { return this.counter.increment(); } public synchronized long decrement() { return this.counter.decrement(); } public synchronized long getCount() { return this.counter.getCount(); } public synchronized void reset() { this.counter.reset(); } public synchronized int hashCode() { return this.counter.hashCode(); } public synchronized boolean equals(final Object obj) { return this.counter.equals(obj); } public synchronized String toString() { return this.counter.toString(); } public synchronized Object clone() { return this.counter.clone(); } }; } /** * Returns a directional counter. * * @param counter LongCounter to make directional. * @param increasing True to create an increasing only * or false to create a decreasing only. * @return A directional counter. */ public static LongCounter makeDirectional(final LongCounter counter, final boolean increasing) { LongCounter temp; if (increasing) { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -8902748795144754375L; public long decrement() { throw new UnsupportedOperationException(); } public void reset() { throw new UnsupportedOperationException(); } }; } else { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 2584758778978644599L; public long increment() { throw new UnsupportedOperationException(); } }; } return temp; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/MethodHashing.java0000644000175000017500000001474210774222622032551 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * Create a unique hash for * * @author Marc Fleury * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class MethodHashing { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- static Map hashMap = new WeakHashMap(); public static Method findMethodByHash(Class clazz, long hash) throws Exception { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methodHash(methods[i]) == hash) return methods[i]; } if (clazz.getSuperclass() != null) { return findMethodByHash(clazz.getSuperclass(), hash); } return null; } public static Constructor findConstructorByHash(Class clazz, long hash) throws Exception { Constructor[] cons = clazz.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) { if (constructorHash(cons[i]) == hash) return cons[i]; } if (clazz.getSuperclass() != null) { return findConstructorByHash(clazz.getSuperclass(), hash); } return null; } public static long methodHash(Method method) throws Exception { Class[] parameterTypes = method.getParameterTypes(); String methodDesc = method.getName()+"("; for(int j = 0; j < parameterTypes.length; j++) { methodDesc += getTypeString(parameterTypes[j]); } methodDesc += ")"+getTypeString(method.getReturnType()); long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); MessageDigest messagedigest = MessageDigest.getInstance("SHA"); DataOutputStream dataoutputstream = new DataOutputStream(new DigestOutputStream(bytearrayoutputstream, messagedigest)); dataoutputstream.writeUTF(methodDesc); dataoutputstream.flush(); byte abyte0[] = messagedigest.digest(); for(int j = 0; j < Math.min(8, abyte0.length); j++) hash += (long)(abyte0[j] & 0xff) << j * 8; return hash; } public static long constructorHash(Constructor method) throws Exception { Class[] parameterTypes = method.getParameterTypes(); String methodDesc = method.getName()+"("; for(int j = 0; j < parameterTypes.length; j++) { methodDesc += getTypeString(parameterTypes[j]); } methodDesc += ")"; long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); MessageDigest messagedigest = MessageDigest.getInstance("SHA"); DataOutputStream dataoutputstream = new DataOutputStream(new DigestOutputStream(bytearrayoutputstream, messagedigest)); dataoutputstream.writeUTF(methodDesc); dataoutputstream.flush(); byte abyte0[] = messagedigest.digest(); for(int j = 0; j < Math.min(8, abyte0.length); j++) hash += (long)(abyte0[j] & 0xff) << j * 8; return hash; } /** * Calculate method hashes. This algo is taken from RMI. * * @param intf * @return the map */ public static Map getInterfaceHashes(Class intf) { // Create method hashes Method[] methods = intf.getDeclaredMethods(); HashMap map = new HashMap(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; try { long hash = methodHash(method); map.put(method.toString(), new Long(hash)); } catch (Exception e) { } } return map; } static String getTypeString(Class cl) { if (cl == Byte.TYPE) { return "B"; } else if (cl == Character.TYPE) { return "C"; } else if (cl == Double.TYPE) { return "D"; } else if (cl == Float.TYPE) { return "F"; } else if (cl == Integer.TYPE) { return "I"; } else if (cl == Long.TYPE) { return "J"; } else if (cl == Short.TYPE) { return "S"; } else if (cl == Boolean.TYPE) { return "Z"; } else if (cl == Void.TYPE) { return "V"; } else if (cl.isArray()) { return "["+getTypeString(cl.getComponentType()); } else { return "L"+cl.getName().replace('.','/')+";"; } } /* * The use of hashCode is not enough to differenciate methods * we override the hashCode * * The hashes are cached in a static for efficiency * RO: WeakHashMap needed to support undeploy */ public static long calculateHash(Method method) { Map methodHashes = (Map)hashMap.get(method.getDeclaringClass()); if (methodHashes == null) { methodHashes = getInterfaceHashes(method.getDeclaringClass()); // Copy and add WeakHashMap newHashMap = new WeakHashMap(); newHashMap.putAll(hashMap); newHashMap.put(method.getDeclaringClass(), methodHashes); hashMap = newHashMap; } return ((Long)methodHashes.get(method.toString())).longValue(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/TimerTask.java0000644000175000017500000001145110774222622031724 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * A class that represent a task that can be scheduled for one-shot or * repeated execution by a {@link TimerQueue}.

* A similar class is present in java.util package of jdk version >= 1.3; * for compatibility with jdk 1.2 we reimplemented it. * * @see TimerQueue * * @author Simone Bordet * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public abstract class TimerTask implements Executable, Comparable { /** The state before the first execution */ static final int NEW = 1; /** The state after first execution if the TimerTask is repeating */ static final int SCHEDULED = 2; /** The state after first execution if the TimerTask is not repeating */ static final int EXECUTED = 3; /** The state when cancelled */ static final int CANCELLED = 4; // Attributes ---------------------------------------------------- private final Object m_lock = new Object(); private int m_state; // this is a constant, and need not be locked private final long m_period; private long m_nextExecutionTime; /** * Creates a TimerTask object that will be executed once. */ protected TimerTask() { m_state = NEW; m_period = 0; } /** * Creates a TimerTask object that will be executed every period * milliseconds.

* @param period the execution period; if zero, will be executed only once. */ protected TimerTask(long period) { m_state = NEW; if (period < 0) throw new IllegalArgumentException("Period can't be negative"); m_period = period; } /** * Cancels the next execution of this TimerTask (if any).
* If the TimerTask is executing it will prevent the next execution (if any). * @return true if one or more scheduled execution will not take place, * false otherwise. */ public boolean cancel() { synchronized (getLock()) { boolean ret = (m_state == SCHEDULED); m_state = CANCELLED; return ret; } } // Executable implementation --------------------------------------- /** * The task to be executed, to be implemented in subclasses. */ public abstract void execute() throws Exception; // Comparable implementation --------------------------------------- /** * A TimerTask is less than another if it will be scheduled before. * @throws ClassCastException if other is not a TimerTask, according to the Comparable contract */ public int compareTo(Object other) { if (other == this) return 0; TimerTask t = (TimerTask) other; long diff = getNextExecutionTime() - t.getNextExecutionTime(); return (int) diff; } /** Returns the mutex that syncs the access to this object */ Object getLock() { return m_lock; } /** Sets the state of execution of this TimerTask */ void setState(int state) { synchronized (getLock()) { m_state = state; } } /** Returns the state of execution of this TimerTask */ int getState() { synchronized (getLock()) { return m_state; } } /** Returns whether this TimerTask is periodic */ boolean isPeriodic() { return m_period > 0; } /** Returns the next execution time for this TimerTask */ long getNextExecutionTime() { synchronized (getLock()) { return m_nextExecutionTime; } } /** Sets the next execution time for this TimerTask */ void setNextExecutionTime(long time) { synchronized (getLock()) { m_nextExecutionTime = time; } } /** @return the period of this TimerTask */ protected long getPeriod() { return m_period; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Null.java0000644000175000017500000000460410776226110030733 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; /** * A class that represents null. * *

{@link Null#VALUE} is used to given an object variable a dual-mode * nullified value, where null would indicate that the value is * empty, and {@link Null#VALUE} would idicate that the value has been * set to null (or something to that effect). * * @version $Revision: 2800 $ * @author Jason Dillon */ public final class Null implements Serializable { /** The serialVersionUID */ private static final long serialVersionUID = -403173436435490144L; /** The primary instance of Null. */ public static final Null VALUE = new Null(); /** Do not allow public construction. */ private Null() {} /** * Return a string representation. * * @return Null */ public String toString() { return null; } /** * Returns zero. * * @return Zero. */ public int hashCode() { return 0; } /** * Check if the given object is a Null instance or null. * * @param obj Object to test. * @return True if the given object is a Null instance or null. */ public boolean equals(final Object obj) { if (obj == this) return true; return (obj == null || obj.getClass() == getClass()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/JBossStringBuilder.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/JBossStringBuilder.ja0000644000175000017500000003425310470642610033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; import java.util.Arrays; /** * A JBossStringBuilder, providing the same functionality as the * java5 StringBuilder, except no Appendable which is java5 specific. * * @author Adrian Brock * @version $Revision: 1958 $ */ public class JBossStringBuilder implements Serializable, CharSequence { /** Serialization */ private static final long serialVersionUID = 1874946609763446794L; /** The characters */ protected char[] chars; /** The position */ protected int pos; /** * Create a new StringBuilder with no characters and an intial * size of 16 */ public JBossStringBuilder() { this(16); } /** * Create a new StringBuilder with no characters * * @param capacity the initial capacity */ public JBossStringBuilder(int capacity) { chars = new char[capacity]; } /** * Create a new StringBuilder from the given string. * The initial capacity is the length of the string plus 16 * * @param string the string */ public JBossStringBuilder(String string) { this(string.length() + 16); append(string); } /** * Create a new StringBuilder from the given character sequence. * The initial capacity is the length of the sequence plus 16 * * @param charSequence the character sequence */ public JBossStringBuilder(CharSequence charSequence) { this(charSequence.length() + 16); append(charSequence); } /** * Create a new StringBuilder from the given character array * * @param ch the array */ public JBossStringBuilder(char[] ch) { this(ch, 0, ch.length); } /** * Create a new StringBuilder from the given character array * * @param ch the array * @param start the start of the array from which to take characters * @param length the lengh of the array from which to take characters */ public JBossStringBuilder(char[] ch, int start, int length) { this(length + 16); append(ch, start, length); } public JBossStringBuilder append(Object object) { return append(String.valueOf(object)); } public JBossStringBuilder append(String string) { if (string == null) string = "null"; int length = string.length(); if (length == 0) return this; int afterAppend = pos + length; if (afterAppend > chars.length) expandCapacity(afterAppend); string.getChars(0, length, chars, pos); pos = afterAppend; return this; } public JBossStringBuilder append(StringBuffer buffer) { if (buffer == null) return append("null"); int length = buffer.length(); if (length == 0) return this; int afterAppend = pos + length; if (afterAppend > chars.length) expandCapacity(afterAppend); buffer.getChars(0, length, chars, pos); pos = afterAppend; return this; } public JBossStringBuilder append(CharSequence charSequence) { if (charSequence == null) return append("null"); int length = charSequence.length(); if (length == 0) return this; return append(charSequence, 0, charSequence.length()); } public JBossStringBuilder append(CharSequence charSequence, int start, int end) { if (charSequence == null) return append("null"); if (start < 0 || end < 0 || start > end || start > charSequence.length()) throw new IndexOutOfBoundsException("Invalid start=" + start + " end=" + end + " length=" + charSequence.length()); int length = end - start; if (length == 0) return this; int afterAppend = pos + length; if (afterAppend > chars.length) expandCapacity(afterAppend); for (int i = start; i < end; ++i) chars[pos++] = charSequence.charAt(i); pos = afterAppend; return this; } public JBossStringBuilder append(char[] array) { if (array == null) return append("null"); if (array.length == 0) return this; String string = String.valueOf(array); return append(string); } public JBossStringBuilder append(char[] array, int offset, int length) { if (array == null) return append("null"); int arrayLength = array.length; if (offset < 0 || length < 0 || offset + length > arrayLength) throw new IndexOutOfBoundsException("Invalid offset=" + offset + " length=" + length + " array.length=" + arrayLength); if (length == 0 || arrayLength == 0) return this; String string = String.valueOf(array, offset, length); return append(string); } public JBossStringBuilder append(boolean primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder append(char primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder append(int primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder append(long primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder append(float primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder append(double primitive) { String string = String.valueOf(primitive); return append(string); } public JBossStringBuilder delete(int start, int end) { if (start < 0 || start > pos || start > end || end > pos) throw new IndexOutOfBoundsException("Invalid start=" + start + " end=" + end + " length=" + pos); if (start == end) return this; int removed = end - start; System.arraycopy(chars, start + removed, chars, start, pos - end); pos -= removed; return this; } public JBossStringBuilder deleteCharAt(int index) { return delete(index, 1); } public JBossStringBuilder replace(int start, int end, String string) { delete(start, end); return insert(start, string); } public JBossStringBuilder insert(int index, char[] string) { return insert(index, string, 0, string.length); } public JBossStringBuilder insert(int index, char[] string, int offset, int len) { int stringLength = string.length; if (index < 0 || index > pos || offset < 0 || len < 0 || (offset + len) > string.length) throw new IndexOutOfBoundsException("Invalid index=" + index + " offset=" + offset + " len=" + len + " string.length=" + stringLength + " length=" + pos); if (len == 0) return this; int afterAppend = pos + len; if (afterAppend > chars.length) expandCapacity(afterAppend); System.arraycopy(chars, index, chars, index + stringLength, pos - index); System.arraycopy(string, offset, chars, index, len); pos = afterAppend; return this; } public JBossStringBuilder insert(int offset, Object object) { if (object == null) return insert(offset, "null"); else return insert(offset, String.valueOf(object)); } public JBossStringBuilder insert(int offset, String string) { if (offset < 0 || offset > pos) throw new IndexOutOfBoundsException("Invalid offset=" + offset + " length=" + pos); if (string == null) string = "null"; int stringLength = string.length(); int afterAppend = pos + stringLength; if (afterAppend > chars.length) expandCapacity(afterAppend); System.arraycopy(chars, offset, chars, offset + stringLength, pos - offset); string.getChars(0, stringLength, chars, offset); pos = afterAppend; return this; } public JBossStringBuilder insert(int offset, CharSequence charSequence) { if (charSequence == null) return insert(offset, "null"); else return insert(offset, charSequence, 0, charSequence.length()); } public JBossStringBuilder insert(int offset, CharSequence charSequence, int start, int end) { if (charSequence == null) charSequence = "null"; int sequenceLength = charSequence.length(); if (offset < 0 || offset > pos || start < 0 || end < 0 || start > sequenceLength || end > sequenceLength || start > end) throw new IndexOutOfBoundsException("Invalid offset=" + offset + " start=" + start + " end=" + end + " sequence.length()=" + sequenceLength + " length=" + pos); int len = end - start; if (len == 0) return this; int afterAppend = pos + len; if (afterAppend > chars.length) expandCapacity(afterAppend); System.arraycopy(chars, offset, chars, offset + sequenceLength, pos - offset); for (int i = start; i < end; ++i) chars[offset++] = charSequence.charAt(i); pos = afterAppend; return this; } public JBossStringBuilder insert(int offset, boolean primitive) { return insert(offset, String.valueOf(primitive)); } public JBossStringBuilder insert(int offset, char primitive) { return insert(offset, String.valueOf(primitive)); } public JBossStringBuilder insert(int offset, int primitive) { return insert(offset, String.valueOf(primitive)); } public JBossStringBuilder insert(int offset, long primitive) { return insert(offset, String.valueOf(primitive)); } public JBossStringBuilder insert(int offset, float primitive) { return insert(offset, String.valueOf(primitive)); } public JBossStringBuilder insert(int offset, double primitive) { return insert(offset, String.valueOf(primitive)); } public int indexOf(String string) { return indexOf(string, 0); } public int indexOf(String string, int fromIndex) { // FIXME return toString().indexOf(string, fromIndex); } public int indexOf(char ch) { return indexOf(ch, 0); } public int indexOf(char ch, int fromIndex) { // FIXME return toString().indexOf(ch, fromIndex); } public int lastIndexOf(String string) { return lastIndexOf(string, pos); } public int lastIndexOf(String string, int fromIndex) { // FIXME return toString().lastIndexOf(string, fromIndex); } public int lastIndexOf(char ch) { return lastIndexOf(ch, pos); } public int lastIndexOf(char ch, int fromIndex) { // FIXME return toString().lastIndexOf(ch, fromIndex); } public JBossStringBuilder reverse() { char[] tmp = new char[pos]; for(int n = 0; n < pos; n ++) tmp[n] = chars[pos-n-1]; chars = tmp; return this; } public String toString() { return new String(chars, 0, pos); } public int length() { return pos; } public int capacity() { return chars.length; } public void ensureCapacity(int minimum) { if (minimum < 0 || minimum < chars.length) return; expandCapacity(minimum); } public void trimToSize() { char[] trimmed = new char[pos]; System.arraycopy(chars, 0, trimmed, 0, pos); chars = trimmed; } public void setLength(int newLength) { if (newLength < 0) throw new StringIndexOutOfBoundsException(newLength); if (newLength > chars.length) expandCapacity(newLength); Arrays.fill(chars, newLength, chars.length, '\0'); pos = newLength; } public char charAt(int index) { return chars[index]; } public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { if (srcBegin < 0 || dstBegin < 0 || srcBegin > srcEnd || srcEnd > pos || (dstBegin + srcEnd - srcBegin) > dst.length) throw new IndexOutOfBoundsException("Invalid srcBegin=" + srcBegin + " srcEnd=" + srcEnd + " dstBegin=" + dstBegin + " dst.length=" + dst.length + " length=" + pos); int len = srcEnd - srcBegin; if (len == 0) return; System.arraycopy(chars, srcBegin, dst, dstBegin, len); } public void setCharAt(int index, char ch) { if (index < 0 || index > pos) throw new IndexOutOfBoundsException("Invalid index=" + index + " length=" + pos); chars[index] = ch; } public String substring(int start) { return substring(start, pos); } public CharSequence subSequence(int start, int end) { return substring(start, end); } public String substring(int start, int end) { if (start < 0 || end < 0 || start > end || end > pos) throw new IndexOutOfBoundsException("Invalid start=" + start + " end=" + end + " length=" + pos); return new String(chars, start, end - start); } /** * Expand the capacity to the greater of the minimum * or twice the current size * * @param minimum the minimum */ protected void expandCapacity(int minimum) { int newSize = chars.length * 2; if (minimum > newSize) newSize = minimum; char[] newChars = new char[newSize]; System.arraycopy(chars, 0, newChars, 0, pos); chars = newChars; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/WeakObject.java0000644000175000017500000000732010774222622032037 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; /** * Convenience class to wrap an Object into a WeakReference. * *

Modified from java.util.WeakHashMap.WeakKey. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public final class WeakObject extends WeakReference { /** The hash code of the nested object */ protected final int hashCode; /** * Construct a WeakObject. * * @param obj Object to reference. */ public WeakObject(final Object obj) { super(obj); hashCode = obj.hashCode(); } /** * Construct a WeakObject. * * @param obj Object to reference. * @param queue Reference queue. */ public WeakObject(final Object obj, final ReferenceQueue queue) { super(obj, queue); hashCode = obj.hashCode(); } /** * Check the equality of an object with this. * * @param obj Object to test equality with. * @return True if object is equal. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { WeakObject soft = (WeakObject)obj; Object a = this.get(); Object b = soft.get(); if (a == null || b == null) return false; if (a == b) return true; return a.equals(b); } return false; } /** * Return the hash code of the nested object. * * @return The hash code of the nested object. */ public int hashCode() { return hashCode; } ///////////////////////////////////////////////////////////////////////// // Factory Methods // ///////////////////////////////////////////////////////////////////////// /** * Create a WeakObject for the given object. * * @param obj Object to reference. * @return WeakObject or null if object is null. */ public static WeakObject create(final Object obj) { if (obj == null) return null; else return new WeakObject(obj); } /** * Create a WeakObject for the given object. * * @param obj Object to reference. * @param queue Reference queue. * @return WeakObject or null if object is null. */ public static WeakObject create(final Object obj, final ReferenceQueue queue) { if (obj == null) return null; else return new WeakObject(obj, queue); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/0000755000175000017500000000000011105642363030422 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/Util.java0000644000175000017500000002657310774222622032222 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.naming; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.LinkRef; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import org.jboss.logging.Logger; /** A static utility class for common JNDI operations. * * @author Scott.Stark@jboss.org * @author adrian@jboss.com * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class Util { private static final Logger log = Logger.getLogger(Util.class); /** Create a subcontext including any intermediate contexts. @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx of the subcontext. @return The new or existing JNDI subcontext @throws javax.naming.NamingException on any JNDI failure */ public static Context createSubcontext(Context ctx, String name) throws NamingException { Name n = ctx.getNameParser("").parse(name); return createSubcontext(ctx, n); } /** Create a subcontext including any intermediate contexts. @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx of the subcontext. @return The new or existing JNDI subcontext @throws NamingException on any JNDI failure */ public static Context createSubcontext(Context ctx, Name name) throws NamingException { Context subctx = ctx; for (int pos = 0; pos < name.size(); pos++) { String ctxName = name.get(pos); try { subctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException e) { subctx = ctx.createSubcontext(ctxName); } // The current subctx will be the ctx for the next name component ctx = subctx; } return subctx; } /** Bind val to name in ctx, and make sure that all intermediate contexts exist @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx where value will be bound @param value the value to bind. @throws NamingException for any error */ public static void bind(Context ctx, String name, Object value) throws NamingException { Name n = ctx.getNameParser("").parse(name); bind(ctx, n, value); } /** Bind val to name in ctx, and make sure that all intermediate contexts exist @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx where value will be bound @param value the value to bind. @throws NamingException for any error */ public static void bind(Context ctx, Name name, Object value) throws NamingException { int size = name.size(); String atom = name.get(size - 1); Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1)); parentCtx.bind(atom, value); } /** Rebind val to name in ctx, and make sure that all intermediate contexts exist @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx where value will be bound @param value the value to bind. @throws NamingException for any error */ public static void rebind(Context ctx, String name, Object value) throws NamingException { Name n = ctx.getNameParser("").parse(name); rebind(ctx, n, value); } /** Rebind val to name in ctx, and make sure that all intermediate contexts exist @param ctx the parent JNDI Context under which value will be bound @param name the name relative to ctx where value will be bound @param value the value to bind. @throws NamingException for any error */ public static void rebind(Context ctx, Name name, Object value) throws NamingException { int size = name.size(); String atom = name.get(size - 1); Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1)); parentCtx.rebind(atom, value); } /** Unbinds a name from ctx, and removes parents if they are empty @param ctx the parent JNDI Context under which the name will be unbound @param name The name to unbind @throws NamingException for any error */ public static void unbind(Context ctx, String name) throws NamingException { unbind(ctx, ctx.getNameParser("").parse(name)); } /** Unbinds a name from ctx, and removes parents if they are empty @param ctx the parent JNDI Context under which the name will be unbound @param name The name to unbind @throws NamingException for any error */ public static void unbind(Context ctx, Name name) throws NamingException { ctx.unbind(name); //unbind the end node in the name int sz = name.size(); // walk the tree backwards, stopping at the domain while (--sz > 0) { Name pname = name.getPrefix(sz); try { ctx.destroySubcontext(pname); } catch (NamingException e) { log.trace("Unable to remove context " + pname, e); break; } } } /** * Lookup an object in the default initial context * * @param name the name to lookup * @param clazz the expected type * @return the object * @throws Exception for any error */ public static Object lookup(String name, Class clazz) throws Exception { InitialContext ctx = new InitialContext(); try { return lookup(ctx, name, clazz); } finally { ctx.close(); } } /** * Lookup an object in the default initial context * * @param name the name to lookup * @param clazz the expected type * @return the object * @throws Exception for any error */ public static Object lookup(Name name, Class clazz) throws Exception { InitialContext ctx = new InitialContext(); try { return lookup(ctx, name, clazz); } finally { ctx.close(); } } /** * Lookup an object in the given context * * @param context the context * @param name the name to lookup * @param clazz the expected type * @return the object * @throws Exception for any error */ public static Object lookup(Context context, String name, Class clazz) throws Exception { Object result = context.lookup(name); checkObject(context, name, result, clazz); return result; } /** * Lookup an object in the given context * * @param context the context * @param name the name to lookup * @param clazz the expected type * @return the object * @throws Exception for any error */ public static Object lookup(Context context, Name name, Class clazz) throws Exception { Object result = context.lookup(name); checkObject(context, name.toString(), result, clazz); return result; } /** * Create a link * * @param fromName the from name * @param toName the to name * @throws NamingException for any error */ public static void createLinkRef(String fromName, String toName) throws NamingException { InitialContext ctx = new InitialContext(); createLinkRef(ctx, fromName, toName); } /** * Create a link * * @param ctx the context * @param fromName the from name * @param toName the to name * @throws NamingException for any error */ public static void createLinkRef(Context ctx, String fromName, String toName) throws NamingException { LinkRef link = new LinkRef(toName); Context fromCtx = ctx; Name name = ctx.getNameParser("").parse(fromName); String atom = name.get(name.size()-1); for(int n = 0; n < name.size()-1; n ++) { String comp = name.get(n); try { fromCtx = (Context) fromCtx.lookup(comp); } catch(NameNotFoundException e) { fromCtx = fromCtx.createSubcontext(comp); } } log.debug("atom: " + atom); log.debug("link: " + link); fromCtx.rebind(atom, link); log.debug("Bound link " + fromName + " to " + toName); } /** * Remove the link ref * * @param name the name of the link binding * @throws NamingException for any error */ public static void removeLinkRef(String name) throws NamingException { InitialContext ctx = new InitialContext(); removeLinkRef(ctx, name); } /** * Remove the link ref * * @param ctx the context * @param name the name of the link binding * @throws NamingException for any error */ public static void removeLinkRef(Context ctx, String name) throws NamingException { log.debug("Unbinding link " + name); ctx.unbind(name); } /** * Checks an object implements the given class * * @param context the context * @param name the name to lookup * @param object the object * @param clazz the expected type * @throws Exception for any error */ protected static void checkObject(Context context, String name, Object object, Class clazz) throws Exception { Class objectClass = object.getClass(); if (clazz.isAssignableFrom(objectClass) == false) { StringBuffer buffer = new StringBuffer(100); buffer.append("Object at '").append(name); buffer.append("' in context ").append(context.getEnvironment()); buffer.append(" is not an instance of "); appendClassInfo(buffer, clazz); buffer.append(" object class is "); appendClassInfo(buffer, object.getClass()); throw new ClassCastException(buffer.toString()); } } /** * Append Class Info * * @param buffer the buffer to append to * @param clazz the class to describe */ protected static void appendClassInfo(StringBuffer buffer, Class clazz) { buffer.append("[class=").append(clazz.getName()); buffer.append(" classloader=").append(clazz.getClassLoader()); buffer.append(" interfaces={"); Class[] interfaces = clazz.getInterfaces(); for (int i=0; i 0) buffer.append(", "); buffer.append("interface=").append(interfaces[i].getName()); buffer.append(" classloader=").append(interfaces[i].getClassLoader()); } buffer.append("}]"); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/ENCThreadLocalKey.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/ENCThreadLocal0000644000175000017500000000546610774222622033073 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.naming; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.Reference; import javax.naming.RefAddr; import javax.naming.LinkRef; import javax.naming.spi.ObjectFactory; import org.jboss.logging.Logger; /** * Return a LinkRef based on a ThreadLocal key. * * @author Bill Burke * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class ENCThreadLocalKey implements ObjectFactory { private static final Logger log = Logger.getLogger(ENCThreadLocalKey.class); // We need all the weak maps to make sure everything is released properly // and we don't have any memory leaks private final static ThreadLocal key = new ThreadLocal(); public static void setKey(String tlkey) { key.set(tlkey); } public static String getKey() { return (String) key.get(); } public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { Reference ref = (Reference) obj; String reftype = (String) key.get(); boolean trace = log.isTraceEnabled(); if (reftype == null) { if (trace) log.trace("using default in ENC"); reftype = "default"; } RefAddr addr = ref.get(reftype); if (addr == null) { if (trace) log.trace("using default in ENC"); addr = ref.get("default"); // try to get default linking } if (addr != null) { String target = (String) addr.getContent(); if (trace) log.trace("found Reference " + reftype + " with content " + target); return new LinkRef(target); } return null; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/ReadOnlyContext.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/ReadOnlyContex0000644000175000017500000001376210774222622033257 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.naming; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.OperationNotSupportedException; /** A JNDI context wrapper implementation that delegates read-only methods to its delegate Context, and throws OperationNotSupportedException for any method with a side-effect. @author Scott.Stark@jboss.org @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class ReadOnlyContext implements Context { /** The actual context we impose the read-only behavior on */ private Context delegate; public ReadOnlyContext(Context delegate) { this.delegate = delegate; } // Supported methods ----------------------------------------------------------- public void close() throws NamingException { delegate.close(); } public String composeName(String name, String prefix) throws NamingException { return delegate.composeName(name, prefix); } public Name composeName(Name name, Name prefix) throws NamingException { return delegate.composeName(name, prefix); } public String getNameInNamespace() throws NamingException { return delegate.getNameInNamespace(); } public Hashtable getEnvironment() throws NamingException { return delegate.getEnvironment(); } public Object lookup(String name) throws NamingException { return delegate.lookup(name); } public Object lookupLink(String name) throws NamingException { return delegate.lookupLink(name); } public Object lookup(Name name) throws NamingException { return delegate.lookup(name); } public Object lookupLink(Name name) throws NamingException { return delegate.lookupLink(name); } public NameParser getNameParser(String name) throws NamingException { return delegate.getNameParser(name); } public NameParser getNameParser(Name name) throws NamingException { return delegate.getNameParser(name); } public NamingEnumeration list(String name) throws NamingException { return delegate.list(name); } public NamingEnumeration listBindings(String name) throws NamingException { return delegate.listBindings(name); } public NamingEnumeration list(Name name) throws NamingException { return delegate.list(name); } public NamingEnumeration listBindings(Name name) throws NamingException { return delegate.listBindings(name); } // Unsupported methods --------------------------------------------------------- public Object addToEnvironment(String propName, Object propVal) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void bind(String name, Object obj) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void bind(Name name, Object obj) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public Context createSubcontext(String name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public Context createSubcontext(Name name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void destroySubcontext(Name name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public Object removeFromEnvironment(String propName) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void rebind(String name, Object obj) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void rebind(Name name, Object obj) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void rename(Name oldName, Name newName) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void unbind(String name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } public void unbind(Name name) throws NamingException { throw new OperationNotSupportedException("This is a read-only Context"); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/NonSerializableFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/naming/NonSerializabl0000644000175000017500000002424610774222622033274 0ustar twernertwerner /* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.naming; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameAlreadyBoundException; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.RefAddr; import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; /** * A utility class that allows one to bind a non-serializable object into a * local JNDI context. The binding will only be valid for the lifetime of the * VM in which the JNDI InitialContext lives. An example usage code snippet is: *

    // The non-Serializable object to bind
    Object nonserializable = ...;
    // An arbitrary key to use in the StringRefAddr. The best key is the jndi
    // name that the object will be bound under.
    String key = ...;
    // This places nonserializable into the NonSerializableFactory hashmap under key
    NonSerializableFactory.rebind(key, nonserializable);

    Context ctx = new InitialContext();
    // Bind a reference to nonserializable using NonSerializableFactory as the ObjectFactory
    String className = nonserializable.getClass().getName();
    String factory = NonSerializableFactory.class.getName();
    StringRefAddr addr = new StringRefAddr("nns", key);
    Reference memoryRef = new Reference(className, addr, factory, null);
    ctx.rebind(key, memoryRef);
* * Or you can use the {@link #rebind(Context, String, Object)} convenience * method to simplify the number of steps to: *
    Context ctx = new InitialContext();
    // The non-Serializable object to bind
    Object nonserializable = ...;
    // The jndiName that the object will be bound into ctx with
    String jndiName = ...;
    // This places nonserializable into the NonSerializableFactory hashmap under key
    NonSerializableFactory.rebind(ctx, jndiName, nonserializable);
* * To unbind the object, use the following code snippet: *
	new InitialContext().unbind(key);
	NonSerializableFactory.unbind(key);
* * @see javax.naming.spi.ObjectFactory * @see #rebind(Context, String, Object) * * @author Scott Stark. * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class NonSerializableFactory implements ObjectFactory { private static Map wrapperMap = Collections.synchronizedMap(new HashMap()); /** Place an object into the NonSerializableFactory namespace for subsequent access by getObject. There cannot be an already existing binding for key. @param key the name to bind target under. This should typically be the name that will be used to bind target in the JNDI namespace, but it does not have to be. @param target the non-Serializable object to bind. @throws NameAlreadyBoundException thrown if key already exists in the NonSerializableFactory map */ public static synchronized void bind(String key, Object target) throws NameAlreadyBoundException { if( wrapperMap.containsKey(key) == true ) throw new NameAlreadyBoundException(key+" already exists in the NonSerializableFactory map"); wrapperMap.put(key, target); } /** Place or replace an object in the NonSerializableFactory namespce for subsequent access by getObject. Any existing binding for key will be replaced by target. @param key the name to bind target under. This should typically be the name that will be used to bind target in the JNDI namespace, but it does not have to be. @param target the non-Serializable object to bind. */ public static void rebind(String key, Object target) { wrapperMap.put(key, target); } /** Remove a binding from the NonSerializableFactory map. @param key the key into the NonSerializableFactory map to remove. @throws NameNotFoundException thrown if key does not exist in the NonSerializableFactory map */ public static void unbind(String key) throws NameNotFoundException { if( wrapperMap.remove(key) == null ) throw new NameNotFoundException(key+" was not found in the NonSerializableFactory map"); } /** Remove a binding from the NonSerializableFactory map. @param name the name for the key into NonSerializableFactory map to remove. The key is obtained as name.toString(). @throws NameNotFoundException thrown if key does not exist in the NonSerializableFactory map */ public static void unbind(Name name) throws NameNotFoundException { String key = name.toString(); if( wrapperMap.remove(key) == null ) throw new NameNotFoundException(key+" was not found in the NonSerializableFactory map"); } /** Lookup a value from the NonSerializableFactory map. * @param key @return the object bound to key is one exists, null otherwise. */ public static Object lookup(String key) { Object value = wrapperMap.get(key); return value; } /** Lookup a value from the NonSerializableFactory map. * @param name @return the object bound to key is one exists, null otherwise. */ public static Object lookup(Name name) { String key = name.toString(); Object value = wrapperMap.get(key); return value; } /** A convience method that simplifies the process of rebinding a non-zerializable object into a JNDI context. @param ctx the JNDI context to rebind to. @param key the key to use in both the NonSerializableFactory map and JNDI. It must be a valid name for use in ctx.bind(). @param target the non-Serializable object to bind. @throws NamingException thrown on failure to rebind key into ctx. */ public static synchronized void rebind(Context ctx, String key, Object target) throws NamingException { NonSerializableFactory.rebind(key, target); // Bind a reference to target using NonSerializableFactory as the ObjectFactory String className = target.getClass().getName(); String factory = NonSerializableFactory.class.getName(); StringRefAddr addr = new StringRefAddr("nns", key); Reference memoryRef = new Reference(className, addr, factory, null); ctx.rebind(key, memoryRef); } /** A convience method that simplifies the process of rebinding a non-zerializable object into a JNDI context. This version binds the target object into the default IntitialContext using name path. @param name the name to use as JNDI path name. The key into the NonSerializableFactory map is obtained from the toString() value of name. The name parameter cannot be a 0 length name. Any subcontexts between the root and the name must exist. @param target the non-Serializable object to bind. @throws NamingException thrown on failure to rebind key into ctx. */ public static synchronized void rebind(Name name, Object target) throws NamingException { rebind(name, target, false); } /** A convience method that simplifies the process of rebinding a non-zerializable object into a JNDI context. This version binds the target object into the default IntitialContext using name path. @param name the name to use as JNDI path name. The key into the NonSerializableFactory map is obtained from the toString() value of name. The name parameter cannot be a 0 length name. @param target the non-Serializable object to bind. @param createSubcontexts a flag indicating if subcontexts of name should be created if they do not already exist. @throws NamingException thrown on failure to rebind key into ctx. */ public static synchronized void rebind(Name name, Object target, boolean createSubcontexts) throws NamingException { String key = name.toString(); InitialContext ctx = new InitialContext(); if( createSubcontexts == true && name.size() > 1 ) { int size = name.size() - 1; Util.createSubcontext(ctx, name.getPrefix(size)); } rebind(ctx, key, target); } // --- Begin ObjectFactory interface methods /** Transform the obj Reference bound into the JNDI namespace into the actual non-Serializable object. @param obj the object bound in the JNDI namespace. This must be an implementation of javax.naming.Reference with a javax.naming.RefAddr of type "nns" whose content is the String key used to location the non-Serializable object in the NonSerializableFactory map. @param name ignored. @param nameCtx ignored. @param env ignored. @return the non-Serializable object associated with the obj Reference if one exists, null if one does not. */ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable env) throws Exception { // Get the nns value from the Reference obj and use it as the map key Reference ref = (Reference) obj; RefAddr addr = ref.get("nns"); String key = (String) addr.getContent(); Object target = wrapperMap.get(key); return target; } // --- End ObjectFactory interface methods } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/UnexpectedThrowable.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/UnexpectedThrowable.j0000644000175000017500000000457210776226110033311 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Thrown to indicate that a Throwable was caught but was not expected. * This is typical when catching Throwables to handle and rethrow Exceptions * and Errors. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class UnexpectedThrowable extends NestedError { /** The serialVersionUID */ private static final long serialVersionUID = 4318032849691437298L; /** * Construct a UnexpectedThrowable with the specified * detail message. * * @param msg Detail message. */ public UnexpectedThrowable(final String msg) { super(msg); } /** * Construct a UnexpectedThrowable with the specified * detail message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public UnexpectedThrowable(final String msg, final Throwable nested) { super(msg, nested); } /** * Construct a UnexpectedThrowable with the specified * nested Throwable. * * @param nested Nested Throwable. */ public UnexpectedThrowable(final Throwable nested) { super(nested); } /** * Construct a UnexpectedThrowable with no detail. */ public UnexpectedThrowable() { super(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/ThrowableListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/ThrowableListener.jav0000644000175000017500000000273410470642610033315 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.EventListener; /** * An interface used to handle Throwable events. * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface ThrowableListener extends EventListener { /** * Process a throwable. * * @param type The type off the throwable. * @param t Throwable */ void onThrowable(int type, Throwable t); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Executable.java0000644000175000017500000000243210774222622032101 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Interface for the execution of a task. * * @see WorkerQueue * * @author Simone Bordet * @version $Revision: 2787 $ */ public interface Executable { void execute() throws Exception; } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/CachePolicy.java0000644000175000017500000000662510774222622032213 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Interface that specifies a policy for caches.

* Implementation classes can implement a LRU policy, a random one, * a MRU one, or any other suitable policy. * * @author Simone Bordet * @version $Revision: 2787 $ */ public interface CachePolicy { /** * Returns the object paired with the specified key if it's * present in the cache, otherwise must return null.
* Implementations of this method must have complexity of order O(1). * Differently from {@link #peek} this method not only return whether * the object is present in the cache or not, but also * applies the implemented policy that will "refresh" the cached * object in the cache, because this cached object * was really requested. * * @param key the key paired with the object * @return the object * @see #peek */ Object get(Object key); /** * Returns the object paired with the specified key if it's * present in the cache, otherwise must return null.
* Implementations of this method must have complexity of order O(1). * This method should not apply the implemented caching policy to the * object paired with the given key, so that a client can * query if an object is cached without "refresh" its cache status. Real * requests for the object must be done using {@link #get}. * * @param key the key paired with the object * @see #get * @return the object */ Object peek(Object key); /** * Inserts the specified object into the cache following the * implemented policy.
* Implementations of this method must have complexity of order O(1). * * @param key the key paired with the object * @param object the object to cache * @see #remove */ void insert(Object key, Object object); /** * Remove the cached object paired with the specified key.
* Implementations of this method must have complexity of order O(1). * * @param key the key paired with the object * @see #insert */ void remove(Object key); /** * Flushes the cached objects from the cache. */ void flush(); /** * @return the size of the cache */ int size(); void create() throws Exception; void start() throws Exception; void stop(); void destroy(); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NoSuchMethodException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NoSuchMethodException0000644000175000017500000000573010776226110033321 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.reflect.Method; /** * A better NoSuchMethodException which can take a Method object * and formats the detail message based on in. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NoSuchMethodException extends java.lang.NoSuchMethodException { /** The serialVersionUID */ private static final long serialVersionUID = -3044955578250977290L; /** * Construct a NoSuchMethodException with the specified detail * message. * * @param msg Detail message. */ public NoSuchMethodException(String msg) { super(msg); } /** * Construct a NoSuchMethodException using the given method * object to construct the detail message. * * @param method Method to determine detail message from. */ public NoSuchMethodException(Method method) { super(format(method)); } /** * Construct a NoSuchMethodException using the given method * object to construct the detail message. * * @param msg Detail message prefix. * @param method Method to determine detail message suffix from. */ public NoSuchMethodException(String msg, Method method) { super(msg + format(method)); } /** * Construct a NoSuchMethodException with no detail. */ public NoSuchMethodException() { super(); } public static String format(Method method) { StringBuffer buffer = new StringBuffer(); buffer.append(method.getName()).append("("); Class[] paramTypes = method.getParameterTypes(); for (int count = 0; count < paramTypes.length; count++) { if (count > 0) { buffer.append(","); } buffer. append(paramTypes[count].getName().substring(paramTypes[count].getName().lastIndexOf(".")+1)); } buffer.append(")"); return buffer.toString(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NullArgumentException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NullArgumentException0000644000175000017500000000654110776226110033377 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Thrown to indicate that a method argument was null and * should not have been. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NullArgumentException extends IllegalArgumentException { /** The serialVersionUID */ private static final long serialVersionUID = -2308503249278841584L; /** The name of the argument that was null. */ protected final String name; /** The index of the argument or null if no index. */ protected final Object index; /** * Construct a NullArgumentException. * * @param name Argument name. */ public NullArgumentException(final String name) { super(makeMessage(name)); this.name = name; this.index = null; } /** * Construct a NullArgumentException. * * @param name Argument name. * @param index Argument index. */ public NullArgumentException(final String name, final long index) { super(makeMessage(name, new Long(index))); this.name = name; this.index = new Long(index); } /** * Construct a NullArgumentException. * * @param name Argument name. * @param index Argument index. */ public NullArgumentException(final String name, final Object index) { super(makeMessage(name, index)); this.name = name; this.index = index; } /** * Construct a NullArgumentException. */ public NullArgumentException() { this.name = null; this.index = null; } /** * Get the argument name that was null. * * @return The argument name that was null. */ public final String getArgumentName() { return name; } /** * Get the argument index. * * @return The argument index. */ public final Object getArgumentIndex() { return index; } /** * Make a execption message for the argument name. */ private static String makeMessage(final String name) { return "'" + name + "' is null"; } /** * Make a execption message for the argument name and index */ private static String makeMessage(final String name, final Object index) { return "'" + name + "[" + index + "]' is null"; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedThrowable.java0000644000175000017500000001754010774222622033120 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; import java.io.Serializable; import org.jboss.logging.Logger; import org.jboss.util.platform.Java; /** * Interface which is implemented by all the nested throwable flavors. * * @version $Revision: 2787 $ * @author Jason Dillon */ public interface NestedThrowable extends Serializable { /** * A system wide flag to enable or disable printing of the * parent throwable traces. * *

* This value is set from the system property * org.jboss.util.NestedThrowable.parentTraceEnabled * or if that is not set defaults to true. */ boolean PARENT_TRACE_ENABLED = Util.getBoolean("parentTraceEnabled", true); /** * A system wide flag to enable or disable printing of the * nested detail throwable traces. * *

* This value is set from the system property * org.jboss.util.NestedThrowable.nestedTraceEnabled * or if that is not set defaults to true unless * using JDK 1.4 with {@link #PARENT_TRACE_ENABLED} set to false, * then false since there is a native mechansim for this there. * *

* Note then when running under 1.4 is is not possible to disable * the nested trace output, since that is handled by java.lang.Throwable * which we delegate the parent printing to. */ boolean NESTED_TRACE_ENABLED = Util.getBoolean("nestedTraceEnabled", (Java.isCompatible(Java.VERSION_1_4) && !PARENT_TRACE_ENABLED) || !Java.isCompatible(Java.VERSION_1_4)); /** * A system wide flag to enable or disable checking of parent and child * types to detect uneeded nesting * *

* This value is set from the system property * org.jboss.util.NestedThrowable.detectDuplicateNesting * or if that is not set defaults to true. */ boolean DETECT_DUPLICATE_NESTING = Util.getBoolean("detectDuplicateNesting", true); /** * Return the nested throwable. * * @return Nested throwable. */ Throwable getNested(); /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ Throwable getCause(); ///////////////////////////////////////////////////////////////////////// // Nested Throwable Utilities // ///////////////////////////////////////////////////////////////////////// /** * Utilitiy methods for the various flavors of * NestedThrowable. */ final class Util { // Can not be final due to init bug, see getLogger() for details private static Logger log = Logger.getLogger(NestedThrowable.class); /** * Something is very broken with class nesting, which can sometimes * leave log uninitialized durring one of the following method calls. * *

* This is a HACK to keep those methods from NPE until this problem * can be resolved. */ private static Logger getLogger() { if (log == null) log = Logger.getLogger(NestedThrowable.class); return log; } protected static boolean getBoolean(String name, boolean defaultValue) { name = NestedThrowable.class.getName() + "." + name; String value = System.getProperty(name, String.valueOf(defaultValue)); // HACK see getLogger() for details log = getLogger(); log.debug(name + "=" + value); return new Boolean(value).booleanValue(); } public static void checkNested(final NestedThrowable parent, final Throwable child) { if (!DETECT_DUPLICATE_NESTING || parent == null || child == null) return; Class parentType = parent.getClass(); Class childType = child.getClass(); // // This might be backwards... I always get this confused // if (parentType.isAssignableFrom(childType)) { // HACK see getLogger() for details log = getLogger(); log.warn("Duplicate throwable nesting of same base type: " + parentType + " is assignable from: " + childType); } } /** * Returns a formated message for the given detail message * and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. * @return Formatted message. */ public static String getMessage(final String msg, final Throwable nested) { StringBuffer buff = new StringBuffer(msg == null ? "" : msg); if (nested != null) { buff.append(msg == null ? "- " : "; - ") .append("nested throwable: (") .append(nested) .append(")"); } return buff.toString(); } /** * Prints the nested Throwable to the given stream. * * @param nested Nested Throwable. * @param stream Stream to print to. */ public static void print(final Throwable nested, final PrintStream stream) { if (stream == null) throw new NullArgumentException("stream"); if (NestedThrowable.NESTED_TRACE_ENABLED && nested != null) { synchronized (stream) { if (NestedThrowable.PARENT_TRACE_ENABLED) { stream.print(" + nested throwable: "); } else { stream.print("[ parent trace omitted ]: "); } nested.printStackTrace(stream); } } } /** * Prints the nested Throwable to the given writer. * * @param nested Nested Throwable. * @param writer Writer to print to. */ public static void print(final Throwable nested, final PrintWriter writer) { if (writer == null) throw new NullArgumentException("writer"); if (NestedThrowable.NESTED_TRACE_ENABLED && nested != null) { synchronized (writer) { if (NestedThrowable.PARENT_TRACE_ENABLED) { writer.print(" + nested throwable: "); } else { writer.print("[ parent trace omitted ]: "); } nested.printStackTrace(writer); } } } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/0000755000175000017500000000000011105642363030070 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarUtils.java0000644000175000017500000003316410774222622032502 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; /** A utility class for dealing with Jar files. @author Scott.Stark@jboss.org @version $Revision: 2787 $ */ public final class JarUtils { /** * Hide the constructor */ private JarUtils() { } /** *

This function will create a Jar archive containing the src * file/directory. The archive will be written to the specified * OutputStream.

* *

This is a shortcut for
* jar(out, new File[] { src }, null, null, null);

* * @param out The output stream to which the generated Jar archive is * written. * @param src The file or directory to jar up. Directories will be * processed recursively. * @throws IOException */ public static void jar(OutputStream out, File src) throws IOException { jar(out, new File[] { src }, null, null, null); } /** *

This function will create a Jar archive containing the src * file/directory. The archive will be written to the specified * OutputStream.

* *

This is a shortcut for
* jar(out, src, null, null, null);

* * @param out The output stream to which the generated Jar archive is * written. * @param src The file or directory to jar up. Directories will be * processed recursively. * @throws IOException */ public static void jar(OutputStream out, File[] src) throws IOException { jar(out, src, null, null, null); } /** *

This function will create a Jar archive containing the src * file/directory. The archive will be written to the specified * OutputStream. Directories are processed recursively, applying the * specified filter if it exists. * *

This is a shortcut for
* jar(out, src, filter, null, null);

* * @param out The output stream to which the generated Jar archive is * written. * @param src The file or directory to jar up. Directories will be * processed recursively. * @param filter The filter to use while processing directories. Only * those files matching will be included in the jar archive. If * null, then all files are included. * @throws IOException */ public static void jar(OutputStream out, File[] src, FileFilter filter) throws IOException { jar(out, src, filter, null, null); } /** *

This function will create a Jar archive containing the src * file/directory. The archive will be written to the specified * OutputStream. Directories are processed recursively, applying the * specified filter if it exists. * * @param out The output stream to which the generated Jar archive is * written. * @param src The file or directory to jar up. Directories will be * processed recursively. * @param filter The filter to use while processing directories. Only * those files matching will be included in the jar archive. If * null, then all files are included. * @param prefix The name of an arbitrary directory that will precede all * entries in the jar archive. If null, then no prefix will be * used. * @param man The manifest to use for the Jar archive. If null, then no * manifest will be included. * @throws IOException */ public static void jar(OutputStream out, File[] src, FileFilter filter, String prefix, Manifest man) throws IOException { for (int i = 0; i < src.length; i++) { if (!src[i].exists()) { throw new FileNotFoundException(src.toString()); } } JarOutputStream jout; if (man == null) { jout = new JarOutputStream(out); } else { jout = new JarOutputStream(out, man); } if (prefix != null && prefix.length() > 0 && !prefix.equals("/")) { // strip leading '/' if (prefix.charAt(0) == '/') { prefix = prefix.substring(1); } // ensure trailing '/' if (prefix.charAt(prefix.length() - 1) != '/') { prefix = prefix + "/"; } } else { prefix = ""; } JarInfo info = new JarInfo(jout, filter); for (int i = 0; i < src.length; i++) { jar(src[i], prefix, info); } jout.close(); } /** * This simple convenience class is used by the jar method to reduce the * number of arguments needed. It holds all non-changing attributes * needed for the recursive jar method. */ private static class JarInfo { public JarOutputStream out; public FileFilter filter; public byte[] buffer; public JarInfo(JarOutputStream out, FileFilter filter) { this.out = out; this.filter = filter; buffer = new byte[1024]; } } /** * This recursive method writes all matching files and directories to * the jar output stream. */ private static void jar(File src, String prefix, JarInfo info) throws IOException { JarOutputStream jout = info.out; if (src.isDirectory()) { // create / init the zip entry prefix = prefix + src.getName() + "/"; ZipEntry entry = new ZipEntry(prefix); entry.setTime(src.lastModified()); entry.setMethod(JarOutputStream.STORED); entry.setSize(0L); entry.setCrc(0L); jout.putNextEntry(entry); jout.closeEntry(); // process the sub-directories File[] files = src.listFiles(info.filter); for (int i = 0; i < files.length; i++) { jar(files[i], prefix, info); } } else if (src.isFile()) { // get the required info objects byte[] buffer = info.buffer; // create / init the zip entry ZipEntry entry = new ZipEntry(prefix + src.getName()); entry.setTime(src.lastModified()); jout.putNextEntry(entry); // dump the file FileInputStream in = new FileInputStream(src); int len; while ((len = in.read(buffer, 0, buffer.length)) != -1) { jout.write(buffer, 0, len); } in.close(); jout.closeEntry(); } } public static void unjar(InputStream in, File dest) throws IOException { if (!dest.exists()) { dest.mkdirs(); } if (!dest.isDirectory()) { throw new IOException("Destination must be a directory."); } JarInputStream jin = new JarInputStream(in); byte[] buffer = new byte[1024]; ZipEntry entry = jin.getNextEntry(); while (entry != null) { String fileName = entry.getName(); if (fileName.charAt(fileName.length() - 1) == '/') { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.charAt(0) == '/') { fileName = fileName.substring(1); } if (File.separatorChar != '/') { fileName = fileName.replace('/', File.separatorChar); } File file = new File(dest, fileName); if (entry.isDirectory()) { // make sure the directory exists file.mkdirs(); jin.closeEntry(); } else { // make sure the directory exists File parent = file.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } // dump the file OutputStream out = new FileOutputStream(file); int len = 0; while ((len = jin.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } out.flush(); out.close(); jin.closeEntry(); file.setLastModified(entry.getTime()); } entry = jin.getNextEntry(); } /* Explicity write out the META-INF/MANIFEST.MF so that any headers such as the Class-Path are see for the unpackaged jar */ Manifest mf = jin.getManifest(); if (mf != null) { File file = new File(dest, "META-INF/MANIFEST.MF"); File parent = file.getParentFile(); if( parent.exists() == false ) { parent.mkdirs(); } OutputStream out = new FileOutputStream(file); mf.write(out); out.flush(); out.close(); } jin.close(); } /** Given a URL check if its a jar url(jar:!/archive) and if it is, extract the archive entry into the given dest directory and return a file URL to its location. If jarURL is not a jar url then it is simply returned as the URL for the jar. @param jarURL the URL to validate and extract the referenced entry if its a jar protocol URL @param dest the directory into which the nested jar will be extracted. @return the file: URL for the jar referenced by the jarURL parameter. * @throws IOException */ public static URL extractNestedJar(URL jarURL, File dest) throws IOException { // This may not be a jar URL so validate the protocol if( jarURL.getProtocol().equals("jar") == false ) return jarURL; String destPath = dest.getAbsolutePath(); URLConnection urlConn = jarURL.openConnection(); JarURLConnection jarConn = (JarURLConnection) urlConn; // Extract the archive to dest/jarName-contents/archive String parentArchiveName = jarConn.getJarFile().getName(); // Find the longest common prefix between destPath and parentArchiveName int length = Math.min(destPath.length(), parentArchiveName.length()); int n = 0; while( n < length ) { char a = destPath.charAt(n); char b = parentArchiveName.charAt(n); if( a != b ) break; n ++; } // Remove any common prefix from parentArchiveName parentArchiveName = parentArchiveName.substring(n); File archiveDir = new File(dest, parentArchiveName+"-contents"); if( archiveDir.exists() == false && archiveDir.mkdirs() == false ) throw new IOException("Failed to create contents directory for archive, path="+archiveDir.getAbsolutePath()); String archiveName = jarConn.getEntryName(); File archiveFile = new File(archiveDir, archiveName); File archiveParentDir = archiveFile.getParentFile(); if( archiveParentDir.exists() == false && archiveParentDir.mkdirs() == false ) throw new IOException("Failed to create parent directory for archive, path="+archiveParentDir.getAbsolutePath()); InputStream archiveIS = jarConn.getInputStream(); FileOutputStream fos = new FileOutputStream(archiveFile); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[4096]; int read; while( (read = archiveIS.read(buffer)) > 0 ) { bos.write(buffer, 0, read); } archiveIS.close(); bos.close(); // Return the file url to the extracted jar return archiveFile.toURL(); } public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("usage: "); System.exit(0); } if (args[0].equals("x")) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[1])); File dest = new File(args[2]); unjar(in, dest); } else if (args[0].equals("c")) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(args[1])); File[] src = new File[args.length - 2]; for (int i = 0; i < src.length; i++) { src[i] = new File(args[2 + i]); } jar(out, src); } else { System.out.println("Need x or c as first argument"); } } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FileProtocolArchiveBrowserFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FileProtocolArch0000644000175000017500000000332010774222622033213 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.net.URL; import java.util.Iterator; /** * comment * * @author Bill Burke * @author Dimitris Andreadis * @version $Revision: 2305 $ */ @SuppressWarnings("unchecked") public class FileProtocolArchiveBrowserFactory implements ArchiveBrowserFactory { public Iterator create(URL url, ArchiveBrowser.Filter filter) { File f = new File(url.getPath()); if (f.isDirectory()) { return new DirectoryArchiveBrowser(f, filter); } else { return new JarArchiveBrowser(f, filter); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/Files.java0000644000175000017500000003135210470642610032000 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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.UnsupportedEncodingException; import java.net.URL; import org.jboss.logging.Logger; import org.jboss.util.stream.Streams; /** * A collection of file utilities. * * @author Jason Dillon * @author Scott Stark * @author Dimitris Andreadis * @version $Revision: 1958 $ */ public final class Files { /** The Logger instance */ private static final Logger log = Logger.getLogger(Files.class); /** for byte-to-hex conversions */ private static final char[] hexDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** The default size of the copy buffer. */ public static final int DEFAULT_BUFFER_SIZE = 8192; /** Delete a file, or a directory and all of its contents. * * @param dir The directory or file to delete. * @return True if all delete operations were successfull. */ public static boolean delete(final File dir) { boolean success = true; File files[] = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File f = files[i]; if( f.isDirectory() == true ) { // delete the directory and all of its contents. if( delete(f) == false ) { success = false; log.debug("Failed to delete dir: "+f.getAbsolutePath()); } } // delete each file in the directory else if( f.delete() == false ) { success = false; log.debug("Failed to delete file: "+f.getAbsolutePath()); } } } // finally delete the directory if( dir.delete() == false ) { success = false; log.debug("Failed to delete dir: "+dir.getAbsolutePath()); } return success; } /** * Delete a file or directory and all of its contents. * * @param dirname The name of the file or directory to delete. * @return True if all delete operations were successfull. */ public static boolean delete(final String dirname) { return delete(new File(dirname)); } /** * Delete a directory contaning the given file and all its contents. * * @param filename a file or directory in the containing directory to delete * @return true if all delete operations were successfull, false if any * delete failed. */ public static boolean deleteContaining(final String filename) { File file = new File(filename); File containingDir = file.getParentFile(); return delete(containingDir); } /** * Copy a file. * * @param source Source file to copy. * @param target Destination target file. * @param buff The copy buffer. * * @throws IOException Failed to copy file. */ public static void copy(final File source, final File target, final byte buff[]) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); int read; try { while ((read = in.read(buff)) != -1) { out.write(buff, 0, read); } } finally { Streams.flush(out); Streams.close(in); Streams.close(out); } } /** * Copy a file. * * @param source Source file to copy. * @param target Destination target file. * @param size The size of the copy buffer. * * @throws IOException Failed to copy file. */ public static void copy(final File source, final File target, final int size) throws IOException { copy(source, target, new byte[size]); } /** * Copy a file. * * @param source Source file to copy. * @param target Destination target file. * * @throws IOException Failed to copy file. */ public static void copy(final File source, final File target) throws IOException { copy(source, target, DEFAULT_BUFFER_SIZE); } /** * Copy a remote/local URL to a local file * * @param src the remote or local URL * @param dest the local file * @throws IOException upon error */ public static void copy(URL src, File dest) throws IOException { log.debug("Copying " + src + " -> " + dest); // Validate that the dest parent directory structure exists File dir = dest.getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("mkdirs failed for: " + dir.getAbsolutePath()); } } // Remove any existing dest content if (dest.exists()) { if (!Files.delete(dest)) { throw new IOException("delete of previous content failed for: " + dest.getAbsolutePath()); } } // Treat local and remote URLs the same // prepare streams, do the copy and flush InputStream in = new BufferedInputStream(src.openStream()); OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); Streams.copy(in, out); out.flush(); out.close(); in.close(); } /** * Used to encode any string into a string that is safe to use as * a file name on most operating systems. * * Use decodeFileName() to get back the original string. * * Copied by Adrian's org.jboss.mq.pm.file.PersistenceManager * and adapted to use hex instead of decimal digits * * @param name the filename to encode * @return a filesystem-friendly filename */ public static String encodeFileName(String name) { return encodeFileName(name, '@'); } /** * Used to decode a file system friendly filename produced * by encodeFileName() method, above. * * Copied by Adrian's org.jboss.mq.pm.file.PersistenceManager * and adapted to use hex instead of decimal digits * * Note: * Decoding will not work if encoding produced * multi-byte encoded characters. If this is truly * needed we'll have to revise the encoding. * * @param name the filename to decode * @return the original name */ public static String decodeFileName(String name) { return decodeFileName(name, '@'); } /** * See encodeFileName(String) above. * * @param name the filename to encode * @param escape the escape character to use * @return a filesystem-friendly filename */ public static String encodeFileName(String name, char escape) { StringBuffer rc = new StringBuffer(); for (int i = 0; i < name.length(); i++ ) { switch (name.charAt(i)) { // These are the safe characters... case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'h': case 'H': case 'i': case 'I': case 'j': case 'J': case 'k': case 'K': case 'l': case 'L': case 'm': case 'M': case 'n': case 'N': case 'o': case 'O': case 'p': case 'P': case 'q': case 'Q': case 'r': case 'R': case 's': case 'S': case 't': case 'T': case 'u': case 'U': case 'v': case 'V': case 'w': case 'W': case 'x': case 'X': case 'y': case 'Y': case 'z': case 'Z': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '-': case '_': case '.': rc.append(name.charAt(i)); break; // Any other character needs to be encoded. default: // We encode the characters as hh, // where is the passed escape character and // hh is the hex value of the UTF8 byte of the character. // You might get hhhh since UTF8 can produce multiple // bytes for a single character. try { byte data[] = ("" + name.charAt(i)).getBytes("UTF8"); for (int j = 0; j < data.length; j++) { rc.append(escape); rc.append(hexDigits[ (data[j] >> 4) & 0xF ]); // high order digit rc.append(hexDigits[ (data[j] ) & 0xF ]); // low order digit } } catch (UnsupportedEncodingException wonthappen) { // nada } } } return rc.toString(); } /** * See decodeFileName(String) above. * * @param name the filename to decode * @param escape the escape character to use * @return the original name */ public static String decodeFileName(String name, char escape) { if (name == null) { return null; } StringBuffer sbuf = new StringBuffer(name.length()); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (c == escape) { char h1 = name.charAt(++i); char h2 = name.charAt(++i); // convert hex digits to integers int d1 = (h1 >= 'a') ? (10 + h1 - 'a') : ((h1 >= 'A') ? (10 + h1 - 'A') : (h1 - '0')); int d2 = (h2 >= 'a') ? (10 + h2 - 'a') : ((h2 >= 'A') ? (10 + h2 - 'A') : (h2 - '0')); // handling only the hh case here, as we don't know // if hhhh belong to the same character // (and we are lazy to change the encoding) - REVISIT byte[] bytes = new byte[] { (byte)(d1 * 16 + d2) }; try { String s = new String(bytes, "UTF8"); sbuf.append(s); } catch (UnsupportedEncodingException wonthappen) { // nada } } else { sbuf.append(c); } } return sbuf.toString(); } /** * Build a relative path to the given base path. * @param base - the path used as the base * @param path - the path to compute relative to the base path * @return A relative path from base to path * @throws IOException */ public static String findRelativePath(String base, String path) throws IOException { String a = new File(base).getCanonicalFile().toURI().getPath(); String b = new File(path).getCanonicalFile().toURI().getPath(); String[] basePaths = a.split("/"); String[] otherPaths = b.split("/"); int n = 0; for(; n < basePaths.length && n < otherPaths.length; n ++) { if( basePaths[n].equals(otherPaths[n]) == false ) break; } System.out.println("Common length: "+n); StringBuffer tmp = new StringBuffer("../"); for(int m = n; m < basePaths.length - 1; m ++) tmp.append("../"); for(int m = n; m < otherPaths.length; m ++) { tmp.append(otherPaths[m]); tmp.append("/"); } return tmp.toString(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilenamePrefixFilter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilenamePrefixFi0000644000175000017500000000512510470642610033172 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.FilenameFilter; /** * A prefix based filename filter. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FilenamePrefixFilter implements FilenameFilter { /** The prefix which files must have to be accepted. */ protected final String prefix; /** Flag to signal that we want to ignore the case. */ protected final boolean ignoreCase; /** * Construct a FilenamePrefixFilter. * * @param prefix The prefix which files must have to be accepted. * @param ignoreCase True if the filter should be case-insensitive. */ public FilenamePrefixFilter(final String prefix, final boolean ignoreCase) { this.ignoreCase = ignoreCase; this.prefix = (ignoreCase ? prefix.toLowerCase() : prefix); } /** * Construct a case sensitive FilenamePrefixFilter. * * @param prefix The prefix which files must have to be accepted. */ public FilenamePrefixFilter(final String prefix) { this(prefix, false); } /** * Check if a file is acceptible. * * @param dir The directory the file resides in. * @param name The name of the file. * @return true if the file is acceptable. */ public boolean accept(final File dir, final String name) { if (ignoreCase) { return name.toLowerCase().startsWith(prefix); } else { return name.startsWith(prefix); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarArchiveBrowser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarArchiveBrowse0000644000175000017500000000620410774222622033220 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.util.Enumeration; import java.util.Iterator; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; /** * Comment * * @author Bill Burke * @version $Revision: 2787 $ * **/ @SuppressWarnings("unchecked") public class JarArchiveBrowser implements Iterator { JarFile zip; Enumeration entries; JarEntry next; ArchiveBrowser.Filter filter; @SuppressWarnings("deprecation") public JarArchiveBrowser(JarURLConnection url, ArchiveBrowser.Filter filter) { this.filter = filter; try { zip = url.getJarFile(); entries = zip.entries(); } catch (IOException e) { throw new RuntimeException(e); //To change body of catch statement use Options | File Templates. } setNext(); } public JarArchiveBrowser(File f, ArchiveBrowser.Filter filter) { this.filter = filter; try { zip = new JarFile(f); entries = zip.entries(); } catch (IOException e) { throw new RuntimeException(e); //To change body of catch statement use Options | File Templates. } setNext(); } public boolean hasNext() { return next != null; } private void setNext() { next = null; while (entries.hasMoreElements() && next == null) { do { next = (JarEntry)entries.nextElement(); } while (entries.hasMoreElements() && next.isDirectory()); if (next.isDirectory()) next = null; if (next != null && !filter.accept(next.getName())) { next = null; } } } public Object next() { ZipEntry entry = next; setNext(); try { return zip.getInputStream(entry); } catch (IOException e) { throw new RuntimeException(e); } } public void remove() { throw new RuntimeException("Illegal operation on ArchiveBrowser"); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilePrefixFilter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilePrefixFilter0000644000175000017500000000500110470642610033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.FileFilter; /** * A prefix based file filter. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FilePrefixFilter implements FileFilter { /** The prefix which files must have to be accepted. */ protected final String prefix; /** Flag to signal that we want to ignore the case. */ protected final boolean ignoreCase; /** * Construct a FilePrefixFilter. * * @param prefix The prefix which files must have to be accepted. * @param ignoreCase True if the filter should be case-insensitive. */ public FilePrefixFilter(final String prefix, final boolean ignoreCase) { this.ignoreCase = ignoreCase; this.prefix = (ignoreCase ? prefix.toLowerCase() : prefix); } /** * Construct a case sensitive FilePrefixFilter. * * @param prefix The prefix which files must have to be accepted. */ public FilePrefixFilter(final String prefix) { this(prefix, false); } /** * Check if a file is acceptible. * * @param file The file to check. * @return true if the file is acceptable. */ public boolean accept(final File file) { if (ignoreCase) { return file.getName().toLowerCase().startsWith(prefix); } else { return file.getName().startsWith(prefix); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/DirectoryArchiveBrowser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/DirectoryArchive0000644000175000017500000000522010774222622033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Comment * * @author Bill Burke * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class DirectoryArchiveBrowser implements Iterator { private Iterator files; @SuppressWarnings("deprecation") public DirectoryArchiveBrowser(File file, ArchiveBrowser.Filter filter) { ArrayList list = new ArrayList(); try { create(list, file, filter); } catch (Exception e) { throw new RuntimeException(e); } files = list.iterator(); } @SuppressWarnings("deprecation") public static void create(List list, File dir, ArchiveBrowser.Filter filter) throws Exception { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { create(list, files[i], filter); } else { if (filter.accept(files[i].getAbsolutePath())) { list.add(files[i]); } } } } public boolean hasNext() { return files.hasNext(); } public Object next() { File fp = (File) files.next(); try { return new FileInputStream(fp); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public void remove() { throw new RuntimeException("Illegal operation call"); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/ArchiveBrowser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/ArchiveBrowser.j0000644000175000017500000000407010774222622033174 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Comment * * @deprecated * * @author Bill Burke * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public abstract class ArchiveBrowser { public interface Filter { boolean accept(String filename); } //use concurrent hashmap since a protocol can be added on the fly through the public attribute public static Map factoryFinder = new ConcurrentHashMap(); static { factoryFinder.put("file", new FileProtocolArchiveBrowserFactory()); factoryFinder.put("jar", new JarProtocolArchiveBrowserFactory()); } public static Iterator getBrowser(URL url, Filter filter) { ArchiveBrowserFactory factory = (ArchiveBrowserFactory)factoryFinder.get(url.getProtocol()); if (factory == null) throw new RuntimeException("Archive browser cannot handle protocol: " + url); return factory.create(url, filter); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilenameSuffixFilter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FilenameSuffixFi0000644000175000017500000000512110470642610033175 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.FilenameFilter; /** * A suffix based filename filter. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FilenameSuffixFilter implements FilenameFilter { /** The suffix which files must have to be accepted. */ protected final String suffix; /** Flag to signal that we want to ignore the case. */ protected final boolean ignoreCase; /** * Construct a FilenameSuffixFilter. * * @param suffix The suffix which files must have to be accepted. * @param ignoreCase True if the filter should be case-insensitive. */ public FilenameSuffixFilter(final String suffix, final boolean ignoreCase) { this.ignoreCase = ignoreCase; this.suffix = (ignoreCase ? suffix.toLowerCase() : suffix); } /** * Construct a case sensitive FilenameSuffixFilter. * * @param suffix The suffix which files must have to be accepted. */ public FilenameSuffixFilter(final String suffix) { this(suffix, false); } /** * Check if a file is acceptible. * * @param dir The directory the file resides in. * @param name The name of the file. * @return true if the file is acceptable. */ public boolean accept(final File dir, final String name) { if (ignoreCase) { return name.toLowerCase().endsWith(suffix); } else { return name.endsWith(suffix); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FileSuffixFilter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/FileSuffixFilter0000644000175000017500000000667710470642610033244 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.File; import java.io.FileFilter; /** * A suffix based file filter. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FileSuffixFilter implements FileFilter { /** A list of suffixes which files must have to be accepted. */ protected final String suffixes[]; /** Flag to signal that we want to ignore the case. */ protected final boolean ignoreCase; /** * Construct a FileSuffixFilter. * * @param suffixes A list of suffixes which files mut have to be accepted. * @param ignoreCase True if the filter should be case-insensitive. */ public FileSuffixFilter(final String suffixes[], final boolean ignoreCase) { this.ignoreCase = ignoreCase; if (ignoreCase) { this.suffixes = new String[suffixes.length]; for (int i=0; iFileSuffixFilter. * * @param suffixes A list of suffixes which files mut have to be accepted. */ public FileSuffixFilter(final String suffixes[]) { this(suffixes, false); } /** * Construct a FileSuffixFilter. * * @param suffix The suffix which files must have to be accepted. * @param ignoreCase True if the filter should be case-insensitive. */ public FileSuffixFilter(final String suffix, final boolean ignoreCase) { this(new String[] { suffix }, ignoreCase); } /** * Construct a case sensitive FileSuffixFilter. * * @param suffix The suffix which files must have to be accepted. */ public FileSuffixFilter(final String suffix) { this(suffix, false); } /** * Check if a file is acceptible. * * @param file The file to check. * @return true if the file is acceptable. */ public boolean accept(final File file) { boolean success = false; for (int i=0; iBill Burke * @version $Revision: 2787 $ */ @SuppressWarnings("deprecation") public class ClassFileFilter implements ArchiveBrowser.Filter { public boolean accept(String filename) { return filename.endsWith(".class"); } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarProtocolArchiveBrowserFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarProtocolArchi0000644000175000017500000000406010774222622033223 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.util.Iterator; /** * comment * * @author Bill Burke * @version $Revision: 1.1 $ */ @SuppressWarnings("unchecked") public class JarProtocolArchiveBrowserFactory implements ArchiveBrowserFactory { @SuppressWarnings("deprecation") public Iterator create(URL url, ArchiveBrowser.Filter filter) { if (url.toString().endsWith("!/")) { try { return new JarArchiveBrowser((JarURLConnection) url.openConnection(), filter); } catch (IOException e) { throw new RuntimeException("Unable to browse url: " + url, e); } } else { try { return new JarStreamBrowser(url.openStream(), filter); } catch (IOException e) { throw new RuntimeException("Unable to browse url: " + url, e); } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarStreamBrowser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/JarStreamBrowser0000644000175000017500000000664110774222622033261 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.util.Iterator; import java.util.jar.JarInputStream; import java.util.jar.JarEntry; import java.io.File; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStream; import java.io.ByteArrayInputStream; /** * Comment * * @author Bill Burke * @version $Revision: 1958 $ */ @SuppressWarnings("unchecked") public class JarStreamBrowser implements Iterator { // ZipFile zip; // Enumeration entries; JarInputStream jar; JarEntry next; @SuppressWarnings("deprecation") ArchiveBrowser.Filter filter; @SuppressWarnings("deprecation") public JarStreamBrowser(File file, ArchiveBrowser.Filter filter) throws IOException { this(new FileInputStream(file), filter); } @SuppressWarnings("deprecation") public JarStreamBrowser(InputStream is, ArchiveBrowser.Filter filter) throws IOException { this.filter = filter; jar = new JarInputStream(is); setNext(); } public boolean hasNext() { return next != null; } private void setNext() { try { if (next != null) jar.closeEntry(); next = null; do { next = jar.getNextJarEntry(); } while (next != null && (next.isDirectory() || !filter.accept(next.getName()))); if (next == null) jar.close(); } catch (IOException e) { throw new RuntimeException("failed to browse jar", e); } } public Object next() { int size = (int) next.getSize(); byte[] buf = new byte[size]; int count = 0; int current = 0; try { while (( ( current = jar.read(buf, count, size - count) ) != -1 ) && (count < size)) { count += current; } ByteArrayInputStream bais = new ByteArrayInputStream(buf); setNext(); return bais; } catch (IOException e) { try { jar.close(); } catch (IOException ignored) { } throw new RuntimeException(e); } } public void remove() { throw new RuntimeException("Illegal operation on ArchiveBrowser"); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/ArchiveBrowserFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/ArchiveBrowserFa0000644000175000017500000000250110774222622033210 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.file; import java.net.URL; import java.util.Iterator; /** * comment * * @author Bill Burke * @version $Revision: 1.1 $ */ @SuppressWarnings("unchecked") public interface ArchiveBrowserFactory { Iterator create(URL url, ArchiveBrowser.Filter filter); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/file/package.html0000644000175000017500000000151510470642610032352 0ustar twernertwerner

File related classes.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/SynchronizedCachePolicy.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/SynchronizedCachePoli0000644000175000017500000000467110470642610033332 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * A synchronized cache policy wrapper. * * @author Julien Viet * @version $Revision: 1958 $ * @see CachePolicy */ public final class SynchronizedCachePolicy implements CachePolicy { // Attributes ---------------------------------------------------- private final CachePolicy delegate; // Constructors -------------------------------------------------- public SynchronizedCachePolicy(CachePolicy delegate) { this.delegate = delegate; } // CachePolicy implementation ------------------------------------ synchronized public Object get(Object key) { return delegate.get(key); } synchronized public Object peek(Object key) { return delegate.get(key); } synchronized public void insert(Object key, Object object) { delegate.insert(key, object); } synchronized public void remove(Object key) { delegate.remove(key); } synchronized public void flush() { delegate.flush(); } synchronized public int size() { return delegate.size(); } synchronized public void create() throws Exception { delegate.create(); } synchronized public void start() throws Exception { delegate.start(); } synchronized public void stop() { delegate.stop(); } synchronized public void destroy() { delegate.destroy(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedError.java0000644000175000017500000001012010776226110032243 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; /** * A common superclass for Error classes that can * contain a nested Throwable detail object. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NestedError extends Error implements NestedThrowable { /** The serialVersionUID */ private static final long serialVersionUID = -4135571897343827853L; /** The nested throwable */ protected final Throwable nested; /** * Construct a NestedError with the specified * detail message. * * @param msg Detail message. */ public NestedError(final String msg) { super(msg); this.nested = null; } /** * Construct a NestedError with the specified * detail message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public NestedError(final String msg, final Throwable nested) { super(msg); this.nested = nested; NestedThrowable.Util.checkNested(this, nested); } /** * Construct a NestedError with the specified * nested Throwable. * * @param nested Nested Throwable. */ public NestedError(final Throwable nested) { this(nested.getMessage(), nested); } /** * Construct a NestedError with no detail. */ public NestedError() { super(); this.nested = null; } /** * Return the nested Throwable. * * @return Nested Throwable. */ public Throwable getNested() { return nested; } /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ public Throwable getCause() { return nested; } /** * Returns the composite throwable message. * * @return The composite throwable message. */ public String getMessage() { return NestedThrowable.Util.getMessage(super.getMessage(), nested); } /** * Prints the composite message and the embedded stack trace to the * specified print stream. * * @param stream Stream to print to. */ public void printStackTrace(final PrintStream stream) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(stream); } NestedThrowable.Util.print(nested, stream); } /** * Prints the composite message and the embedded stack trace to the * specified print writer. * * @param writer Writer to print to. */ public void printStackTrace(final PrintWriter writer) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(writer); } NestedThrowable.Util.print(nested, writer); } /** * Prints the composite message and the embedded stack trace to * System.err. */ public void printStackTrace() { printStackTrace(System.err); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/builder/0000755000175000017500000000000011105642363030577 5ustar twernertwerner././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/builder/AbstractBuilder.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/builder/AbstractBuild0000644000175000017500000000467610664777142033277 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.builder; import java.security.PrivilegedAction; /** * AbstractBuilder. * * @param the type to be built * @author Adrian Brock * @version $Revision: 1.1 $ */ public class AbstractBuilder implements PrivilegedAction { /** The factory class */ private Class factoryClass; /** The default factory */ private String defaultFactory; /** * Create a new AbstractBuilder. * * @param factoryClass the factory class * @param defaultFactory the default factory * @throws IllegalArgumentException for a null parameter */ public AbstractBuilder(Class factoryClass, String defaultFactory) { if (factoryClass == null) throw new IllegalArgumentException("Null factory class"); if (defaultFactory == null) throw new IllegalArgumentException("Null default factory"); this.factoryClass = factoryClass; this.defaultFactory = defaultFactory; } public T run() { try { String className = System.getProperty(factoryClass.getName(), defaultFactory); Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); Object object = clazz.newInstance(); return factoryClass.cast(object); } catch (Throwable t) { throw new RuntimeException("Error constructing " + factoryClass.getName(), t); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/0000755000175000017500000000000011105642363030717 5ustar twernertwerner././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/DeadlockDetector.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/DeadlockDete0000644000175000017500000000617310774222622033164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.deadlock; import java.util.HashMap; import java.util.HashSet; /** * Created by IntelliJ IDEA. * User: wburke * Date: Aug 21, 2003 * Time: 2:10:46 PM * To change this template use Options | File Templates. */ @SuppressWarnings("unchecked") public class DeadlockDetector { // TODO Maybe this should be an MBean in the future public static DeadlockDetector singleton = new DeadlockDetector(); // This following is for deadlock detection protected HashMap waiting = new HashMap(); public void deadlockDetection(Object holder, Resource resource) throws ApplicationDeadlockException { HashSet set = new HashSet(); set.add(holder); Object checkHolder = resource.getResourceHolder(); synchronized (waiting) { addWaiting(holder, resource); while (checkHolder != null) { Resource waitingFor = (Resource)waiting.get(checkHolder); Object holding = null; if (waitingFor != null) { holding = waitingFor.getResourceHolder(); } if (holding != null) { if (set.contains(holding)) { // removeWaiting should be cleaned up in acquire String msg = "Application deadlock detected, resource="+resource +", holder="+holder+", waitingResource="+waitingFor +", waitingResourceHolder="+holding; throw new ApplicationDeadlockException(msg, true); } set.add(holding); } checkHolder = holding; } } } /** * Add a transaction waiting for a lock * @param holder * @param resource */ public void addWaiting(Object holder, Resource resource) { synchronized (waiting) { waiting.put(holder, resource); } } /** * Remove a transaction waiting for a lock * @param holder */ public void removeWaiting(Object holder) { synchronized (waiting) { waiting.remove(holder); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/Resource.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/Resource.jav0000644000175000017500000000240110470642610033204 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.deadlock; /** * Created by IntelliJ IDEA. * User: wburke * Date: Aug 21, 2003 * Time: 2:11:52 PM * To change this template use Options | File Templates. */ public interface Resource { Object getResourceHolder(); } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/ApplicationDeadlockException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/deadlock/ApplicationD0000644000175000017500000000505310776226110033215 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.deadlock; /** * This exception class is thrown when application deadlock is detected when trying to lock an entity bean * This is probably NOT a result of a jboss bug, but rather that the application is access the same entity * beans within 2 different transaction in a different order. Remember, with a PessimisticEJBLock, * Entity beans are locked until the transaction commits or is rolled back. * * @author Bill Burke * * @version $Revision: 2800 $ * *

Revisions:
*

2002/02/13: billb *

    *
  1. Initial revision *
*/ public class ApplicationDeadlockException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = -908428091244600395L; protected boolean retry = false; public ApplicationDeadlockException() { super(); } public ApplicationDeadlockException(String msg, boolean retry) { super(msg); this.retry = retry; } public boolean retryable() { return retry; } /** * Detects exception contains is or a ApplicationDeadlockException. * @param t * @return true when it is a deadlock */ public static ApplicationDeadlockException isADE(Throwable t) { while (t!=null) { if (t instanceof ApplicationDeadlockException) { return (ApplicationDeadlockException)t; } else { t = t.getCause(); } } return null; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/0000755000175000017500000000000011105642363030566 5ustar twernertwerner././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ClassLoaderSource.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ClassLoaderSo0000644000175000017500000000271610772776222033230 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; /** * Interface for objects that provide a reference to a classloader. * * @see org.jboss.util.threadpool.BasicThreadPool#setClassLoaderSource(ClassLoaderSource) * * @author Brian Stansberry */ public interface ClassLoaderSource { /** * Gets the classloader provided by this object. * * @return the classloader, or null if none is available */ ClassLoader getClassLoader(); } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/DelegatingClassLoader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/DelegatingCla0000644000175000017500000000646310774222622033210 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandlerFactory; /** * A URL classloader that delegates to its parent, avoiding * synchronization. * * A standard flag is provided so it can be used as a parent class, * but later subclassed and to revert to standard class loading * if the subclass wants to load classes. * * @author Adrian Brock * @version $Revision: 2787 $ */ public class DelegatingClassLoader extends URLClassLoader { /** The value returned by {@link #getURLs()}. */ public static final URL[] EMPTY_URL_ARRAY = {}; /** Whether to use standard loading */ protected boolean standard = false; /** * Constructor * * @param parent the parent classloader, cannot be null. */ public DelegatingClassLoader(ClassLoader parent) { super(EMPTY_URL_ARRAY, parent); if (parent == null) throw new IllegalArgumentException("No parent"); } /** * Constructor * * @param parent the parent classloader, cannot be null. * @param factory the url stream factory. */ public DelegatingClassLoader(ClassLoader parent, URLStreamHandlerFactory factory) { super(EMPTY_URL_ARRAY, parent, factory); if (parent == null) throw new IllegalArgumentException("No parent"); } /** * Load a class, by asking the parent * * @param className the class name to load * @param resolve whether to link the class * @return the loaded class * @throws ClassNotFoundException when the class could not be found */ protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException { // Revert to standard rules if (standard) return super.loadClass(className, resolve); // Ask the parent Class clazz = null; try { clazz = getParent().loadClass(className); } catch (ClassNotFoundException e) { // Not found in parent, // maybe it is a proxy registered against this classloader? clazz = findLoadedClass(className); if (clazz == null) throw e; } // Link the class if (resolve) resolveClass(clazz); return clazz; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/MyClassLoaderClassLoaderSource.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/MyClassLoader0000644000175000017500000000254010772776222033227 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; /** * {@link ClassLoaderSource} implementation that returns the ClassLoader * that loaded this class. * * @author Brian Stansberry */ public class MyClassLoaderClassLoaderSource implements ClassLoaderSource { public ClassLoader getClassLoader() { return getClass().getClassLoader(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ContextClassLoader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ContextClassL0000644000175000017500000000553110774222622033246 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.security.AccessController; import java.security.PrivilegedAction; /** * A helper for context classloading.

* * When a security manager is installed, the * constructor checks for the runtime permissions * "getClassLoader" * * @version $Revision: 2787 $ * @author Adrian Brock */ @SuppressWarnings("unchecked") public class ContextClassLoader { /** * Retrieve a classloader permission */ public static final RuntimePermission GETCLASSLOADER = new RuntimePermission("getClassLoader"); /** * Instantiate a new context class loader */ public static final NewInstance INSTANTIATOR = new NewInstance(); /** * Constructor. * * @throws SecurityException when not authroized to get the context classloader */ /*package*/ ContextClassLoader() { SecurityManager manager = System.getSecurityManager(); if (manager != null) { manager.checkPermission(GETCLASSLOADER); } } /** * Retrieve the context classloader * * @return the context classloader */ public ClassLoader getContextClassLoader() { return getContextClassLoader(Thread.currentThread()); } /** * Retrieve the context classloader for the given thread * * @param thread the thread * @return the context classloader */ public ClassLoader getContextClassLoader(final Thread thread) { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return thread.getContextClassLoader(); } }); } private static class NewInstance implements PrivilegedAction { public Object run() { return new ContextClassLoader(); } } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ConstructorTCCLClassLoaderSource.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ConstructorTC0000644000175000017500000000375210774222622033277 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.lang.ref.WeakReference; import java.security.AccessController; /** * {@link ClassLoaderSource} implementation that returns the * {@link Thread#getContextClassLoader() thread context classloader (TCCL)} * in effect when this class' constructor is invoked. * * @author Brian Stansberry */ @SuppressWarnings("unchecked") public class ConstructorTCCLClassLoaderSource implements ClassLoaderSource { private final WeakReference classLoaderRef; public ConstructorTCCLClassLoaderSource() { ContextClassLoader ccl = (ContextClassLoader) AccessController.doPrivileged(ContextClassLoader.INSTANTIATOR); ClassLoader cl = ccl.getContextClassLoader(); if (cl != null) classLoaderRef = new WeakReference(cl); else classLoaderRef = null; } public ClassLoader getClassLoader() { return classLoaderRef == null ? null : (ClassLoader) classLoaderRef.get(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/Translator.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/Translator.ja0000644000175000017500000000653510774222622033247 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.security.ProtectionDomain; /** An interface for transforming byte code before Class creation. This is * compatible with the JDK1.5 java.lang.instrument.ClassFileTransformer * proposal. * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ public interface Translator { /** Optionally transform the supplied class file and return a new replacement * class file. * *

If a transformer has been registered with the class loading layer, * the transformer will be called for every new class definition. * The request for a new class definition is made with defineClass * The transformer is called during the processing of the request, before * the class file bytes have been verified or applied. * *

* If the implementing method determines that no transformations are needed, * it should return null. Otherwise, it should create a new * byte[] array and copy the input classfileBuffer into it, * along with all desired transformations. The input classfileBuffer * must not be modified. * * @param loader - the defining loader of the class to be transformed, may * be null if the bootstrap loader * @param className - the fully-qualified name of the class * @param classBeingRedefined - if this is a redefine, the class being * redefined, otherwise null * @param protectionDomain - the protection domain of the class being * defined or redefined * @param classfileBuffer - the input byte buffer in class file format - must * not be modified * * @throws Exception - if the input does not represent a well-formed class file * @return a well-formed class file buffer (the result of the transform), * or null if no transform is performed. */ public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws Exception; /** Called to indicate that the ClassLoader is being discarded by the server. * * @param loader - a class loader that has possibly been used previously * as an argument to transform. */ public void unregisterClassLoader(ClassLoader loader); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/Translatable.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/Translatable.0000644000175000017500000000265110470642610033206 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.net.URL; /** An interface representing class loader like senamics used in the aop * layer. Its only purpose was to remove the explicit dependency on the * JBoss UCL class loader api, but its existence seems to be a hack that * should be removed. * * @version $Revision: 1958 $ */ public interface Translatable { public URL getResourceLocally(String name); } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ContextClassLoaderSwitcher.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/loading/ContextClassL0000644000175000017500000001443710774222622033253 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.loading; import java.security.AccessController; import java.security.PrivilegedAction; /** * A helper for context classloading switching.

* * When a security manager is installed, the * constructor checks for the runtime permissions * "getClassLoader" and "setContextClassLoader". * This allows the methods of this class to be used later without * having to run in privileged blocks. * * There are optimized methods to perform the operations within * a switch context. This avoids retrieving the current thread * on every operation. * * @version $Revision: 2787 $ * @author Adrian Brock */ @SuppressWarnings("unchecked") public class ContextClassLoaderSwitcher extends ContextClassLoader { /** * Set the context classloader permission */ public static final RuntimePermission SETCONTEXTCLASSLOADER = new RuntimePermission("setContextClassLoader"); /** * Instantiate a new context class loader switcher */ @SuppressWarnings("hiding") public static final NewInstance INSTANTIATOR = new NewInstance(); /** * Constructor. * @throws SecurityException when not authroized to get/set the context classloader */ private ContextClassLoaderSwitcher() { super(); SecurityManager manager = System.getSecurityManager(); if (manager != null) manager.checkPermission(SETCONTEXTCLASSLOADER); } /** * Set the context classloader * @param cl */ public void setContextClassLoader(final ClassLoader cl) { setContextClassLoader(Thread.currentThread(), cl); } /** * Set the context classloader for the given thread * * @param thread the thread * @param cl the new context classloader */ public void setContextClassLoader(final Thread thread, final ClassLoader cl) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { thread.setContextClassLoader(cl); return null; } }); } /** * Retrieve a switch context * * @return the switch context */ public SwitchContext getSwitchContext() { return new SwitchContext(); } /** * Retrieve a switch context and set the new context classloader * * @param cl the new classloader * @return the switch context */ public SwitchContext getSwitchContext(final ClassLoader cl) { return new SwitchContext(cl); } /** * Retrieve a switch context for the classloader of a given class * * @deprecated using a class to determine the classloader is a * bad idea, it has the same problems as Class.forName() * @param clazz the class whose classloader should be set * as the context classloader * @return the switch context */ public SwitchContext getSwitchContext(final Class clazz) { return new SwitchContext(clazz.getClassLoader()); } /** * A helper class to remember the original classloader and * avoid continually retrieveing the current thread. */ public class SwitchContext { /** * The original classloader */ private ClassLoader origCL; /** * The current classloader */ private ClassLoader currentCL; /** * The current thread */ private Thread currentThread; private SwitchContext() { currentThread = Thread.currentThread(); origCL = getContextClassLoader(currentThread); currentCL = origCL; } private SwitchContext(ClassLoader cl) { this(); setClassLoader(cl); } /** * @return the current thread */ public Thread getThread() { return currentThread; } /** * @return the original classloader */ public ClassLoader getOriginalClassLoader() { return origCL; } /** * @return the current classloader * (as set through this class). */ public ClassLoader getCurrentClassLoader() { return currentCL; } /** * Change the context classloader

* * The operation is ignored if the classloader is null * or has not changed * * @param cl the new classloader */ public void setClassLoader(ClassLoader cl) { if (cl != null && cl != currentCL) { setContextClassLoader(currentThread, cl); currentCL = cl; } } /** * Reset back to the original classloader, * only when it has changed. */ public void reset() { if (currentCL != null && currentCL != origCL) setContextClassLoader(currentThread, origCL); } /** * Force a reset back to the original classloader, * useful when somebody else might have changed * the thread context classloader so we cannot optimize */ public void forceReset() { setContextClassLoader(currentThread, origCL); } } private static class NewInstance implements PrivilegedAction { public Object run() { return new ContextClassLoaderSwitcher(); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/WaitSync.java0000644000175000017500000000341210774222622031560 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Interface that gives wait - notify primitives to implementors. * * @see Semaphore * * @author Simone Bordet * @version $Revision: 2787 $ */ public interface WaitSync extends Sync { /** * Pone in wait status this sync, until {@link #doNotify} is called to wake it up. * * @see #doNotify * @throws InterruptedException */ void doWait() throws InterruptedException; /** * Wakes up this sync that has been posed in wait status by a {@link #doWait} call. * If this sync is not waiting, invoking this method should have no effect. * @see #doWait * @throws InterruptedException */ void doNotify() throws InterruptedException; } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedSQLException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedSQLException.ja0000644000175000017500000001117710776226110033156 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; import java.sql.SQLException; /** * A common superclass for SQLException classes that can contain * a nested Throwable detail object. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NestedSQLException extends SQLException implements NestedThrowable { /** The serialVersionUID */ private static final long serialVersionUID = -8348882503434035185L; /** The nested throwable */ protected final Throwable nested; /** * Construct a NestedSQLException with the specified detail * message. * * @param msg Detail message. */ public NestedSQLException(final String msg) { super(msg); this.nested = null; } /** * Construct a NestedSQLException with the specified detail * message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public NestedSQLException(final String msg, final Throwable nested) { super(msg); this.nested = nested; NestedThrowable.Util.checkNested(this, nested); } /** * Construct a NestedSQLException with the specified * nested Throwable. * * @param nested Nested Throwable. */ public NestedSQLException(final Throwable nested) { this(nested.getMessage(), nested); } /** * Construct a NestedSQLException. * * @param msg Detail message. * @param state SQL state message. */ public NestedSQLException(final String msg, final String state) { super(msg, state); this.nested = null; } /** * Construct a NestedSQLException. * * @param msg Detail message. * @param state SQL state message. * @param code SQL vendor code. */ public NestedSQLException(final String msg, final String state, final int code) { super(msg, state, code); this.nested = null; } /** * Return the nested Throwable. * * @return Nested Throwable. */ public Throwable getNested() { return nested; } /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ public Throwable getCause() { return nested; } /** * Returns the composite throwable message. * * @return The composite throwable message. */ public String getMessage() { return NestedThrowable.Util.getMessage(super.getMessage(), nested); } /** * Prints the composite message and the embedded stack trace to the * specified print stream. * * @param stream Stream to print to. */ public void printStackTrace(final PrintStream stream) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(stream); } NestedThrowable.Util.print(nested, stream); } /** * Prints the composite message and the embedded stack trace to the * specified print writer. * * @param writer Writer to print to. */ public void printStackTrace(final PrintWriter writer) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(writer); } NestedThrowable.Util.print(nested, writer); } /** * Prints the composite message and the embedded stack trace to * System.err. */ public void printStackTrace() { printStackTrace(System.err); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/JBossObject.java0000644000175000017500000001544410774222622032176 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.ref.SoftReference; import java.util.Collection; import java.util.Iterator; import org.jboss.logging.Logger; /** * Utility Class * * Utility Class that provides a Logger instance (log) and * caching of toString() and hashCode() values. * * You most probably want to override the method that * comes from JBossInterface: * * public void toShortString(StringBuffer buffer) * * to append to the buffer the key class properties, and * also override the following methods to provide the * hashCode and the class properties that should be cached: * * protected void toString(StringBuffer buffer) * protected int getHashCode() * * Cached values can be flushed using flushJBossObjectCache() * * Caching can be disabled by simply overriding toString() * and hashCode(), or returning false from methods: * * protected boolean cacheToString() * protected boolean cacheGetHashCode() * * @author Adrian Brock * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class JBossObject implements JBossInterface { /** The log */ protected Logger log; /** Cached toString */ protected transient SoftReference toString; /** Cached hashCode */ protected transient int hashCode = Integer.MIN_VALUE; /** * Safe equality check * * @param one an object * @param two another object * @return true when they are equal */ public static boolean equals(Object one, Object two) { if (one == null && two != null) return false; if (one != null && one.equals(two) == false) return false; return true; } /** * Safe inequality check * * @param one an object * @param two another object * @return true when they are not equal */ public static boolean notEqual(Object one, Object two) { return equals(one, two) == false; } /** * List the set of JBossObjects * * @param buffer the buffer * @param objects the collection of objects */ public static void list(JBossStringBuilder buffer, Collection objects) { if (objects == null) return; buffer.append('['); if (objects.isEmpty() == false) { for (Iterator i = objects.iterator(); i.hasNext();) { Object object = i.next(); if (object instanceof JBossObject) ((JBossObject) object).toShortString(buffer); else buffer.append(object.toString()); if (i.hasNext()) buffer.append(", "); } } buffer.append(']'); } /** * Create a new object */ public JBossObject() { log = Logger.getLogger(getClass()); } /** * Create a new object using the specified Logger instace * * @param log the Logger instance to use */ public JBossObject(Logger log) { this.log = (log != null) ? log : Logger.getLogger(getClass()); } /** * Override toString to cache the value * * @return the String */ public String toString() { if (cacheToString() == false) return toStringImplementation(); String result = null; if (toString != null) result = (String) toString.get(); if (result == null) { result = toStringImplementation(); toString = new SoftReference(result); } return result; } /** * Override hashCode to cache the value * * @return the hashCode */ public int hashCode() { if (hashCode == Integer.MIN_VALUE || cacheGetHashCode() == false) hashCode = getHashCode(); return hashCode; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public String toShortString() { JBossStringBuilder buffer = new JBossStringBuilder(); toShortString(buffer); return buffer.toString(); } /** * Append the key class properties to the buffer * * @param buffer the buffer */ public void toShortString(JBossStringBuilder buffer) { } /** * Get the class short name * * @return the short name of the class */ public String getClassShortName() { String longName = getClass().getName(); int dot = longName.lastIndexOf('.'); if (dot != -1) return longName.substring(dot + 1); return longName; } /** * Implementation of String * * @return the string */ protected String toStringImplementation() { JBossStringBuilder buffer = new JBossStringBuilder(); buffer.append(getClassShortName()).append('@'); buffer.append(Integer.toHexString(System.identityHashCode(this))); buffer.append('{'); toString(buffer); buffer.append('}'); return buffer.toString(); } /** * Flush the JBossObject cached values */ protected void flushJBossObjectCache() { toString = null; hashCode = Integer.MIN_VALUE; } /** * Append the class properties to the buffer * * @param buffer the buffer */ protected void toString(JBossStringBuilder buffer) { } /** * Calculate the hashcode * * @return the hash code */ protected int getHashCode() { return super.hashCode(); } /** * Whether we should cache the result toString() * * @return true by default */ protected boolean cacheToString() { return true; } /** * Whether we should cache the result hashCode() * * @return true by default */ protected boolean cacheGetHashCode() { return true; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Heap.java0000644000175000017500000001313010774222622030672 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.Comparator; /** * Data structure that mantains data in a ordered binary tree; each node is * greater (smaller) or equal than its 2 sub-nodes, for all the hierarchy.

* Elements of this data structure should either implement Comparable, or a * Comparator should be given as argument to the constructor. * * @author Simone Bordet * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class Heap { private Comparator m_comparator; private int m_count; private Object[] m_nodes; /** * Creates a new Heap whose elements inserted implement the * {@link Comparable} interface. */ public Heap() { this(null); } /** * Creates a new Heap whose elements are compared using the given * {@link Comparator}. * @param comparator */ public Heap(Comparator comparator) { m_comparator = comparator; clear(); } /** * Inserts the given element in this heap. * @param obj * * @see #extract */ public void insert(Object obj) { int length = m_nodes.length; // Expand if necessary if (m_count == length) { Object[] newNodes = new Object[length + length]; System.arraycopy(m_nodes, 0, newNodes, 0, length); m_nodes = newNodes; } // Be cur_slot the first unused slot index; be par_slot its parent index. // Start from cur_slot and walk up the tree comparing the object to // insert with the object at par_slot; if it's smaller move down the object at par_slot, // otherwise cur_slot is the index where insert the object. If not done, // shift up the tree so that now cur_slot is the old par_slot and // par_slot is the parent index of the new cur_slot (so the grand-parent // index of the old cur_slot) and compare again. int k = m_count; while (k > 0) { int par = parent(k); if (compare(obj, m_nodes[par]) < 0) { m_nodes[k] = m_nodes[par]; k = par; } else break; } m_nodes[k] = obj; ++m_count; } /** * Removes and returns the least element of this heap. * @return the extracted object * * @see #insert * @see #peek */ public Object extract() { if (m_count < 1) {return null;} else { int length = m_nodes.length >> 1; // Shrink if necessary if (length > 5 && m_count < (length >> 1)) { Object[] newNodes = new Object[length]; System.arraycopy(m_nodes, 0, newNodes, 0, length); m_nodes = newNodes; } // int k = 0; Object ret = m_nodes[k]; --m_count; Object last = m_nodes[m_count]; for (;;) { int l = left(k); if (l >= m_count) {break;} else { int r = right(k); int child = (r >= m_count || compare(m_nodes[l], m_nodes[r]) < 0) ? l : r; if (compare(last, m_nodes[child]) > 0) { m_nodes[k] = m_nodes[child]; k = child; } else {break;} } } m_nodes[k] = last; m_nodes[m_count] = null; return ret; } } /** * @return without removing it, the least element of this heap. * * @see #extract */ public Object peek() { if (m_count < 1) {return null;} else {return m_nodes[0];} } /** * Empties this heap */ public void clear() { m_count = 0; m_nodes = new Object[10]; } protected int compare(Object o1, Object o2) { if (m_comparator != null) { return m_comparator.compare(o1, o2); } else { if (o1 == null) { if (o2 == null) {return 0;} else {return -((Comparable)o2).compareTo(o1);} } else {return ((Comparable)o1).compareTo(o2);} } } /** * @return the parent index of index. * @param index */ protected int parent(int index) { return (index - 1) >> 1; } /** * @param index * @return the left child index of index. */ protected int left(int index) { return index + index + 1; } /** * @param index * @return the right child index of index. */ protected int right(int index) { return index + index + 2; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/package.html0000644000175000017500000000152610470642610031435 0ustar twernertwerner

Utility classes and interfaces.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedException.java0000644000175000017500000001020210776226110033111 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; /** * A common superclass for Exception classes that can contain * a nested Throwable detail object. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NestedException extends Exception implements NestedThrowable { /** The serialVersionUID */ private static final long serialVersionUID = 7003381223684751953L; /** The nested throwable */ protected final Throwable nested; /** * Construct a NestedException with the specified detail * message. * * @param msg Detail message. */ public NestedException(final String msg) { super(msg); this.nested = null; } /** * Construct a NestedException with the specified detail * message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public NestedException(final String msg, final Throwable nested) { super(msg); this.nested = nested; NestedThrowable.Util.checkNested(this, nested); } /** * Construct a NestedException with the specified * nested Throwable. * * @param nested Nested Throwable. */ public NestedException(final Throwable nested) { this(nested.getMessage(), nested); } /** * Construct a NestedException with no detail. */ public NestedException() { super(); this.nested = null; } /** * Return the nested Throwable. * * @return Nested Throwable. */ public Throwable getNested() { return nested; } /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ public Throwable getCause() { return nested; } /** * Returns the composite throwable message. * * @return The composite throwable message. */ public String getMessage() { return NestedThrowable.Util.getMessage(super.getMessage(), nested); } /** * Prints the composite message and the embedded stack trace to the * specified print stream. * * @param stream Stream to print to. */ public void printStackTrace(final PrintStream stream) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(stream); } NestedThrowable.Util.print(nested, stream); } /** * Prints the composite message and the embedded stack trace to the * specified print writer. * * @param writer Writer to print to. */ public void printStackTrace(final PrintWriter writer) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(writer); } NestedThrowable.Util.print(nested, writer); } /** * Prints the composite message and the embedded stack trace to * System.err. */ public void printStackTrace() { printStackTrace(System.err); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Strings.java0000644000175000017500000011122311041662731031445 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Map; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; import java.util.Locale; /** * A collection of String utilities. * * @author Jason Dillon * @author Scott Stark * @author Claudio Vesco * @author Dimitris Andreadis * @version $Revision: 2886 $ */ @SuppressWarnings("unchecked") public final class Strings { /** An empty string constant */ public static final String EMPTY = ""; /** Millisecond conversion constants */ private static final long MSEC = 1; private static final long SECS = 1000; private static final long MINS = 60 * 1000; private static final long HOUR = 60 * 60 * 1000; /** * List of valid Java keywords, see The Java Language Specification * Second Edition Section 3.9, 3.10.3 and 3.10.7 */ private static final String[] keywords = { "abstract", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while", "true", // technically no keywords but we are not picky "false", "null" }; /** * List of EJB-QL Identifiers as defined in the EJB 2.0 Specification * Section 11.2.6.1 */ private static final String[] ejbQlIdentifiers = { "AND", "AS", "BETWEEN", "DISTINCT", "EMPTY", "FALSE", "FROM", "IN", "IS", "LIKE", "MEMBER", "NOT", "NULL", "OBJECT", "OF", "OR", "SELECT", "UNKNOWN", "TRUE", "WHERE", }; ///////////////////////////////////////////////////////////////////////// // Substitution Methods // ///////////////////////////////////////////////////////////////////////// /** * Substitute sub-strings in side of a string. * * @param buff Stirng buffer to use for substitution (buffer is not reset) * @param from String to substitute from * @param to String to substitute to * @param string String to look for from in * @return Substituted string */ public static String subst(final StringBuffer buff, final String from, final String to, final String string) { int begin = 0, end = 0; while ((end = string.indexOf(from, end)) != -1) { // append the first part of the string buff.append(string.substring(begin, end)); // append the replaced string buff.append(to); // update positions begin = end + from.length(); end = begin; } // append the rest of the string buff.append(string.substring(begin, string.length())); return buff.toString(); } /** * Substitute sub-strings in side of a string. * * @param from String to substitute from * @param to String to substitute to * @param string String to look for from in * @return Substituted string */ public static String subst(final String from, final String to, final String string) { return subst(new StringBuffer(), from, to, string); } /** * Substitute sub-strings in side of a string. * * @param buff String buffer to use for substitution (buffer is not reset) * @param string String to subst mappings in * @param map Map of from->to strings * @param beginToken Beginning token * @param endToken Ending token * @return Substituted string */ public static String subst(final StringBuffer buff, final String string, final Map map, final String beginToken, final String endToken) { int begin = 0, rangeEnd = 0; Range range; while ((range = rangeOf(beginToken, endToken, string, rangeEnd)) != null) { // append the first part of the string buff.append(string.substring(begin, range.begin)); // Get the string to replace from the map String key = string.substring(range.begin + beginToken.length(), range.end); Object value = map.get(key); // if mapping does not exist then use empty; if (value == null) value = EMPTY; // append the replaced string buff.append(value); // update positions begin = range.end + endToken.length(); rangeEnd = begin; } // append the rest of the string buff.append(string.substring(begin, string.length())); return buff.toString(); } /** * Substitute sub-strings in side of a string. * * @param string String to subst mappings in * @param map Map of from->to strings * @param beginToken Beginning token * @param endToken Ending token * @return Substituted string */ public static String subst(final String string, final Map map, final String beginToken, final String endToken) { return subst(new StringBuffer(), string, map, beginToken, endToken); } /** * Substitute index identifiers with the replacement value from the * given array for the corresponding index. * * @param buff The string buffer used for the substitution * (buffer is not reset). * @param string String substitution format. * @param replace Array of strings whose values will be used as * replacements in the given string when a token with * their index is found. * @param token The character token to specify the start of an index * reference. * @return Substituted string. */ public static String subst(final StringBuffer buff, final String string, final String replace[], final char token) { int i = string.length(); for (int j = 0; j >= 0 && j < i; j++) { char c = string.charAt(j); // if the char is the token, then get the index if (c == token) { // if we aren't at the end of the string, get the index if (j != i) { int k = Character.digit(string.charAt(j + 1), 10); if (k == -1) { buff.append(string.charAt(j + 1)); } else if (k < replace.length) { buff.append(replace[k]); } j++; } } else { buff.append(c); } } return buff.toString(); } /** * Substitute index identifiers with the replacement value from the * given array for the corresponding index. * * @param string String substitution format. * @param replace Array of strings whose values will be used as * replacements in the given string when a token with * their index is found. * @param token The character token to specify the start of an index * reference. * @return Substituted string. */ public static String subst(final String string, final String replace[], final char token) { return subst(new StringBuffer(), string, replace, token); } /** * Substitute index identifiers (with % for the index token) * with the replacement value from the given array for the corresponding * index. * * @param string String substitution format. * @param replace Array of strings whose values will be used as * replacements in the given string when a token with * their index is found. * @return Substituted string. */ public static String subst(final String string, final String replace[]) { return subst(new StringBuffer(), string, replace, '%'); } ///////////////////////////////////////////////////////////////////////// // Range Methods // ///////////////////////////////////////////////////////////////////////// /** * Represents a range between two integers. */ public static class Range { /** The beginning of the range. */ public int begin; /** The end of the range. */ public int end; /** * Construct a new range. * * @param begin The beginning of the range. * @param end The end of the range. */ public Range(int begin, int end) { this.begin = begin; this.end = end; } /** * Default constructor. */ public Range() { } } /** * Return the range from a begining token to an ending token. * * @param beginToken String to indicate begining of range. * @param endToken String to indicate ending of range. * @param string String to look for range in. * @param fromIndex Beginning index. * @return (begin index, end index) or null. */ public static Range rangeOf(final String beginToken, final String endToken, final String string, final int fromIndex) { int begin = string.indexOf(beginToken, fromIndex); if (begin != -1) { int end = string.indexOf(endToken, begin + 1); if (end != -1) { return new Range(begin, end); } } return null; } /** * Return the range from a begining token to an ending token. * * @param beginToken String to indicate begining of range. * @param endToken String to indicate ending of range. * @param string String to look for range in. * @return (begin index, end index) or null. */ public static Range rangeOf(final String beginToken, final String endToken, final String string) { return rangeOf(beginToken, endToken, string, 0); } ///////////////////////////////////////////////////////////////////////// // Spliting Methods // ///////////////////////////////////////////////////////////////////////// /** * Split up a string into multiple strings based on a delimiter. * * @param string String to split up. * @param delim Delimiter. * @param limit Limit the number of strings to split into * (-1 for no limit). * @return Array of strings. */ public static String[] split(final String string, final String delim, final int limit) { // get the count of delim in string, if count is > limit // then use limit for count. The number of delimiters is less by one // than the number of elements, so add one to count. int count = count(string, delim) + 1; if (limit > 0 && count > limit) { count = limit; } String strings[] = new String[count]; int begin = 0; for (int i = 0; i < count; i++) { // get the next index of delim int end = string.indexOf(delim, begin); // if the end index is -1 or if this is the last element // then use the string's length for the end index if (end == -1 || i + 1 == count) end = string.length(); // if end is 0, then the first element is empty if (end == 0) strings[i] = EMPTY; else strings[i] = string.substring(begin, end); // update the begining index begin = end + 1; } return strings; } /** * Split up a string into multiple strings based on a delimiter. * * @param string String to split up. * @param delim Delimiter. * @return Array of strings. */ public static String[] split(final String string, final String delim) { return split(string, delim, -1); } ///////////////////////////////////////////////////////////////////////// // Joining/Concatenation Methods // ///////////////////////////////////////////////////////////////////////// /** * Join an array of strings into one delimited string. * * @param buff String buffered used for join (buffer is not reset). * @param array Array of objects to join as strings. * @param delim Delimiter to join strings with or null. * @return Joined string. */ public static String join(final StringBuffer buff, final Object array[], final String delim) { boolean haveDelim = (delim != null); for (int i = 0; i < array.length; i++) { buff.append(array[i]); // if this is the last element then don't append delim if (haveDelim && (i + 1) < array.length) { buff.append(delim); } } return buff.toString(); } /** * Join an array of strings into one delimited string. * * @param array Array of objects to join as strings. * @param delim Delimiter to join strings with or null. * @return Joined string. */ public static String join(final Object array[], final String delim) { return join(new StringBuffer(), array, delim); } /** * Convert and join an array of objects into one string. * * @param array Array of objects to join as strings. * @return Converted and joined objects. */ public static String join(final Object array[]) { return join(array, null); } /** * Convert and join an array of bytes into one string. * * @param array Array of objects to join as strings. * @return Converted and joined objects. */ public static String join(final byte array[]) { Byte bytes[] = new Byte[array.length]; for (int i = 0; i < bytes.length; i++) { bytes[i] = new Byte(array[i]); } return join(bytes, null); } /** * Return a string composed of the given array. * * @param buff Buffer used to construct string value (not reset). * @param array Array of objects. * @param prefix String prefix. * @param separator Element sepearator. * @param suffix String suffix. * @return String in the format of: * prefix + n ( + separator + n+i)* + suffix. */ public static String join(final StringBuffer buff, final Object[] array, final String prefix, final String separator, final String suffix) { buff.append(prefix); join(buff, array, separator); buff.append(suffix); return buff.toString(); } /** * Return a string composed of the given array. * * @param array Array of objects. * @param prefix String prefix. * @param separator Element sepearator. * @param suffix String suffix. * @return String in the format of: * prefix + n ( + separator + n+i)* + suffix. */ public static String join(final Object[] array, final String prefix, final String separator, final String suffix) { return join(new StringBuffer(), array, prefix, separator, suffix); } ///////////////////////////////////////////////////////////////////////// // Counting Methods // ///////////////////////////////////////////////////////////////////////// /** * Count the number of instances of substring within a string. * * @param string String to look for substring in. * @param substring Sub-string to look for. * @return Count of substrings in string. */ public static int count(final String string, final String substring) { int count = 0; int idx = 0; while ((idx = string.indexOf(substring, idx)) != -1) { idx++; count++; } return count; } /** * Count the number of instances of character within a string. * * @param string String to look for substring in. * @param c Character to look for. * @return Count of substrings in string. */ public static int count(final String string, final char c) { return count(string, String.valueOf(c)); } ///////////////////////////////////////////////////////////////////////// // Padding Methods // ///////////////////////////////////////////////////////////////////////// /** * Return a string padded with the given string for the given count. * * @param buff String buffer used for padding (buffer is not reset). * @param string Pad element. * @param count Pad count. * @return Padded string. */ public static String pad(final StringBuffer buff, final String string, final int count) { for (int i = 0; i < count; i++) { buff.append(string); } return buff.toString(); } /** * Return a string padded with the given string for the given count. * * @param string Pad element. * @param count Pad count. * @return Padded string. */ public static String pad(final String string, final int count) { return pad(new StringBuffer(), string, count); } /** * Return a string padded with the given string value of an object * for the given count. * * @param obj Object to convert to a string. * @param count Pad count. * @return Padded string. */ public static String pad(final Object obj, final int count) { return pad(new StringBuffer(), String.valueOf(obj), count); } ///////////////////////////////////////////////////////////////////////// // Misc Methods // ///////////////////////////////////////////////////////////////////////// /** *

Compare two strings. * *

Both or one of them may be null. * @param me * @param you * * @return true if object equals or intern ==, else false. */ public static boolean compare(final String me, final String you) { // If both null or intern equals if (me == you) return true; // if me null and you are not if (me == null && you != null) return false; // me will not be null, test for equality return me.equals(you); } /** * Check if the given string is empty. * * @param string String to check * @return True if string is empty */ public static boolean isEmpty(final String string) { return string.equals(EMPTY); } /** * Return the nth index of the given token occurring in the given string. * * @param string String to search. * @param token Token to match. * @param index Nth index. * @return Index of nth item or -1. */ public static int nthIndexOf(final String string, final String token, final int index) { int j = 0; for (int i = 0; i < index; i++) { j = string.indexOf(token, j + 1); if (j == -1) break; } return j; } /** * Capitalize the first character of the given string. * * @param string String to capitalize. * @return Capitalized string. * * @throws IllegalArgumentException String is null or empty. */ public static String capitalize(final String string) { if (string == null) throw new NullArgumentException("string"); if (string.equals("")) throw new EmptyStringException("string"); return Character.toUpperCase(string.charAt(0)) + string.substring(1); } /** * Trim each string in the given string array. * *

This modifies the string array. * * @param strings String array to trim. * @return String array with each element trimmed. */ public static String[] trim(final String[] strings) { for (int i = 0; i < strings.length; i++) { strings[i] = strings[i].trim(); } return strings; } /** * Make a URL from the given string. * *

* If the string is a properly formatted file URL, then the file * portion will be made canonical. * *

* If the string is an invalid URL then it will be converted into a * file URL. * * @param urlspec The string to construct a URL for. * @param relativePrefix The string to prepend to relative file * paths, or null to disable prepending. * @return A URL for the given string. * * @throws MalformedURLException Could not make a URL for the given string. */ public static URL toURL(String urlspec, final String relativePrefix) throws MalformedURLException { urlspec = urlspec.trim(); URL url; try { url = new URL(urlspec); if (url.getProtocol().equals("file")) { url = makeURLFromFilespec(url.getFile(), relativePrefix); } } catch (Exception e) { // make sure we have a absolute & canonical file url try { url = makeURLFromFilespec(urlspec, relativePrefix); } catch (IOException n) { // // jason: or should we rethrow e? // throw new MalformedURLException(n.toString()); } } return url; } public static URI toURI(String urispec, final String relativePrefix) throws URISyntaxException { urispec = urispec.trim(); URI uri; if( urispec.startsWith("file:") ) { uri = makeURIFromFilespec(urispec.substring(5), relativePrefix); } else { uri = new URI(urispec); } return uri; } /** A helper to make a URL from a filespec. */ private static URL makeURLFromFilespec(final String filespec, final String relativePrefix) throws IOException { // make sure the file is absolute & canonical file url File file = new File(decode(filespec)); // if we have a prefix and the file is not abs then prepend if (relativePrefix != null && !file.isAbsolute()) { file = new File(relativePrefix, filespec); } // make sure it is canonical (no ../ and such) file = file.getCanonicalFile(); return file.toURI().toURL(); } private static String decode(String filespec) { try { return URLDecoder.decode(filespec, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Error decoding filespec: " + filespec, e); } } private static URI makeURIFromFilespec(final String filespec, final String relativePrefix) { // make sure the file is absolute & canonical file url File file = new File(decode(filespec)); // if we have a prefix and the file is not abs then prepend if (relativePrefix != null && !file.isAbsolute()) { file = new File(relativePrefix, filespec); } return file.toURI(); } /** * Make a URL from the given string. * * @see #toURL(String,String) * * @param urlspec The string to construct a URL for. * @return A URL for the given string. * * @throws MalformedURLException Could not make a URL for the given string. */ public static URL toURL(final String urlspec) throws MalformedURLException { return toURL(urlspec, null); } /** * * @param urispec * @return the uri * @throws URISyntaxException for any error */ public static URI toURI(final String urispec) throws URISyntaxException { return toURI(urispec, null); } /** * Check whether the given String is a reserved Java Keyword * according to the Java Language Specifications. * * @param s String to check * * @return true if the given String is a reserved Java * keyword, false otherwise. */ public final static boolean isJavaKeyword(String s) { if (s == null || s.length() == 0) { return false; } for (int i = 0; i < keywords.length; i++) { if (keywords[i].equals(s)) { return true; } } return false; } /** * Check whether the given String is an identifier according to the * EJB-QL definition. See The EJB 2.0 Documentation Section 11.2.6.1. * * @param s String to check * * @return true if the given String is a reserved * identifier in EJB-QL, false otherwise. */ public final static boolean isEjbQlIdentifier(String s) { if (s == null || s.length() == 0) { return false; } for (int i = 0; i < ejbQlIdentifiers.length; i++) { if (ejbQlIdentifiers[i].equalsIgnoreCase(s)) { return true; } } return false; } /** * Check whether the given String is a valid identifier according * to the Java Language specifications. * * See The Java Language Specification Second Edition, Section 3.8 * for the definition of what is a valid identifier. * * @param s String to check * * @return true if the given String is a valid Java * identifier, false otherwise. */ public final static boolean isValidJavaIdentifier(String s) { // an empty or null string cannot be a valid identifier if (s == null || s.length() == 0) { return false; } char[] c = s.toCharArray(); if (!Character.isJavaIdentifierStart(c[0])) { return false; } for (int i = 1; i < c.length; i++) { if (!Character.isJavaIdentifierPart(c[i])) { return false; } } return true; } /** * Returns a new string with all the whitespace removed * * @param s the source string * @return the string without whitespace or null */ public static String removeWhiteSpace(String s) { String retn = null; if (s != null) { int len = s.length(); StringBuffer sbuf = new StringBuffer(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (!Character.isWhitespace(c)) sbuf.append(c); } retn = sbuf.toString(); } return retn; } /** * The default toString implementation of an object * * @param object the object * @return a string in the form className@hexHashCode */ public static final String defaultToString(Object object) { if (object == null) return "null"; else return object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object)); } /** * The default toString implementation of an object * * @param object the object * @param buffer the string builder */ public static final void defaultToString(JBossStringBuilder buffer, Object object) { if (object == null) buffer.append("null"); else { buffer.append(object.getClass().getName()); buffer.append('@'); buffer.append(Integer.toHexString(System.identityHashCode(object))); } } /** * The default toString implementation of an object * * @param object the object * @param buffer the string buffer */ public static final void defaultToString(StringBuffer buffer, Object object) { if (object == null) buffer.append("null"); else { buffer.append(object.getClass().getName()); buffer.append('@'); buffer.append(Integer.toHexString(System.identityHashCode(object))); } } /** * Parses a time period into a long. * * Translates possible [msec|sec|min|h] suffixes * * For example: * "1" -> 1 (msec) * "1msec -> 1 (msec) * "1sec" -> 1000 (msecs) * "1min" -> 60000 (msecs) * "1h" -> 3600000 (msecs) * * Accepts negative periods, e.g. "-1" * * @param period the stringfied time period * @return the parsed time period as long * @throws NumberFormatException */ public static long parseTimePeriod(String period) { try { String s = period.toLowerCase(); long factor; // look for suffix if (s.endsWith("msec")) { s = s.substring(0, s.lastIndexOf("msec")); factor = MSEC; } else if (s.endsWith("sec")) { s = s.substring(0, s.lastIndexOf("sec")); factor = SECS; } else if (s.endsWith("min")) { s = s.substring(0, s.lastIndexOf("min")); factor = MINS; } else if (s.endsWith("h")) { s = s.substring(0, s.lastIndexOf("h")); factor = HOUR; } else { factor = 1; } return Long.parseLong(s) * factor; } catch (RuntimeException e) { // thrown in addition when period is 'null' throw new NumberFormatException("For input time period: '" + period + "'"); } } /** * Same like parseTimePeriod(), but guards for negative entries. * * @param period the stringfied time period * @return the parsed time period as long * @throws NumberFormatException */ public static long parsePositiveTimePeriod(String period) { long retval = parseTimePeriod(period); if (retval < 0) { throw new NumberFormatException("Negative input time period: '" + period + "'"); } return retval; } /** * Tokenize the given String into a String array via a StringTokenizer. * * The given delimiters string is supposed to consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using delimitedListToStringArray * * @param str the String to tokenize * @param delimiters the delimiter characters, assembled as String * (each of those characters is individually considered as delimiter) * @param trimTokens trim the tokens via String's trim * @param ignoreEmptyTokens omit empty tokens from the result array * (only applies to tokens that are empty after trimming; StringTokenizer * will not consider subsequent delimiters as token in the first place). * @return an array of the tokens (null if the input String was null) */ public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List tokens = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return tokens.toArray(new String[tokens.size()]); } /** * Trim leading whitespace from the given String. * * @param str the string to check * @return the trimmed String * @see java.lang.Character#isWhitespace(char) */ public static String trimLeadingWhitespace(String str) { return trimLeadingCharacter(str, CharacterChecker.WHITESPACE); } /** * Trim all occurences of the supplied leading character from the given String. * * @param str the string to check * @param leadingCharacter the leading character to be trimmed * @return the trimmed String */ public static String trimLeadingCharacter(String str, final char leadingCharacter) { return trimLeadingCharacter(str, new CharacterChecker() { public boolean isCharacterLegal(char character) { return character == leadingCharacter; } }); } /** * Trim all occurences of the supplied leading character from the given String. * * @param str the string to check * @param checker the character checker * @return the trimmed String */ public static String trimLeadingCharacter(String str, CharacterChecker checker) { if (hasLength(str) == false) { return str; } if (checker == null) throw new IllegalArgumentException("Null character checker"); StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && checker.isCharacterLegal(buf.charAt(0))) { buf.deleteCharAt(0); } return buf.toString(); } /** * Check that the given string param is neither null nor of length 0. * * @param string the string * @return true if the String is not null and has length */ public static boolean hasLength(String string) { return (string != null && string.length() > 0); } /** * Parse the given localeString into a {@link java.util.Locale}. * * This is the inverse operation of {@link java.util.Locale#toString Locale's toString}. * * @param localeString the locale string * @return a corresponding Locale instance */ public static Locale parseLocaleString(String localeString) { String[] parts = tokenizeToStringArray(localeString, "_ ", false, false); String language = (parts.length > 0 ? parts[0] : ""); String country = (parts.length > 1 ? parts[1] : ""); String variant = ""; if (parts.length >= 2) { // There is definitely a variant, and it is everything after the country // code sans the separator between the country code and the variant. int endIndexOfCountryCode = localeString.indexOf(country) + country.length(); // Strip off any leading '_' and whitespace, what's left is the variant. variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode)); if (variant.startsWith("_")) { variant = trimLeadingCharacter(variant, '_'); } } return (language.length() > 0 ? new Locale(language, country, variant) : null); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/UnreachableStatementException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/UnreachableStatementE0000644000175000017500000000344510776226110033306 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Thrown to indicate that section of code that should never have been * reachable, has just been reached. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class UnreachableStatementException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = -6741968131968754812L; /** * Construct a UnreachableStatementException with a detail message. * * @param msg Detail message. */ public UnreachableStatementException(final String msg) { super(msg); } /** * Construct a UnreachableStatementException with no detail. */ public UnreachableStatementException() { super(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/ThrowableHandler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/ThrowableHandler.java0000644000175000017500000001070210774222622033244 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.List; import java.util.ArrayList; import java.util.Collections; /** * A static singleton that handles processing throwables that otherwise would * be ignored or dumped to System.err. * * @version $Revision: 2787 $ * @author Jason Dillon */ public final class ThrowableHandler { /** * Container for throwable types. */ public static interface Type { /** Unknown throwable. */ int UNKNOWN = 0; /** Error throwable. */ int ERROR = 1; /** Warning throwable. */ int WARNING = 2; } ///////////////////////////////////////////////////////////////////////// // Listener Methods // ///////////////////////////////////////////////////////////////////////// /** The list of listeners */ protected static List listeners = Collections.synchronizedList(new ArrayList()); /** * Add a ThrowableListener to the listener list. Listener is added only * if if it is not already in the list. * * @param listener ThrowableListener to add to the list. */ public static void addThrowableListener(ThrowableListener listener) { // only add the listener if it isn't already in the list if (!listeners.contains(listener)) { listeners.add(listener); } } /** * Remove a ThrowableListener from the listener list. * * @param listener ThrowableListener to remove from the list. */ public static void removeThrowableListener(ThrowableListener listener) { listeners.remove(listener); } /** * Fire onThrowable to all registered listeners. * * @param type The type off the throwable. * @param t Throwable */ protected static void fireOnThrowable(int type, Throwable t) { Object[] list = listeners.toArray(); for (int i=0; iObject utilities. * * @author Jason Dillon * @author Ales Justin */ @SuppressWarnings("unchecked") public final class Objects { ///////////////////////////////////////////////////////////////////////// // Coercion Methods // ///////////////////////////////////////////////////////////////////////// /** * Get a compatible constructor for the given value type * * @param type Class to look for constructor in * @param valueType Argument type for constructor * @return Constructor or null */ public static Constructor getCompatibleConstructor(final Class type, final Class valueType) { // first try and find a constructor with the exact argument type try { return type.getConstructor(new Class[] { valueType }); } catch (Exception ignore) { // if the above failed, then try and find a constructor with // an compatible argument type // get an array of compatible types Class[] types = type.getClasses(); for (int i=0; inon-null and is an * instance of Reference. If the object is null * then null is returned. If the object is not an instance of * Reference, then the object is returned. * * @param obj Object to dereference. * @return Dereferenced object. */ @SuppressWarnings("unchecked") public static Object deref(final Object obj) { if (obj != null && obj instanceof Reference) { Reference ref = (Reference)obj; return ref.get(); } return obj; } /** * Dereference an object * * @param the expected type * @param obj the object or reference * @param expected the expected type * @return the object or null */ public static T deref(final Object obj, Class expected) { Object result = deref(obj); if (result == null) return null; return expected.cast(result); } /** * Check if the given object is an array (primitve or native). * * @param obj Object to test. * @return True of the object is an array. */ public static boolean isArray(final Object obj) { if (obj != null) return obj.getClass().isArray(); return false; } /** * @return an Object array for the given object. * * @param obj Object to convert to an array. Converts primitive * arrays to Object arrays consisting of their wrapper * classes. If the object is not an array (object or primitve) * then a new array of the given type is created and the * object is set as the sole element. */ public static Object[] toArray(final Object obj) { // if the object is an array, the cast and return it. if (obj instanceof Object[]) { return (Object[])obj; } // if the object is an array of primitives then wrap the array Class type = obj.getClass(); Object array; if (type.isArray()) { int length = Array.getLength(obj); Class componentType = type.getComponentType(); array = Array.newInstance(componentType, length); for (int i=0; i * * It has a static method and an MBean wrapper for dynamic configuration.

* * The class is first checked for availablity before setting the system * property. * @jmx.mbean * * @version $Revision: 1958 $ * @author Adrian Brock */ public class SystemPropertyClassValue implements SystemPropertyClassValueMBean { public static final Logger log = Logger.getLogger(SystemPropertyClassValue.class); /** Property name. */ protected String property; /** Class Name. */ protected String className; /** * Constructor. */ public SystemPropertyClassValue() { } /** * The system property value * * @jmx.managed-attribute */ public String getProperty() { return property; } /** * The system property value * * @jmx.managed-attribute */ public void setProperty(String property) { this.property = property; } /** * The class name to use a value for the system property * when it is available * * @jmx.managed-attribute */ public String getClassName() { return className; } /** * The class name to use a value for the system property * when it is available * * @jmx.managed-attribute */ public void setClassName(String className) { this.className = className; } /** * JBoss lifecycle * * @jmx.managed-operation */ public void create() { Throwable error = setSystemPropertyClassValue(property, className); if (error != null) log.trace("Error loading class " + className + " property " + property + " not set.", error); } /** * Sets the system property to a class when the class is available. * * @param property the property to set * @param className the class to set as the properties value * @return any error loading the class * @exception IllegalArgumentException for a null or empty parameter */ public static Throwable setSystemPropertyClassValue(String property, String className) { // Validation if (property == null || property.trim().length() == 0) throw new IllegalArgumentException("Null or empty property"); if (className == null || className.trim().length() == 0) throw new IllegalArgumentException("Null or empty class name"); // Is the class available? try { Thread.currentThread().getContextClassLoader().loadClass(className); } catch (Throwable problem) { return problem; } // The class is there, set the property. System.setProperty(property, className); return null; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/package.html0000644000175000017500000000376010470642610033323 0ustar twernertwerner

An advanced property access, managment and notification system.

This system provides some helpful additions to the standard Java property system. Some of these features include:

  • Events
  • Convenience Grouping
  • Array Properties

Aims to provide a JavaBeans style api for accessing properties in a simple, powerful and consistent fashion.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • Re-design storeage of properties; making them more tree-like
  • Re-design property binding events; probably force use of a PropertyContainer sub-class or another JavaBeans like object
  • Move back to planet57.core?
  • Allow reading properties from a URL
  • Read properties correctly with win32 or unix style pathing
  • Create a property parser framework
  • Add an XML property parser
  • Add property map support and general configuration objects access. This will allow property.foo to be mapped to com.whatever.class.
  • Allow configuration objects to take more than one property group name, using the order for precidence.
././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyRead0000644000175000017500000000331310774222622033403 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.Map; import java.io.IOException; /** * Iterface used to allow a PropertyMap to read property definitions * in an implementation independent fashion. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public interface PropertyReader { /** * Read a map of properties from this input source. * * @return Read properties map. * * @throws PropertyException Failed to read properties. * @throws IOException I/O error while reading properties. */ Map readProperties() throws PropertyException, IOException; } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/Configurable.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/Configurable0000644000175000017500000000270310470642610033361 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; /** * An interface that allows for dynamic configuration of instance objects * with properties. * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface Configurable { /** * Configure this object with the given properties. * * @param props Properties to configure from. */ void configure(PropertyMap props); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyGroup.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyGrou0000644000175000017500000002032210774222622033443 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.Properties; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.Iterator; import org.jboss.util.NullArgumentException; /** * This is a helper class to access a group of properties with out having to * refer to their full names. * *

This class needs more work to be fully functional. It should suffice * for adding property listeners and getting/setting property values, * but other activies might not work out so well. * * @version $Revision: 2787 $ * @author Jason Dillon * @author Adrian Brock */ @SuppressWarnings("unchecked") public class PropertyGroup extends PropertyMap { /** Serial version uid */ private static final long serialVersionUID = -2557641199743063159L; /** Base property name */ protected final String basename; /** * Construct a PropertyGroup. * * @param basename Base property name. * @param container Property container. * * @throws NullArgumentException Basename is null. */ public PropertyGroup(final String basename, final Properties container) { super(container); if (basename == null) throw new NullArgumentException("basename"); this.basename = basename; } /** * Get the base property name for this group. * * @return Base property name. */ public final String getBaseName() { return basename; } /** * Make a fully qualified property name. * * @param suffix Property name suffix. */ private String makePropertyName(final String suffix) { return basename + PropertyMap.PROPERTY_NAME_SEPARATOR + suffix; } /** * Make a fully qualified property name. * * @param suffix Property name suffix. */ private String makePropertyName(final Object suffix) { return makePropertyName(String.valueOf(suffix)); } /** * Check if this PropertyMap contains a given property name. * * @param name Property name. * @return True if property map or defaults contains key. */ public boolean containsKey(final Object name) { if (name == null) throw new NullArgumentException("name"); return super.containsKey(makePropertyName(name)); } /** * Set a property. * * @param name Property name. * @param value Property value. * @return Previous property value or null. */ public Object put(final Object name, final Object value) { if (name == null) throw new NullArgumentException("name"); return super.put(makePropertyName(name), value); } /** * Get a property * * @param name Property name. * @return Property value or null. */ public Object get(final Object name) { if (name == null) throw new NullArgumentException("name"); return super.get(makePropertyName(name)); } /** * Remove a property. * * @param name Property name. * @return Removed property value. */ public Object remove(final Object name) { if (name == null) throw new NullArgumentException("name"); return super.remove(makePropertyName(name)); } /** * Returns an entry set for all properties in this group. * *

* This is currently ver inefficient, but should get the * job done for now. */ @SuppressWarnings("unchecked") public Set entrySet() { final Set superSet = super.entrySet(true); return new java.util.AbstractSet() { private boolean isInGroup(Map.Entry entry) { String key = (String) entry.getKey(); return key.startsWith(basename); } public int size() { Iterator iter = superSet.iterator(); int count = 0; while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (isInGroup(entry)) { count++; } } return count; } public Iterator iterator() { return new Iterator() { private Iterator iter = superSet.iterator(); private Object next; public boolean hasNext() { if (next != null) return true; while (next == null) { if (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (isInGroup(entry)) { next = entry; return true; } } else { break; } } return false; } public Object next() { if (next == null) throw new java.util.NoSuchElementException(); Object obj = next; next = null; return obj; } public void remove() { iter.remove(); } }; } }; } /** * Add a bound property listener. * *

Generates a fully qualified property name and adds the listener * under that name. * * @param listener Bound property listener to add. */ protected void addPropertyListener(final BoundPropertyListener listener) { // get the bound property name String name = makePropertyName(listener.getPropertyName()); // get the bound listener list for the property List list = (List) boundListeners.get(name); // if list is null, then add a new list if (list == null) { list = new ArrayList(); boundListeners.put(name, list); } // if listener is not in the list already, then add it if (!list.contains(listener)) { list.add(listener); // notify listener that is is bound listener.propertyBound(this); } } /** * Remove a bound property listener. * *

Generates a fully qualified property name and removes the listener * under that name. * * @param listener Bound property listener to remove. * @return True if listener was removed. */ protected boolean removePropertyListener(final BoundPropertyListener listener) { // get the bound property name String name = makePropertyName(listener.getPropertyName()); // get the bound listener list for the property List list = (List) boundListeners.get(name); boolean removed = false; if (list != null) { removed = list.remove(listener); // notify listener that is was unbound if (removed) listener.propertyUnbound(this); } return removed; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/FilePropertyReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/FileProperty0000644000175000017500000000751710774222622033421 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.Properties; import java.util.Map; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.IOException; import org.jboss.util.NullArgumentException; /** * Reads properties from one or more files. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class FilePropertyReader implements PropertyReader { /** Array of filenames to load properties from */ protected String[] filenames; /** * Construct a FilePropertyReader with an array of filenames * to read from. * * @param filenames Filenames to load properties from */ public FilePropertyReader(String[] filenames) { if (filenames == null) throw new NullArgumentException("filenames"); this.filenames = filenames; } /** * Construct a FilePropertyReader with a single filename to read from. * * @param filename Filename to load properties from */ public FilePropertyReader(String filename) { this(new String[] { filename }); } /** * Get an input stream for the given filename. * * @param filename File name to get input stream for. * @return Input stream for file. * * @throws IOException Failed to get input stream for file. */ protected InputStream getInputStream(String filename) throws IOException { File file = new File(filename); return new FileInputStream(file); } /** * Load properties from a file into a properties map. * * @param props Properties map to load properties into. * @param filename Filename to read properties from. * * @throws IOException Failed to load properties from filename. * @throws IllegalArgumentException Filename is invalid. */ protected void loadProperties(Properties props, String filename) throws IOException { if (filename == null) throw new NullArgumentException("filename"); if (filename.equals("")) throw new IllegalArgumentException("filename"); InputStream in = new BufferedInputStream(getInputStream(filename)); props.load(in); in.close(); } /** * Read properties from each specified filename * * @return Read properties * * @throws PropertyException Failed to read properties. * @throws IOException I/O error while reading properties. */ public Map readProperties() throws PropertyException, IOException { Properties props = new Properties(); // load each specified property file for (int i=0; i$Revision: 2800 $ * @author Jason Dillon */ public class PropertyException extends NestedRuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = 452085442436956822L; /** * Construct a PropertyException with the specified detail * message. * * @param msg Detail message. */ public PropertyException(String msg) { super(msg); } /** * Construct a PropertyException with the specified detail * message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public PropertyException(String msg, Throwable nested) { super(msg, nested); } /** * Construct a PropertyException with the specified * nested Throwable. * * @param nested Nested Throwable. */ public PropertyException(Throwable nested) { super(nested); } /** * Construct a PropertyException with no detail. */ public PropertyException() { super(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/Property.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/Property.jav0000644000175000017500000001260710774222622033374 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.security.AccessController; import java.security.PrivilegedAction; /** * Provides shorter method names for working with the {@link PropertyManager}. * * @version $Revision: 2787 $ * @author Jason Dillon * @author Adrian Brock */ @SuppressWarnings("unchecked") public final class Property { /** Platform dependent line separator. */ public static String LINE_SEPARATOR; /** Platform dependant file separator. */ public static String FILE_SEPARATOR; /** Platform dependant path separator. */ public static String PATH_SEPARATOR; static { PrivilegedAction action = new PrivilegedAction() { public Object run() { LINE_SEPARATOR = Property.get("line.separator"); FILE_SEPARATOR = Property.get("file.separator"); PATH_SEPARATOR = Property.get("path.separator"); return null; } }; AccessController.doPrivileged(action); } /** * Add a property listener * * @param listener Property listener to add */ public static void addListener(PropertyListener listener) { PropertyManager.addPropertyListener(listener); } /** * Add an array of property listeners * * @param listeners Array of property listeners to add */ public static void addListeners(PropertyListener[] listeners) { PropertyManager.addPropertyListeners(listeners); } /** * Remove a property listener * * @param listener Property listener to remove * @return True if listener was removed */ public static boolean removeListener(PropertyListener listener) { return PropertyManager.removePropertyListener(listener); } /** * Set a property * * @param name Property name * @param value Property value * @return Previous property value or null */ public static String set(String name, String value) { return PropertyManager.setProperty(name, value); } /** * Remove a property * * @param name Property name * @return Removed property value or null */ public static String remove(String name) { return PropertyManager.getProperty(name); } /** * Get a property * * @param name Property name * @param defaultValue Default property value * @return Property value or default */ public static String get(String name, String defaultValue) { return PropertyManager.getProperty(name, defaultValue); } /** * Get a property * * @param name Property name * @return Property value or null */ public static String get(String name) { return PropertyManager.getProperty(name); } /** * Get an array style property * * @param base Base property name * @param defaultValues Default property values * @return Array of property values or default */ public static String[] getArray(String base, String[] defaultValues) { return PropertyManager.getArrayProperty(base, defaultValues); } /** * Get an array style property * * @param name Property name * @return Array of property values or empty array */ public static String[] getArray(String name) { return PropertyManager.getArrayProperty(name); } /** * Check if a property of the given name exists. * * @param name Property name * @return True if property exists */ public static boolean exists(String name) { return PropertyManager.containsProperty(name); } /** * Get a property group for the given property base * * @param basename Base property name * @return Property group */ public static PropertyGroup getGroup(String basename) { return PropertyManager.getPropertyGroup(basename); } /** * Get a property group for the given property base at the given index * * @param basename Base property name * @param index Array property index * @return Property group */ public static PropertyGroup getGroup(String basename, int index) { return PropertyManager.getPropertyGroup(basename, index); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/DefaultPropertyReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/DefaultPrope0000644000175000017500000000554510774222622033366 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; /** * Reads properties from files specified via a system property. * *

Unless otherwise specified, propertie filenames will be read from * the org.jboss.properties singleton or array property. * * @version $Revision: 2787 $ * @author Jason Dillon */ public final class DefaultPropertyReader extends FilePropertyReader { // // Might want to have a org.jboss.properties.property.name or something // property to determine what property name to read from. // // For now just use 'properties' // /** Default property name to read filenames from */ public static final String DEFAULT_PROPERTY_NAME = "properties"; /** * Construct a DefaultPropertyReader with a specified property * name. * * @param propertyName Property name. */ public DefaultPropertyReader(final String propertyName) { super(getFilenames(propertyName)); } /** * Construct a DefaultPropertyReader. */ public DefaultPropertyReader() { this(DEFAULT_PROPERTY_NAME); } /** * Get an array of filenames to load. * * @param propertyName Property to read filenames from. * @return Array of filenames. * @throws PropertyException */ public static String[] getFilenames(final String propertyName) throws PropertyException { String filenames[]; // check for singleton property first Object filename = PropertyManager.getProperty(propertyName); if (filename != null) { filenames = new String[] { String.valueOf(filename) }; } else { // if no singleton property exists then look for array props filenames = PropertyManager.getArrayProperty(propertyName); } return filenames; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/BoundPropertyAdapter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/BoundPropert0000644000175000017500000000354410470642610033410 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; /** * An abstract adapter class for receiving bound property events. * *

Methods defined in this class are empty. This class exists as * as convenience for creating listener objects. * * @version $Revision: 1958 $ * @author Jason Dillon */ public abstract class BoundPropertyAdapter extends PropertyAdapter implements BoundPropertyListener { /** * Notifies that this listener was bound to a property. * * @param map PropertyMap which contains property bound to. */ public void propertyBound(final PropertyMap map) {} /** * Notifies that this listener was unbound from a property. * * @param map PropertyMap which contains property bound to. */ public void propertyUnbound(final PropertyMap map) {} } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyManager.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyMana0000644000175000017500000002501610774222622033410 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import java.util.Iterator; import java.io.IOException; import org.jboss.util.ThrowableHandler; /** * A more robust replacement of java.lang.System for property * access. * * @version $Revision: 2787 $ * @author Jason Dillon * @author Adrian Brock */ @SuppressWarnings("unchecked") public final class PropertyManager { /** Property reader list property name */ public static final String READER_PROPERTY_NAME = "org.jboss.util.property.reader"; /** Token which specifies the default property reader */ public static final String DEFAULT_PROPERTY_READER_TOKEN = "DEFAULT"; /** The default property reader name array */ private static final String[] DEFAULT_PROPERTY_READERS = { DEFAULT_PROPERTY_READER_TOKEN }; /** Default property container */ private static PropertyMap props; /** * Do not allow instantiation of this class. */ private PropertyManager() { } /** * Initialize the property system. */ static { // construct default property container and initialze from system props props = new PropertyMap(); PrivilegedAction action = new PrivilegedAction() { public Object run() { props.putAll(System.getProperties()); // replace system props to enable notifications via System.setProperty() System.setProperties(props); // load properties from initial property readers String[] readerNames = getArrayProperty(READER_PROPERTY_NAME, DEFAULT_PROPERTY_READERS); // construct each source and read its properties for (int i = 0; i < readerNames.length; i++) { try { if (readerNames[i].equals(DEFAULT_PROPERTY_READER_TOKEN)) { load(new DefaultPropertyReader()); } else { load(readerNames[i]); } } catch (IOException e) { ThrowableHandler.add(e); } } return null; } }; AccessController.doPrivileged(action); } /** * Get the default PropertyMap. * * @return Default PropertyMap. */ public static PropertyMap getDefaultPropertyMap() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); return props; } /** * Add a property listener. * * @param listener Property listener to add. */ public static void addPropertyListener(final PropertyListener listener) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.addPropertyListener(listener); } /** * Add an array of property listeners. * * @param listeners Array of property listeners to add. */ public static void addPropertyListeners(final PropertyListener[] listeners) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.addPropertyListeners(listeners); } /** * Remove a property listener. * * @param listener Property listener to remove. * @return True if listener was removed. */ public static boolean removePropertyListener(final PropertyListener listener) { return props.removePropertyListener(listener); } /** * Load properties from a map. * * @param prefix Prefix to append to all map keys (or null). * @param map Map containing properties to load. * @throws PropertyException */ public static void load(final String prefix, final Map map) throws PropertyException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.load(prefix, map); } /** * Load properties from a map. * * @param map Map containing properties to load. * @throws PropertyException * @throws IOException */ public static void load(final Map map) throws PropertyException, IOException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.load(map); } /** * Load properties from a PropertyReader. * * @param reader PropertyReader to read properties from. * @throws PropertyException * @throws IOException */ public static void load(final PropertyReader reader) throws PropertyException, IOException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.load(reader); } /** * Load properties from a PropertyReader specifed by the * given class name. * * @param classname Class name of a PropertyReader to * read from. * @throws PropertyException * @throws IOException */ public static void load(final String classname) throws PropertyException, IOException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); props.load(classname); } /** * Set a property. * * @param name Property name. * @param value Property value. * @return Previous property value or null. */ public static String setProperty(final String name, final String value) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return (String) props.setProperty(name, value); } /** * Remove a property. * * @param name Property name. * @return Removed property value or null. */ public static String removeProperty(final String name) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return props.removeProperty(name); } /** * Get a property. * * @param name Property name. * @param defaultValue Default property value. * @return Property value or default. */ public static String getProperty(final String name, final String defaultValue) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return props.getProperty(name, defaultValue); } /** * Get a property. * * @param name Property name. * @return Property value or null. */ public static String getProperty(final String name) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return props.getProperty(name); } /** * Get an array style property. * * @param base Base property name. * @param defaultValues Default property values. * @return Array of property values or default. */ public static String[] getArrayProperty(final String base, final String[] defaultValues) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); return props.getArrayProperty(base, defaultValues); } /** * Get an array style property. * * @param name Property name. * @return Array of property values or empty array. */ public static String[] getArrayProperty(final String name) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return props.getArrayProperty(name); } /** * Return an iterator over all contained property names. * * @return Property name iterator. */ public static Iterator names() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); return props.names(); } /** * Check if this map contains a given property. * * @param name Property name. * @return True if contains property. */ public static boolean containsProperty(final String name) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertyAccess(name); return props.containsProperty(name); } /** * Get a property group for the given property base. * * @param basename Base property name. * @return Property group. */ public static PropertyGroup getPropertyGroup(final String basename) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); return props.getPropertyGroup(basename); } /** * Get a property group for the given property base at the given index. * * @param basename Base property name. * @param index Array property index. * @return Property group. */ public static PropertyGroup getPropertyGroup(final String basename, final int index) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPropertiesAccess(); return props.getPropertyGroup(basename, index); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/BoundPropertyListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/BoundPropert0000644000175000017500000000464710470642610033415 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; /** * The listener interface for receiving bound property events (as well as * property events). * *

Classes that are interested in processing a bound property event * implement this interface, and register instance objects with a given * {@link PropertyMap} or via * {@link PropertyManager#addPropertyListener(PropertyListener)}. * *

Note that this is not the typical listener interface, as it extends * from {@link PropertyListener}, and defines {@link #getPropertyName()} * which is not an event triggered method. This method serves to instruct * the {@link PropertyMap} the listener is registered with, which property * it will bind to. * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface BoundPropertyListener extends PropertyListener { /** * Get the property name which this listener is bound to. * * @return Property name. */ String getPropertyName(); /** * Notifies that this listener was bound to a property. * * @param map PropertyMap which contains property bound to. */ void propertyBound(PropertyMap map); /** * Notifies that this listener was unbound from a property. * * @param map PropertyMap which contains property bound to. */ void propertyUnbound(PropertyMap map); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyMap.0000644000175000017500000005220710774222622033331 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.List; import java.util.LinkedList; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Collections; import java.util.Properties; import javax.naming.Context; import javax.naming.ldap.LdapContext; import org.jboss.util.NullArgumentException; /** * A replacement for the standard java.util.Properties * class which adds, among others, property event capabilities. * * @todo consider moving the JNDI property handling to a InitialContextFactoryBuilder * * @version $Revision: 2787 $ * @author Jason Dillon * @author Scott.Stark@jboss.org * @author Adrian Brock */ @SuppressWarnings("unchecked") public class PropertyMap extends Properties { /** Serial version uid */ private static final long serialVersionUID = 8747802918099008518L; /** Property name separator */ public static final String PROPERTY_NAME_SEPARATOR = "."; /** Empty array property */ public static final String[] EMPTY_ARRAY_PROPERTY = new String[0]; /** Property listener list */ protected transient List unboundListeners; /** Bound property name -> listener list map */ protected transient Map boundListeners; /** * This map avoids heavy contention for the properties that JNDI looks * up everytime a new InitialContext instance is created. Once the container is * up and running getProperty calls other than for the JNDI property are very rare, * so the double lookup is not much of a performance problem. * If at all possible, this class should be read-only and use no locks at all. */ private transient Map jndiMap; private final static Object NULL_VALUE = new Object(); /** * Construct a PropertyMap with default properties. * * @param defaults Default properties. */ public PropertyMap(Properties defaults) { super(defaults); init(); } /** * Construct a PropertyMap. */ public PropertyMap() { this(null); } /** Initialized listener lists and the JNDI properties cache map */ private void init() { unboundListeners = Collections.synchronizedList(new ArrayList()); boundListeners = Collections.synchronizedMap(new HashMap()); jndiMap = new HashMap(); PrivilegedAction action = new PrivilegedAction() { public Object run() { Object value = System.getProperty(Context.PROVIDER_URL); if (value == null) value = NULL_VALUE; jndiMap.put(Context.PROVIDER_URL, value); value = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (value == null) value = NULL_VALUE; jndiMap.put(Context.INITIAL_CONTEXT_FACTORY, value); value = System.getProperty(Context.OBJECT_FACTORIES); if (value == null) value = NULL_VALUE; jndiMap.put(Context.OBJECT_FACTORIES, value); value = System.getProperty(Context.URL_PKG_PREFIXES); if (value == null) value = NULL_VALUE; jndiMap.put(Context.URL_PKG_PREFIXES, value); value = System.getProperty(Context.STATE_FACTORIES); if (value == null) value = NULL_VALUE; jndiMap.put(Context.STATE_FACTORIES, value); value = System.getProperty(Context.DNS_URL); if (value == null) value = NULL_VALUE; jndiMap.put(Context.DNS_URL, value); value = System.getProperty(LdapContext.CONTROL_FACTORIES); if (value == null) value = NULL_VALUE; jndiMap.put(LdapContext.CONTROL_FACTORIES, value); return null; } }; AccessController.doPrivileged(action); } /** Called by setProperty to update the jndiMap cache values. * @param name the property name * @param value the property value */ private void updateJndiCache(String name, String value) { if( name == null ) return; boolean isJndiProperty = name.equals(Context.PROVIDER_URL) || name.equals(Context.INITIAL_CONTEXT_FACTORY) || name.equals(Context.OBJECT_FACTORIES) || name.equals(Context.URL_PKG_PREFIXES) || name.equals(Context.STATE_FACTORIES) || name.equals(Context.DNS_URL) || name.equals(LdapContext.CONTROL_FACTORIES) ; if( isJndiProperty == true ) jndiMap.put(name, value); } /** * Set a property. * * @param name Property name. * @param value Property value. * @return Previous property value or null. */ public Object put(Object name, Object value) { if (name == null) throw new NullArgumentException("name"); // value can be null // check if this is a new addition or not prior to updating the hash boolean add = !containsKey(name); Object prev = super.put(name, value); PropertyEvent event = new PropertyEvent(this, name.toString(), value.toString()); // fire propertyAdded or propertyChanged if (add) { firePropertyAdded(event); } else { firePropertyChanged(event); } return prev; } /** * Remove a property. * * @param name Property name. * @return Removed property value. */ public Object remove(Object name) { if (name == null) throw new NullArgumentException("name"); // check if there is a property with this name boolean contains = containsKey(name); Object value = null; if (contains) { value = super.remove(name); if (defaults != null) { Object obj = defaults.remove(name); if (value == null) { value = obj; } } // Remove any JNDI property value jndiMap.remove(name); PropertyEvent event = new PropertyEvent(this, name.toString(), value.toString()); firePropertyRemoved(event); } return value; } /** * Returns a set of keys for all entries in this group and optionally * all of the keys in the defaults map. * @param includeDefaults * @return the key set */ public Set keySet(final boolean includeDefaults) { if (includeDefaults) { Set set = new HashSet(); set.addAll(defaults.keySet()); set.addAll(super.keySet()); return Collections.synchronizedSet(set); } return super.keySet(); } /** * Returns a set of entrys for all entries in this group and optionally * all of the entrys in the defaults map. * @param includeDefaults * @return the entry set */ public Set entrySet(final boolean includeDefaults) { if (includeDefaults) { Set set = new HashSet(); set.addAll(defaults.entrySet()); set.addAll(super.entrySet()); return Collections.synchronizedSet(set); } return super.entrySet(); } /** * Add a property listener. * * @param listener Property listener to add. */ public void addPropertyListener(PropertyListener listener) { if (listener == null) throw new NullArgumentException("listener"); if (listener instanceof BoundPropertyListener) { addPropertyListener((BoundPropertyListener) listener); } else { // only add the listener if it is not in the list already if (!unboundListeners.contains(listener)) unboundListeners.add(listener); } } /** * Add a bound property listener. * * @param listener Bound property listener to add. */ protected void addPropertyListener(BoundPropertyListener listener) { // get the bound property name String name = listener.getPropertyName(); // get the bound listener list for the property List list = (List) boundListeners.get(name); // if list is null, then add a new list if (list == null) { list = Collections.synchronizedList(new ArrayList()); boundListeners.put(name, list); } // if listener is not in the list already, then add it if (!list.contains(listener)) { list.add(listener); // notify listener that is is bound listener.propertyBound(this); } } /** * Add an array of property listeners. * * @param listeners Array of property listeners to add. */ public void addPropertyListeners(PropertyListener[] listeners) { if (listeners == null) throw new NullArgumentException("listeners"); for (int i = 0; i < listeners.length; i++) { addPropertyListener(listeners[i]); } } /** * Remove a property listener. * * @param listener Property listener to remove. * @return True if listener was removed. */ public boolean removePropertyListener(PropertyListener listener) { if (listener == null) throw new NullArgumentException("listener"); boolean removed = false; if (listener instanceof BoundPropertyListener) { removed = removePropertyListener((BoundPropertyListener) listener); } else { removed = unboundListeners.remove(listener); } return removed; } /** * Remove a bound property listener. * * @param listener Bound property listener to remove. * @return True if listener was removed. */ protected boolean removePropertyListener(BoundPropertyListener listener) { // get the bound property name String name = listener.getPropertyName(); // get the bound listener list for the property List list = (List) boundListeners.get(name); boolean removed = false; if (list != null) { removed = list.remove(listener); // notify listener that is was unbound if (removed) listener.propertyUnbound(this); } return removed; } /** * Fire a property added event to the given list of listeners. * * @param list Listener list. * @param event Property event. */ private void firePropertyAdded(List list, PropertyEvent event) { if (list == null) return; int size = list.size(); for (int i = 0; i < size; i++) { PropertyListener listener = (PropertyListener) list.get(i); listener.propertyAdded(event); } } /** * Fire a property added event to all registered listeners. * * @param event Property event. */ protected void firePropertyAdded(PropertyEvent event) { // fire all bound listeners (if any) first if (boundListeners != null) { List list = (List) boundListeners.get(event.getPropertyName()); if (list != null) { firePropertyAdded(list, event); } } // next fire all unbound listeners firePropertyAdded(unboundListeners, event); } /** * Fire a property removed event to the given list of listeners. * * @param list Listener list. * @param event Property event. */ private void firePropertyRemoved(List list, PropertyEvent event) { if (list == null) return; int size = list.size(); for (int i = 0; i < size; i++) { PropertyListener listener = (PropertyListener) list.get(i); listener.propertyRemoved(event); } } /** * Fire a property removed event to all registered listeners. * * @param event Property event. */ protected void firePropertyRemoved(PropertyEvent event) { // fire all bound listeners (if any) first if (boundListeners != null) { List list = (List) boundListeners.get(event.getPropertyName()); if (list != null) { firePropertyRemoved(list, event); } } // next fire all unbound listeners firePropertyRemoved(unboundListeners, event); } /** * Fire a property changed event to the given list of listeners. * * @param list Listener list. * @param event Property event. */ private void firePropertyChanged(List list, PropertyEvent event) { if (list == null) return; int size = list.size(); for (int i = 0; i < size; i++) { PropertyListener listener = (PropertyListener) list.get(i); listener.propertyChanged(event); } } /** * Fire a property changed event to all listeners. * * @param event Property event. */ protected void firePropertyChanged(PropertyEvent event) { // fire all bound listeners (if any) first if (boundListeners != null) { List list = (List) boundListeners.get(event.getPropertyName()); if (list != null) { firePropertyChanged(list, event); } } // next fire all unbound listeners firePropertyChanged(unboundListeners, event); } /** * Make a optionaly prefixed property name. * * @param base Base property name. * @param prefix Optional prefix (can be null). * @return Property name. */ protected String makePrefixedPropertyName(String base, String prefix) { String name = base; if (prefix != null) { StringBuffer buff = new StringBuffer(base); if (prefix != null) { buff.insert(0, PROPERTY_NAME_SEPARATOR); buff.insert(0, prefix); } return buff.toString(); } return name; } /** * Load properties from a map. * * @param prefix Prefix to append to all map keys (or null). * @param map Map containing properties to load. * @throws PropertyException */ public void load(String prefix, Map map) throws PropertyException { // prefix can be null if (map == null) throw new NullArgumentException("map"); // set properties for each key in map Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { // make a string key with optional prefix String key = String.valueOf(iter.next()); String name = makePrefixedPropertyName(key, prefix); String value = String.valueOf(map.get(name)); // set the property setProperty(name, value); } } /** * Load properties from a map. * * @param map Map containing properties to load. * @throws PropertyException */ public void load(Map map) throws PropertyException { load(null, map); } /** * Load properties from a PropertyReader. * * @param reader PropertyReader to read properties from. * @throws PropertyException * @throws IOException */ public void load(PropertyReader reader) throws PropertyException, IOException { if (reader == null) throw new NullArgumentException("reader"); load(reader.readProperties()); } /** * Load properties from a PropertyReader specifed by the given class name. * * @param className Class name of a PropertyReader to read from. * @throws PropertyException * @throws IOException */ public void load(String className) throws PropertyException, IOException { if (className == null) throw new NullArgumentException("className"); PropertyReader reader = null; try { Class type = Class.forName(className); reader = (PropertyReader) type.newInstance(); } catch (Exception e) { throw new PropertyException(e); } // load the properties from the source load(reader); } /** * Set a property. * *

Returns Object instead of String due to limitations with * java.util.Properties. * * @param name Property name. * @param value Property value. * @return Previous property value or null. */ public Object setProperty(String name, String value) { updateJndiCache(name, value); return put(name, value); } public String getProperty(String name) { Object value = jndiMap.get(name); if (value != null) { // key was in the map return (value == NULL_VALUE) ? null : (String) value; } return super.getProperty(name); } /** * Remove a property. * * @param name Property name. * @return Removed property value or null. */ public String removeProperty(String name) { return (String) remove(name); } /** * Make an indexed property name. * * @param base Base property name. * @param index Property index. * @return Indexed property name. */ protected String makeIndexPropertyName(String base, int index) { return base + PROPERTY_NAME_SEPARATOR + index; } /** * Get an array style property. * *

Array properties are specified as: * base_property_name.INDEX. * *

Indexes begin with zero and must be contiguous. A break in * continuity signals the end of the array. * * @param base Base property name. * @param defaultValues Default property values. * @return Array of property values or default. */ public String[] getArrayProperty(String base, String[] defaultValues) { if (base == null) throw new NullArgumentException("base"); // create a new list to store indexed values into List list = new LinkedList(); int i = 0; while (true) { // make the index property name String name = makeIndexPropertyName(base, i); // see if there is a value for this property String value = getProperty(name); if (value != null) { list.add(value); } else if (i >= 0) { break; // no more index properties } i++; } String values[] = defaultValues; // if the list is not empty, then return it as an array if (list.size() != 0) { values = (String[]) list.toArray(new String[list.size()]); } return values; } /** * Get an array style property. * * @param name Property name. * @return Array of property values or empty array. */ public String[] getArrayProperty(String name) { return getArrayProperty(name, EMPTY_ARRAY_PROPERTY); } /** * Return an iterator over all contained property names. * * @return Property name iterator. */ public Iterator names() { return keySet().iterator(); } /** * Check if this map contains a given property. * * @param name Property name. * @return True if contains property. */ public boolean containsProperty(String name) { return containsKey(name); } /** * Get a property group for the given property base. * * @param basename Base property name. * @return Property group. */ public PropertyGroup getPropertyGroup(String basename) { return new PropertyGroup(basename, this); } /** * Get a property group for the given property base at the given index. * * @param basename Base property name. * @param index Array property index. * @return Property group. */ public PropertyGroup getPropertyGroup(String basename, int index) { String name = makeIndexPropertyName(basename, index); return getPropertyGroup(name); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { // reset the listener lists init(); stream.defaultReadObject(); } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/MethodBoundPropertyListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/MethodBoundP0000644000175000017500000001461510774222622033322 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jboss.util.ThrowableHandler; import org.jboss.util.propertyeditor.PropertyEditors; /** * Binds property values to class methods. * * @version $Revision: 2787 $ * @author Jason Dillon */ public class MethodBoundPropertyListener extends BoundPropertyAdapter { /** Property name which we are bound to */ protected final String propertyName; /** Instance object that contains setter method */ protected final Object instance; /** Property setter method */ protected final Method setter; /** Property descriptor */ protected final PropertyDescriptor descriptor; /** * Construct a MethodBoundPropertyListener. * * @param instance Instance object that contains setter method. * @param propertyName The name of the property which will be bound. * @param beanPropertyName The name of the property setter method. * * @throws PropertyException */ public MethodBoundPropertyListener(final Object instance, final String propertyName, final String beanPropertyName) { this.instance = instance; this.propertyName = propertyName; try { descriptor = getPropertyDescriptor(beanPropertyName); if (descriptor == null) { throw new PropertyException ("missing method for: " + beanPropertyName); } setter = descriptor.getWriteMethod(); if (setter == null) { throw new PropertyException ("missing setter method for: " + beanPropertyName); } try { setter.setAccessible(true); } catch (SecurityException e) { ThrowableHandler.add(e); } } catch (IntrospectionException e) { throw new PropertyException(e); } } /** * Get the PropertyDescriptor for the given bean property name. * * @param beanPropertyName Bean property name. * @return PropertyDescriptor. */ private PropertyDescriptor getPropertyDescriptor(final String beanPropertyName) throws IntrospectionException { Class instanceType = instance.getClass(); BeanInfo beanInfo = Introspector.getBeanInfo(instanceType); PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors(); PropertyDescriptor descriptor = null; for (int i=0; i type = descriptor.getPropertyType(); PropertyEditor editor = PropertyEditors.findEditor(type); editor.setAsText(value); Object coerced = editor.getValue(); // System.out.println("type: " + type); // System.out.println("coerced: " + coerced); // invoke the setter method setter.invoke(instance, new Object[] { coerced }); } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); if (target instanceof PropertyException) { throw (PropertyException)target; } else { throw new PropertyException(target); } } catch (Exception e) { throw new PropertyException(e); } } /** * Notifies that a property has been added. * * @param event Property event. */ public void propertyAdded(final PropertyEvent event) { invokeSetter(event.getPropertyValue()); } /** * Notifies that a property has changed. * * @param event Property event. */ public void propertyChanged(final PropertyEvent event) { invokeSetter(event.getPropertyValue()); } /** * Notifies that this listener was bound to a property. * * @param map PropertyMap which contains property bound to. */ public void propertyBound(final PropertyMap map) { // only set the field if the map contains the property already if (map.containsProperty(propertyName)) { invokeSetter(map.getProperty(propertyName)); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyAdapter.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyAdap0000644000175000017500000000360310470642610033373 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; /** * An abstract adapter class for receving property events. * *

Methods defined in this class are empty. This class exists as * as convenience for creating listener objects. * * @version $Revision: 1958 $ * @author Jason Dillon */ public abstract class PropertyAdapter implements PropertyListener { /** * Notifies that a property was added. * * @param event Property event. */ public void propertyAdded(final PropertyEvent event) {} /** * Notifies that a property was removed. * * @param event Property event. */ public void propertyRemoved(final PropertyEvent event) {} /** * Notifies that a property has changed. * * @param event Property event. */ public void propertyChanged(final PropertyEvent event) {} } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyEvent.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyEven0000644000175000017500000000613010776226110033423 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.EventObject; import org.jboss.util.NullArgumentException; /** * A property event. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class PropertyEvent extends EventObject { /** The serialVersionUID */ private static final long serialVersionUID = -5007209897739884086L; /** Property name. */ protected final String name; /** Property value. */ protected final String value; /** * Construct a new PropertyEvent. * * @param source The source of the event. * @param name The property name effected. * @param value The value of the property effected. * * @throws NullArgumentException Name or source is null. */ public PropertyEvent(final Object source, final String name, final String value) { super(source); if (name == null) throw new NullArgumentException("name"); // value can be null this.name = name; this.value = value; } /** * Construct a new PropertyEvent. * * @param source The source of the event. * @param name The property name effected. * * @throws NullArgumentException Name or source is null. */ public PropertyEvent(Object source, String name) { this(source, name, null); } /** * Get the name of the property that is effected. * * @return Property name. */ public final String getPropertyName() { return name; } /** * Get the value of the property that is effected. * * @return The value of the property that is effected or null. */ public final String getPropertyValue() { return value; } /** * Return a string representation of this event. * * @return A string representation of this event. */ public String toString() { return super.toString() + "{ name=" + name + ", value=" + value + " }"; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/FieldBoundPropertyListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/FieldBoundPr0000644000175000017500000001243010774222622033300 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import org.jboss.util.FieldInstance; import org.jboss.util.NullArgumentException; import org.jboss.util.Classes; import org.jboss.util.ThrowableHandler; import org.jboss.util.propertyeditor.PropertyEditors; import java.beans.PropertyEditor; /** * Binds property values to class fields. * * @version $Revision: 2787 $ * @author Jason Dillon */ public class FieldBoundPropertyListener extends BoundPropertyAdapter { /** Property name which we are bound to */ protected final String propertyName; /** Field instance */ protected final FieldInstance fieldInstance; /** * Constructs a FieldBoundPropertyListener. * * @param instance Instance object. * @param fieldName Field name. * @param propertyName Property to bind to. * * @throws NullArgumentException Property name is null. */ public FieldBoundPropertyListener(final Object instance, final String fieldName, final String propertyName) { if (propertyName == null) throw new NullArgumentException("propertyName"); // FieldInstance checks instance & fieldName this.propertyName = propertyName; try { // construct field instance fieldInstance = new FieldInstance(instance, fieldName); try { fieldInstance.getField().setAccessible(true); } catch (SecurityException e) { ThrowableHandler.add(e); } // force the given class to load, so that any CoersionHelpers // that are nested in it are loaded properly Classes.forceLoad(fieldInstance.getField().getType()); } catch (NoSuchFieldException e) { throw new PropertyException(e); } } /** * Constructs a FieldBoundPropertyListener. * *

Field name is used for property name. * * @param instance Instance object. * @param fieldName Field name. */ public FieldBoundPropertyListener(final Object instance, final String fieldName) { this(instance, fieldName, fieldName); } /** * Get the property name which this listener is bound to. * * @return Property name. */ public final String getPropertyName() { return propertyName; } /** * Filter the property value prior to coercing and binding to field. * *

Allows instance to filter values prior to object coercion and * field binding. * * @param value Property value. * @return the filtered value */ public String filterValue(String value) { return value; } /** * Coerce and set specified value to field. * * @param value Field value. * * @throws PropertyException Failed to set field value. */ protected void setFieldValue(String value) { try { // filter property value value = filterValue(value); // coerce value to field type Class type = fieldInstance.getField().getType(); PropertyEditor editor = PropertyEditors.findEditor(type); editor.setAsText(value); Object coerced = editor.getValue(); // bind value to field fieldInstance.set(coerced); } catch (IllegalAccessException e) { throw new PropertyException(e); } } /** * Notifies that a property has been added. * * @param event Property event. */ public void propertyAdded(final PropertyEvent event) { setFieldValue(event.getPropertyValue()); } /** * Notifies that a property has changed * * @param event Property event */ public void propertyChanged(final PropertyEvent event) { setFieldValue(event.getPropertyValue()); } /** * Notifies that this listener was bound to a property. * * @param map PropertyMap which contains property bound to. */ public void propertyBound(final PropertyMap map) { // only set the field if the map contains the property already if (map.containsProperty(propertyName)) { setFieldValue(map.getProperty(propertyName)); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyContainer.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyCont0000644000175000017500000001266610776226110033444 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.Properties; /** * Provides helper methods for working with instance or class properties. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class PropertyContainer extends PropertyMap { /** The serialVersionUID */ private static final long serialVersionUID = -3347198703863412326L; /** The group name for this container. */ protected String groupname = ""; /** * Initialize the container with a property group. * @param props */ public PropertyContainer(final Properties props) { super(props); } /** * Initialize the container with a property group of the given name. * * @param groupname Property group name. */ public PropertyContainer(final String groupname) { this(Property.getGroup(groupname)); this.groupname = groupname; } /** * Initialize the container with a property group of the given class name. * * @param type The class whos name will be the property group name. */ public PropertyContainer(final Class type) { this(type.getName()); } /** * Creates a {@link FieldBoundPropertyListener} for the field and * property name and adds it the underlying property group. * * @param name The field name to bind values to. * @param propertyName The property name to bind to. * * @throws IllegalArgumentException Field of property name is null or * empty. */ protected void bindField(final String name, final String propertyName) { if (name == null || name.equals("")) throw new IllegalArgumentException("name"); if (propertyName == null || propertyName.equals("")) throw new IllegalArgumentException("propertyName"); addPropertyListener (new FieldBoundPropertyListener(this, name, propertyName)); } /** * Creates a {@link FieldBoundPropertyListener} for the field and * property name and adds it the underlying property group. * * @param name The field name and property to bind values to. * * @throws IllegalArgumentException Field of property name is null or * empty. */ protected void bindField(final String name) { bindField(name, name); } /** * Creates a {@link MethodBoundPropertyListener} for the method and * property name and adds it the underlying property group. * * @param name The method name to bind values to. * @param propertyName The property name to bind to. * * @throws IllegalArgumentException Method of property name is null or * empty. */ protected void bindMethod(final String name, final String propertyName) { if (name == null || name.equals("")) throw new IllegalArgumentException("name"); if (propertyName == null || propertyName.equals("")) throw new IllegalArgumentException("propertyName"); addPropertyListener // opposite of field bound =( (new MethodBoundPropertyListener(this, propertyName, name)); } /** * Creates a {@link MethodBoundPropertyListener} for the method and * property name and adds it the underlying property group. * * @param name The method name and property to bind values to. * * @throws IllegalArgumentException Method of property name is null or * empty. */ protected void bindMethod(final String name) { bindMethod(name, name); } private String makeName(final String name) { return groupname + "." + name; } protected void throwException(final String name) throws PropertyException { throw new PropertyException(makeName(name)); } protected void throwException(final String name, final String msg) throws PropertyException { throw new PropertyException(makeName(name) + ": " + msg); } protected void throwException(final String name, final String msg, final Throwable nested) throws PropertyException { throw new PropertyException(makeName(name) + ": " + msg, nested); } protected void throwException(final String name, final Throwable nested) throws PropertyException { throw new PropertyException(makeName(name), nested); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyListener.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyList0000644000175000017500000000371110470642610033441 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import java.util.EventListener; /** * The listener interface for receiving property events. * *

Classes that are interested in processing a property event implement * this interface, and register instance objects with a given PropertyMap * or the PropertyManager via addPropertyListener(). * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface PropertyListener extends EventListener { /** * Notifies that a property was added * * @param event Property event */ void propertyAdded(PropertyEvent event); /** * Notifies that a property was removed * * @param event Property event */ void propertyRemoved(PropertyEvent event); /** * Notifies that a property has changed * * @param event Property event */ void propertyChanged(PropertyEvent event); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyError.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/property/PropertyErro0000644000175000017500000000436710776226110033447 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.property; import org.jboss.util.NestedError; /** * Thrown to indicate a fatal problem with the property system. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class PropertyError extends NestedError { /** The serialVersionUID */ private static final long serialVersionUID = -4956548740655706282L; /** * Construct a PropertyError with the specified detail * message. * * @param msg Detail message. */ public PropertyError(String msg) { super(msg); } /** * Construct a PropertyError with the specified detail * message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public PropertyError(String msg, Throwable nested) { super(msg, nested); } /** * Construct a PropertyError with the specified * nested Throwable. * * @param nested Nested Throwable. */ public PropertyError(Throwable nested) { super(nested); } /** * Construct a PropertyError with no detail. */ public PropertyError() { super(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/platform/0000755000175000017500000000000011105642364030776 5ustar twernertwerner././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/platform/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/platform/package.html0000644000175000017500000000175210470642610033262 0ustar twernertwerner

Platform specific extentions to the Java programming language.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • Add default implementation for PID that generates psuedo-pid-like numbers
  • Add native support for PID
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/platform/Java.java0000644000175000017500000001126710555402342032527 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.platform; /** * Provides common access to specifics about the version of Java * that a virtual machine supports. * *

Determines the version of the Java Virtual Machine by checking * for the availablity of version specific classes.

* *

Classes are loaded in the following order: *

    *
  1. java.lang.Void was introduced in JDK 1.1
  2. *
  3. java.lang.ThreadLocal was introduced in JDK 1.2
  4. *
  5. java.lang.StrictMath was introduced in JDK 1.3
  6. *
  7. java.lang.StackTraceElement was introduced in JDK 1.4
  8. *
  9. java.lang.Enum was introduced in JDK 1.5
  10. *
  11. java.lang.management.LockInfo was introduced in JDK 1.6
  12. *
*

* * @version $Revision: 2240 $ * @author Jason Dillon * @author Dimitris Andreadis */ public final class Java { /** Prevent instantiation */ private Java() {} /** Java version 1.0 token */ public static final int VERSION_1_0 = 0x01; /** Java version 1.1 token */ public static final int VERSION_1_1 = 0x02; /** Java version 1.2 token */ public static final int VERSION_1_2 = 0x03; /** Java version 1.3 token */ public static final int VERSION_1_3 = 0x04; /** Java version 1.4 token */ public static final int VERSION_1_4 = 0x05; /** Java version 1.5 token */ public static final int VERSION_1_5 = 0x06; /** Java version 1.6 token */ public static final int VERSION_1_6 = 0x07; /** * Private to avoid over optimization by the compiler. * * @see #getVersion() Use this method to access this final value. */ private static final int VERSION; /** Initialize VERSION. */ static { // default to 1.0 int version = VERSION_1_0; try { // check for 1.1 Class.forName("java.lang.Void"); version = VERSION_1_1; // check for 1.2 Class.forName("java.lang.ThreadLocal"); version = VERSION_1_2; // check for 1.3 Class.forName("java.lang.StrictMath"); version = VERSION_1_3; // check for 1.4 Class.forName("java.lang.StackTraceElement"); version = VERSION_1_4; // check for 1.5 Class.forName("java.lang.Enum"); version = VERSION_1_5; // check for 1.6 Class.forName("java.lang.management.LockInfo"); version = VERSION_1_6; } catch (ClassNotFoundException ignore) { } VERSION = version; } /** * Return the version of Java supported by the VM. * * @return The version of Java supported by the VM. */ public static int getVersion() { return VERSION; } /** * Returns true if the given version identifer is equal to the * version identifier of the current virtuial machine. * * @param version The version identifier to check for. * @return True if the current virtual machine is the same version. */ public static boolean isVersion(final int version) { return VERSION == version; } /** * Returns true if the current virtual machine is compatible with * the given version identifer. * * @param version The version identifier to check compatibility of. * @return True if the current virtual machine is compatible. */ public static boolean isCompatible(final int version) { // if our vm is the same or newer then we are compatible return VERSION >= version; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/platform/PID.java0000644000175000017500000000776610776226110032275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.platform; import java.io.Serializable; import java.util.Random; /** * Provides access to the process identifier for this virtual machine. * *

Currently does not support native access and generates random numbers * for the process id. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class PID implements Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = -6837013326314943907L; /** The int process identifier. */ protected final int id; /** * Construct a new PID. * * @param id Process identifier. */ protected PID(final int id) { this.id = id; } /** * Get the int process identifier. * * @return int process identifier. */ public final int getID() { return id; } /** * Return a string representation of this PID. * * @return A string representation of this PID. */ public String toString() { return String.valueOf(id); } /** * Return a string representation of this PID. * @param radix * * @return A string representation of this PID. */ public String toString(int radix) { return Integer.toString(id, radix); } /** * Return the hash code of this PID. * * @return The hash code of this PID. */ public int hashCode() { return id; } /** * Check if the given object is equal to this PID. * * @param obj Object to test equality with. * @return True if object is equals to this PID. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { PID pid = (PID)obj; return pid.id == id; } return false; } /** * Returns a copy of this PID. * * @return A copy of this PID. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ///////////////////////////////////////////////////////////////////////// // Instance Access // ///////////////////////////////////////////////////////////////////////// /** The single instance of PID for the running Virtual Machine */ private static PID instance = null; /** * Get the PID for the current virtual machine. * * @return Process identifier. */ public synchronized static PID getInstance() { if (instance == null) { instance = create(); } return instance; } /** * Create the PID for the current virtual mahcine. * * @return Process identifier. */ private static PID create() { // for now just return a random integer. int random = Math.abs(new Random().nextInt()); return new PID(random); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/LRUCachePolicy.java0000644000175000017500000003542511032707620032570 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.HashMap; import java.util.Map; /** * Implementation of a Least Recently Used cache policy. * * @author Simone Bordet * @version $Revision: 2883 $ */ @SuppressWarnings("unchecked") public class LRUCachePolicy implements CachePolicy { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- /** * The map holding the cached objects */ protected Map m_map; /** * The linked list used to implement the LRU algorithm */ protected LRUList m_list; /** * The maximum capacity of this cache */ protected int m_maxCapacity; /** * The minimum capacity of this cache */ protected int m_minCapacity; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Creates a LRU cache policy object with zero cache capacity. * * @see #create */ public LRUCachePolicy() { } /** * Creates a LRU cache policy object with the specified minimum * and maximum capacity. * @param min * @param max * * @see #create */ public LRUCachePolicy(int min, int max) { if (min < 2 || min > max) {throw new IllegalArgumentException("Illegal cache capacities");} m_minCapacity = min; m_maxCapacity = max; } /** * Create map holding entries. * * @return the map */ protected Map createMap() { return new HashMap(); } // Public -------------------------------------------------------- // Service implementation ---------------------------------------------- /** * Initializes the cache, creating all required objects and initializing their * values. * @see #start * @see #destroy */ public void create() { m_map = createMap(); m_list = createList(); m_list.m_maxCapacity = m_maxCapacity; m_list.m_minCapacity = m_minCapacity; m_list.m_capacity = m_maxCapacity; } /** * Starts this cache that is now ready to be used. * @see #create * @see #stop */ public void start() { } /** * Stops this cache thus {@link #flush}ing all cached objects.
* After this method is called, a call to {@link #start} will restart the cache. * @see #start * @see #destroy */ public void stop() { if (m_list != null) { flush(); } } /** * Destroys the cache that is now unusable.
* To have it working again it must be re-{@link #create}ed and * re-{@link #start}ed. * * @see #create */ public void destroy() { if( m_map != null ) m_map.clear(); if( m_list != null ) m_list.clear(); } public Object get(Object key) { if (key == null) { throw new IllegalArgumentException("Requesting an object using a null key"); } LRUCacheEntry value = (LRUCacheEntry)m_map.get(key); if (value != null) { m_list.promote(value); return value.m_object; } else { cacheMiss(); return null; } } public Object peek(Object key) { if (key == null) { throw new IllegalArgumentException("Requesting an object using a null key"); } LRUCacheEntry value = (LRUCacheEntry)m_map.get(key); if (value == null) { return null; } else { return value.m_object; } } public void insert(Object key, Object o) { if (o == null) {throw new IllegalArgumentException("Cannot insert a null object in the cache");} if (key == null) {throw new IllegalArgumentException("Cannot insert an object in the cache with null key");} if (m_map.containsKey(key)) { throw new IllegalStateException("Attempt to put in the cache an object that is already there"); } m_list.demote(); LRUCacheEntry entry = createCacheEntry(key, o); m_map.put(key, entry); m_list.promote(entry); } public void remove(Object key) { if (key == null) {throw new IllegalArgumentException("Removing an object using a null key");} Object value = m_map.remove(key); if (value != null) { m_list.remove((LRUCacheEntry)value); } //else Do nothing, the object isn't in the cache list } public void flush() { LRUCacheEntry entry = null; while ((entry = m_list.m_tail) != null) { ageOut(entry); } } public int size() { return m_list.m_count; } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- /** * Factory method for the linked list used by this cache implementation. * @return the lru list */ protected LRUList createList() {return new LRUList();} /** * Callback method called when the cache algorithm ages out of the cache * the given entry.
* The implementation here is removing the given entry from the cache. * @param entry */ protected void ageOut(LRUCacheEntry entry) { remove(entry.m_key); } /** * Callback method called when a cache miss happens. */ protected void cacheMiss() { } /** * Factory method for cache entries * @param key * @param value * @return the entry */ protected LRUCacheEntry createCacheEntry(Object key, Object value) { return new LRUCacheEntry(key, value); } // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- /** * Double queued list used to store cache entries. */ public class LRUList { /** The maximum capacity of the cache list */ @SuppressWarnings("hiding") public int m_maxCapacity; /** The minimum capacity of the cache list */ @SuppressWarnings("hiding") public int m_minCapacity; /** The current capacity of the cache list */ public int m_capacity; /** The number of cached objects */ public int m_count; /** The head of the double linked list */ public LRUCacheEntry m_head; /** The tail of the double linked list */ public LRUCacheEntry m_tail; /** The cache misses happened */ public int m_cacheMiss; /** * Creates a new double queued list. */ protected LRUList() { m_head = null; m_tail = null; m_count = 0; } /** * Promotes the cache entry entry to the last used position * of the list.
* If the object is already there, does nothing. * @param entry the object to be promoted, cannot be null * @see #demote * @throws IllegalStateException if this method is called with a full cache */ protected void promote(LRUCacheEntry entry) { if (entry == null) {throw new IllegalArgumentException("Trying to promote a null object");} if (m_capacity < 1) {throw new IllegalStateException("Can't work with capacity < 1");} entryPromotion(entry); entry.m_time = System.currentTimeMillis(); if (entry.m_prev == null) { if (entry.m_next == null) { // entry is new or there is only the head if (m_count == 0) // cache is empty { m_head = entry; m_tail = entry; ++m_count; entryAdded(entry); } else if (m_count == 1 && m_head == entry) {} // there is only the head and I want to promote it, do nothing else if (m_count < m_capacity) { entry.m_prev = null; entry.m_next = m_head; m_head.m_prev = entry; m_head = entry; ++m_count; entryAdded(entry); } else if (m_count < m_maxCapacity) { entry.m_prev = null; entry.m_next = m_head; m_head.m_prev = entry; m_head = entry; ++m_count; int oldCapacity = m_capacity; ++m_capacity; entryAdded(entry); capacityChanged(oldCapacity); } else {throw new IllegalStateException("Attempt to put a new cache entry on a full cache");} } else {} // entry is the head, do nothing } else { if (entry.m_next == null) // entry is the tail { LRUCacheEntry beforeLast = entry.m_prev; beforeLast.m_next = null; entry.m_prev = null; entry.m_next = m_head; m_head.m_prev = entry; m_head = entry; m_tail = beforeLast; } else // entry is in the middle of the list { LRUCacheEntry previous = entry.m_prev; previous.m_next = entry.m_next; entry.m_next.m_prev = previous; entry.m_prev = null; entry.m_next = m_head; m_head.m_prev = entry; m_head = entry; } } } /** * Demotes from the cache the least used entry.
* If the cache is not full, does nothing. * @see #promote */ protected void demote() { if (m_capacity < 1) {throw new IllegalStateException("Can't work with capacity < 1");} if (m_count > m_maxCapacity) {throw new IllegalStateException("Cache list entries number (" + m_count + ") > than the maximum allowed (" + m_maxCapacity + ")");} if (m_count == m_maxCapacity) { LRUCacheEntry entry = m_tail; // the entry will be removed by ageOut ageOut(entry); } else {} // cache is not full, do nothing } /** * Removes from the cache list the specified entry. * @param entry */ protected void remove(LRUCacheEntry entry) { if (entry == null) {throw new IllegalArgumentException("Cannot remove a null entry from the cache");} if (m_count < 1) {throw new IllegalStateException("Trying to remove an entry from an empty cache");} entry.m_key = entry.m_object = null; if (m_count == 1) { m_head = m_tail = null; } else { if (entry.m_prev == null) // the head { m_head = entry.m_next; m_head.m_prev = null; entry.m_next = null; } else if (entry.m_next == null) // the tail { m_tail = entry.m_prev; m_tail.m_next = null; entry.m_prev = null; } else // in the middle { entry.m_next.m_prev = entry.m_prev; entry.m_prev.m_next = entry.m_next; entry.m_prev = null; entry.m_next = null; } } --m_count; entryRemoved(entry); } /** * Callback that signals that the given entry is just about to be added. * @param entry */ protected void entryPromotion(LRUCacheEntry entry) {} /** * Callback that signals that the given entry has been added to the cache. * @param entry */ protected void entryAdded(LRUCacheEntry entry) {} /** * Callback that signals that the given entry has been removed from the cache. * @param entry */ protected void entryRemoved(LRUCacheEntry entry) {} /** * Callback that signals that the capacity of the cache is changed. * @param oldCapacity the capacity before the change happened */ protected void capacityChanged(int oldCapacity) {} protected void clear() { LRUCacheEntry entry = m_head; m_head = null; m_tail = null; m_count = 0; for (; entry != null; entry = entry.m_next) entryRemoved(entry); } public String toString() { String s = Integer.toHexString(super.hashCode()); s += " size: " + m_count; for (LRUCacheEntry entry = m_head; entry != null; entry = entry.m_next) { s += "\n" + entry; } return s; } } /** * Double linked cell used as entry in the cache list. */ public class LRUCacheEntry { /** Reference to the next cell in the list */ public LRUCacheEntry m_next; /** Reference to the previous cell in the list */ public LRUCacheEntry m_prev; /** The key used to retrieve the cached object */ public Object m_key; /** The cached object */ public Object m_object; /** The timestamp of the creation */ public long m_time; /** * Creates a new double linked cell, storing the object we * want to cache and the key that is used to retrieve it. * @param key * @param object */ protected LRUCacheEntry(Object key, Object object) { m_key = key; m_object = object; m_next = null; m_prev = null; m_time = 0; // Set when inserted in the list. } public String toString() { return "key: " + m_key + ", object: " + ( m_object==null ? "null" : Integer.toHexString(m_object.hashCode())) + ", entry: " + Integer.toHexString(super.hashCode()); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/SoftObject.java0000644000175000017500000000732210774222622032065 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.ref.SoftReference; import java.lang.ref.ReferenceQueue; /** * Convenience class to wrap an Object into a SoftReference. * *

Modified from java.util.WeakHashMap.WeakKey. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public final class SoftObject extends SoftReference { /** The hash code of the nested object */ protected final int hashCode; /** * Construct a SoftObject. * * @param obj Object to reference. */ public SoftObject(final Object obj) { super(obj); hashCode = obj.hashCode(); } /** * Construct a SoftObject. * * @param obj Object to reference. * @param queue Reference queue. */ public SoftObject(final Object obj, final ReferenceQueue queue) { super(obj, queue); hashCode = obj.hashCode(); } /** * Check the equality of an object with this. * * @param obj Object to test equality with. * @return True if object is equal. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { SoftObject soft = (SoftObject)obj; Object a = this.get(); Object b = soft.get(); if (a == null || b == null) return false; if (a == b) return true; return a.equals(b); } return false; } /** * Return the hash code of the nested object. * * @return The hash code of the nested object. */ public int hashCode() { return hashCode; } ///////////////////////////////////////////////////////////////////////// // Factory Methods // ///////////////////////////////////////////////////////////////////////// /** * Create a SoftObject for the given object. * * @param obj Object to reference. * @return SoftObject or null if object is null. */ public static SoftObject create(final Object obj) { if (obj == null) return null; else return new SoftObject(obj); } /** * Create a SoftObject for the given object. * * @param obj Object to reference. * @param queue Reference queue. * @return SoftObject or null if object is null. */ public static SoftObject create(final Object obj, final ReferenceQueue queue) { if (obj == null) return null; else return new SoftObject(obj, queue); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/0000755000175000017500000000000011105642364031305 5ustar twernertwerner././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SerializableEnumeration.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Serializab0000644000175000017500000000464510776226110033326 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.NoSuchElementException; /** * ??? * * @author ??? * @version $Revision: 2800 $ */ @SuppressWarnings("unchecked") public class SerializableEnumeration extends ArrayList implements Enumeration { /** The serialVersionUID */ private static final long serialVersionUID = 8678951571196067510L; private int index; public SerializableEnumeration () { index = 0; } public SerializableEnumeration (Collection c) { super(c); index = 0; } public SerializableEnumeration (int initialCapacity) { super(initialCapacity); index = 0; } public boolean hasMoreElements() { return (index < size()); } public Object nextElement() throws NoSuchElementException { try { Object nextObj = get(index); index++; return nextObj; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { // the only thing to write is the index field out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueTreeMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueT0000644000175000017500000000344711103262257033245 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.Comparator; import java.util.SortedMap; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @author Ales Justin */ public class WeakValueTreeMap extends ReferenceValueTreeMap { public WeakValueTreeMap() { } public WeakValueTreeMap(Comparator kComparator) { super(kComparator); } public WeakValueTreeMap(SortedMap> sorted) { super(sorted); } protected ValueRef create(K key, V value, ReferenceQueue q) { return WeakValueRef.create(key, value, q); } }././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/EmptyCollectionException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/EmptyColle0000644000175000017500000000343210776226110033307 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; /** * Thrown to indicate that an operation can not be performed on an empty * collection. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class EmptyCollectionException extends CollectionException { /** The serialVersionUID */ private static final long serialVersionUID = -4562591066479152759L; /** * Construct a EmptyCollectionException with the specified * detail message. * * @param msg Detail message. */ public EmptyCollectionException(String msg) { super(msg); } /** * Construct a EmptyCollectionException with no detail. */ public EmptyCollectionException() { super(); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakIdentityHashMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakIdenti0000644000175000017500000007262110774222622033266 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; import java.util.*; /** * A hashtable-based Map implementation with weak keys and * using reference-equality in place of object-equality when comparing keys * (and values). In an WeakIdentityHashMap, two keys k1 and * k2 are considered equal if and only if (k1==k2). * An entry in a WeakIdentityHashMap will automatically be removed when * its key is no longer in ordinary use. More precisely, the presence of a * mapping for a given key will not prevent the key from being discarded by the * garbage collector, that is, made finalizable, finalized, and then reclaimed. * When a key has been discarded its entry is effectively removed from the map. * *

Based on java.util.WeakHashMap

* * @author Dawid Kurzyniec * @version $Revision: 2787 $ * @author Kabir Khan * @see java.util.IdentityHashMap * @see java.util.WeakHashMap */ @SuppressWarnings("unchecked") public class WeakIdentityHashMap /*extends AbstractMap*/ implements Map { /** * The default initial capacity -- MUST be a power of two. */ private static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load fast used when none specified in constructor. */ private static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The table, resized as necessary. Length MUST Always be a power of two. */ private Entry[] table; /** * The number of key-value mappings contained in this weak hash map. */ private int size; /** * The next size value at which to resize (capacity * load factor). */ private int threshold; /** * The load factor for the hash table. */ private final float loadFactor; /** * Reference queue for cleared WeakEntries */ private final ReferenceQueue queue = new ReferenceQueue(); /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ private volatile int modCount; /** * Each of these fields are initialized to contain an instance of the * appropriate view the first time this view is requested. The views are * stateless, so there's no reason to create more than one of each. */ transient volatile Set keySet = null; transient volatile Collection values = null; /** * Constructs a new, empty WeakIdentityHashMap with the given * initial capacity and the given load factor. * * @param initialCapacity The initial capacity of the * WeakIdentityHashMap * @param loadFactor The load factor of the * WeakIdentityHashMap * @throws IllegalArgumentException If the initial capacity is negative, * or if the load factor is nonpositive. */ public WeakIdentityHashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Initial Capacity: "+ initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load factor: "+ loadFactor); int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; table = new Entry[capacity]; this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); } /** * Constructs a new, empty WeakIdentityHashMap with the given * initial capacity and the default load factor, which is 0.75. * * @param initialCapacity The initial capacity of the * WeakIdentityHashMap * @throws IllegalArgumentException If the initial capacity is negative. */ public WeakIdentityHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs a new, empty WeakIdentityHashMap with the default * initial capacity (16) and the default load factor (0.75). */ public WeakIdentityHashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = DEFAULT_INITIAL_CAPACITY; table = new Entry[DEFAULT_INITIAL_CAPACITY]; } /** * Constructs a new WeakIdentityHashMap with the same mappings as * the specified Map. The WeakIdentityHashMap is created * with default load factor, which is 0.75 and an initial capacity * sufficient to hold the mappings in the specified Map. * * @param t the map whose mappings are to be placed in this map. * @throws NullPointerException if the specified map is null. */ public WeakIdentityHashMap(Map t) { this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, 16), DEFAULT_LOAD_FACTOR); putAll(t); } // internal utilities /** * Value representing null keys inside tables. */ private static final Object NULL_KEY = new Object(); /** * Use NULL_KEY for key if it is null. */ private static Object maskNull(Object key) { return (key == null ? NULL_KEY : key); } /** * Return internal representation of null key back to caller as null */ private static Object unmaskNull(Object key) { return (key == NULL_KEY ? null : key); } /** * Return a hash code for non-null Object x. */ int hash(Object x) { int h = System.identityHashCode(x); return h - (h << 7); // that is,, -127 * h } /** * Return index for hash code h. */ static int indexFor(int h, int length) { return h & (length-1); } /** * Expunge stale entries from the table. */ private void expungeStaleEntries() { Object r; while ( (r = queue.poll()) != null) { Entry e = (Entry)r; int h = e.hash; int i = indexFor(h, table.length); Entry prev = table[i]; Entry p = prev; while (p != null) { Entry next = p.next; if (p == e) { if (prev == e) table[i] = next; else prev.next = next; e.next = null; // Help GC e.value = null; // " " size--; break; } prev = p; p = next; } } } /** * Return the table after first expunging stale entries */ private Entry[] getTable() { expungeStaleEntries(); return table; } /** * Returns the number of key-value mappings in this map. * This result is a snapshot, and may not reflect unprocessed * entries that will be removed before next attempted access * because they are no longer referenced. */ public int size() { if (size == 0) return 0; expungeStaleEntries(); return size; } /** * Returns true if this map contains no key-value mappings. * This result is a snapshot, and may not reflect unprocessed * entries that will be removed before next attempted access * because they are no longer referenced. */ public boolean isEmpty() { return size() == 0; } /** * Returns the value to which the specified key is mapped in this weak * hash map, or 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 is also * possible that the map explicitly maps the key to null. The * containsKey method may be used to distinguish these two * cases. * * @param key the 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 #put(Object, Object) */ public Object get(Object key) { Object k = maskNull(key); int h = hash(k); Entry[] tab = getTable(); int index = indexFor(h, tab.length); Entry e = tab[index]; while (e != null) { if (e.hash == h && k == e.get()) return e.value; e = e.next; } return null; } /** * Returns true if this map contains a mapping for the * specified key. * * @param key The key whose presence in this map is to be tested * @return true if there is a mapping for key; * false otherwise */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * Returns the entry associated with the specified key in the HashMap. * Returns null if the HashMap contains no mapping for this key. */ Entry getEntry(Object key) { Object k = maskNull(key); int h = hash(k); Entry[] tab = getTable(); int index = indexFor(h, tab.length); Entry e = tab[index]; while (e != null && !(e.hash == h && k == e.get())) e = e.next; return e; } /** * Associates the specified value with the specified key in this map. * 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 HashMap previously associated * null with the specified key. */ public Object put(Object key, Object value) { Object k = maskNull(key); int h = hash(k); Entry[] tab = getTable(); int i = indexFor(h, tab.length); for (Entry e = tab[i]; e != null; e = e.next) { if (h == e.hash && k == e.get()) { Object oldValue = e.value; if (value != oldValue) e.value = value; return oldValue; } } modCount++; tab[i] = new Entry(k, value, queue, h, tab[i]); if (++size >= threshold) resize(tab.length * 2); return null; } /** * Rehashes the contents of this map into a new HashMap instance * with a larger capacity. This method is called automatically when the * number of keys in this map exceeds its capacity and load factor. * * Note that this method is a no-op if it's called with newCapacity == * 2*MAXIMUM_CAPACITY (which is Integer.MIN_VALUE). * * @param newCapacity the new capacity, MUST be a power of two. */ void resize(int newCapacity) { // assert (newCapacity & -newCapacity) == newCapacity; // power of 2 Entry[] oldTable = getTable(); int oldCapacity = oldTable.length; // check if needed if (size < threshold || oldCapacity > newCapacity) return; Entry[] newTable = new Entry[newCapacity]; transfer(oldTable, newTable); table = newTable; /* * If ignoring null elements and processing ref queue caused massive * shrinkage, then restore old table. This should be rare, but avoids * unbounded expansion of garbage-filled tables. */ if (size >= threshold / 2) { threshold = (int)(newCapacity * loadFactor); } else { expungeStaleEntries(); transfer(newTable, oldTable); table = oldTable; } } /** Transfer all entries from src to dest tables */ private void transfer(Entry[] src, Entry[] dest) { for (int j = 0; j < src.length; ++j) { Entry e = src[j]; src[j] = null; while (e != null) { Entry next = e.next; Object key = e.get(); if (key == null) { e.next = null; // Help GC e.value = null; // " " size--; } else { int i = indexFor(e.hash, dest.length); e.next = dest[i]; dest[i] = e; } e = next; } } } /** * Copies all of the mappings from the specified map to this map 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. * @throws NullPointerException if the specified map is null. */ public void putAll(Map t) { // Expand enough to hold t's elements without resizing. int n = t.size(); if (n == 0) return; if (n >= threshold) { n = (int)(n / loadFactor + 1); if (n > MAXIMUM_CAPACITY) n = MAXIMUM_CAPACITY; int capacity = table.length; while (capacity < n) capacity <<= 1; resize(capacity); } for (Iterator i = t.entrySet().iterator(); 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. * * @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. */ public Object remove(Object key) { Object k = maskNull(key); int h = hash(k); Entry[] tab = getTable(); int i = indexFor(h, tab.length); Entry prev = tab[i]; Entry e = prev; while (e != null) { Entry next = e.next; if (h == e.hash && k == e.get()) { modCount++; size--; if (prev == e) tab[i] = next; else prev.next = next; return e.value; } prev = e; e = next; } return null; } /** Special version of remove needed by Entry set */ Entry removeMapping(Object o) { if (!(o instanceof Map.Entry)) return null; Entry[] tab = getTable(); Map.Entry entry = (Map.Entry)o; Object k = maskNull(entry.getKey()); int h = hash(k); int i = indexFor(h, tab.length); Entry prev = tab[i]; Entry e = prev; while (e != null) { Entry next = e.next; if (h == e.hash && e.equals(entry)) { modCount++; size--; if (prev == e) tab[i] = next; else prev.next = next; return e; } prev = e; e = next; } return null; } /** * Removes all mappings from this map. */ public void clear() { // clear out ref queue. We don't need to expunge entries // since table is getting cleared. while (queue.poll() != null) ; modCount++; Entry tab[] = table; for (int i = 0; i < tab.length; ++i) tab[i] = null; size = 0; // Allocation of array may have caused GC, which may have caused // additional entries to go stale. Removing these entries from the // reference queue will make them eligible for reclamation. while (queue.poll() != null) ; } /** * Returns true if this map maps one or more keys to the * specified value. * * @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(Object value) { if (value==null) return containsNullValue(); Entry tab[] = getTable(); for (int i = tab.length ; i-- > 0 ;) for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false; } /** * Special-case code for containsValue with null argument */ private boolean containsNullValue() { Entry tab[] = getTable(); for (int i = tab.length ; i-- > 0 ;) for (Entry e = tab[i] ; e != null ; e = e.next) if (e.value==null) return true; return false; } /** * The entries in this hash table extend WeakReference, using its main ref * field as the key. */ private static class Entry extends WeakReference implements Map.Entry { private Object value; private final int hash; private Entry next; /** * Create new entry. */ Entry(Object key, Object value, ReferenceQueue queue, int hash, Entry next) { super(key, queue); this.value = value; this.hash = hash; this.next = next; } public Object getKey() { return unmaskNull(this.get()); } public Object getValue() { return value; } public Object setValue(Object newValue) { Object oldValue = value; value = newValue; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public int hashCode() { Object k = getKey(); Object v = getValue(); return ((k==null ? 0 : System.identityHashCode(k)) ^ (v==null ? 0 : v.hashCode())); } public String toString() { return getKey() + "=" + getValue(); } } private abstract class HashIterator implements Iterator { int index; Entry entry = null; Entry lastReturned = null; int expectedModCount = modCount; /** * Strong reference needed to avoid disappearance of key * between hasNext and next */ Object nextKey = null; /** * Strong reference needed to avoid disappearance of key * between nextEntry() and any use of the entry */ Object currentKey = null; HashIterator() { index = (size() != 0 ? table.length : 0); } public boolean hasNext() { Entry[] t = table; while (nextKey == null) { Entry e = entry; int i = index; while (e == null && i > 0) e = t[--i]; entry = e; index = i; if (e == null) { currentKey = null; return false; } nextKey = e.get(); // hold on to key in strong ref if (nextKey == null) entry = entry.next; } return true; } protected Entry nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (nextKey == null && !hasNext()) throw new NoSuchElementException(); lastReturned = entry; entry = entry.next; currentKey = nextKey; nextKey = null; return lastReturned; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); WeakIdentityHashMap.this.remove(currentKey); expectedModCount = modCount; lastReturned = null; currentKey = null; } } private class ValueIterator extends HashIterator { public Object next() { return nextEntry().value; } } private class KeyIterator extends HashIterator { public Object next() { return nextEntry().getKey(); } } private class EntryIterator extends HashIterator { public Object next() { return nextEntry(); } } // Views private transient Set entrySet = null; /** * 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. The set supports element removal, which removes the * corresponding mapping from this 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 keys contained in this map. */ public Set keySet() { Set ks = keySet; return (ks != null ? ks : (keySet = new KeySet())); } private class KeySet extends AbstractSet { public Iterator iterator() { return new KeyIterator(); } public int size() { return WeakIdentityHashMap.this.size(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { if (containsKey(o)) { WeakIdentityHashMap.this.remove(o); return true; } else return false; } public void clear() { WeakIdentityHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(); } public Object[] toArray(Object a[]) { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(a); } } /** * 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. The collection supports element * removal, which removes the corresponding mapping from this 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 Collection values() { Collection vs = values; return (vs != null ? vs : (values = new Values())); } private class Values extends AbstractCollection { public Iterator iterator() { return new ValueIterator(); } public int size() { return WeakIdentityHashMap.this.size(); } public boolean contains(Object o) { return containsValue(o); } public void clear() { WeakIdentityHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(); } public Object[] toArray(Object a[]) { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(i.next()); return c.toArray(a); } } /** * Returns a collection view of the mappings contained in this map. Each * element in the returned collection is a Map.Entry. The * collection is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. 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 mappings contained in this map. * @see java.util.Map.Entry */ public Set entrySet() { Set es = entrySet; return (es != null ? es : (entrySet = new EntrySet())); } private class EntrySet extends AbstractSet { public Iterator iterator() { return new EntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Entry candidate = getEntry(e.getKey()); return candidate != null && candidate.equals(e); } public boolean remove(Object o) { return removeMapping(o) != null; } public int size() { return WeakIdentityHashMap.this.size(); } public void clear() { WeakIdentityHashMap.this.clear(); } public Object[] toArray() { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(new SimpleEntry((Map.Entry) i.next())); return c.toArray(); } public Object[] toArray(Object a[]) { Collection c = new ArrayList(size()); for (Iterator i = iterator(); i.hasNext(); ) c.add(new SimpleEntry((Map.Entry) i.next())); return c.toArray(a); } } static class SimpleEntry implements Map.Entry { Object key; Object value; public SimpleEntry(Object key, Object value) { this.key = key; this.value = value; } public SimpleEntry(Map.Entry e) { this.key = e.getKey(); this.value = e.getValue(); } public Object getKey() { return key; } public Object getValue() { return value; } public Object setValue(Object value) { Object oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/AbstractQueue.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/AbstractQu0000644000175000017500000001043610774222622033307 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.AbstractCollection; /** * An abstract implementation of a Queue. Sub-classes must provide methods * for addLast(Object) and removeFirst(). * * @param the element type * @version $Revision: 2787 $ * @author Jason Dillon */ public abstract class AbstractQueue extends AbstractCollection implements Queue { /** Default maximum queue size */ public static int DEFAULT_MAXIMUM_SIZE = UNLIMITED_MAXIMUM_SIZE; /** Maximum queue size */ protected int maximumSize = DEFAULT_MAXIMUM_SIZE; /** * Initializes the AbstractQueue. */ protected AbstractQueue() {} /** * Initializes the AbstractQueue. * * @param maxSize Maximum queue size. * * @exception IllegalArgumentException Illegal size. */ protected AbstractQueue(final int maxSize) { setMaximumSize(maxSize); } /** * Get the maximum size of the queue. * * @return Maximum queue size or {@link #UNLIMITED_MAXIMUM_SIZE}. */ public int getMaximumSize() { return maximumSize; } /** * Set the maximum size of the queue * * @param size New maximim queue size or {@link #UNLIMITED_MAXIMUM_SIZE}. * * @exception IllegalArgumentException Illegal size. */ public void setMaximumSize(final int size) { if (size < 0 && size != UNLIMITED_MAXIMUM_SIZE) throw new IllegalArgumentException("illegal size: " + size); maximumSize = size; } /** * Check if the queue is full. * * @return True if the queue is full. */ public boolean isFull() { if (maximumSize != UNLIMITED_MAXIMUM_SIZE && size() >= maximumSize) return true; return false; } /** * Check if the queue is empty. * * @return True if the queue is empty. */ public boolean isEmpty() { if (size() <= 0) return true; return false; } /** * Append and object to the underling list. * * @param obj Object to enqueue. * @return True if collection was modified. * * @exception FullCollectionException The queue is full. */ public boolean add(E obj) throws FullCollectionException { if (isFull()) throw new FullCollectionException(); return addLast(obj); } /** * Remove and return the first object in the queue. * * @return Dequeued object. * * @exception EmptyCollectionException The queue is empty. */ public E remove() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(); return removeFirst(); } /** * Removes all of the elements from this queue */ public void clear() { while (!isEmpty()) { remove(); } } /** * Appends the given element to the end of the queue * * @param obj Object to append * @return Per Collection.add(), we return a boolean to indicate if * the object modified the collection. */ protected abstract boolean addLast(E obj); /** * Remove the first object in the queue * * @return First object in the queue */ protected abstract E removeFirst(); } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CollectionException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Collection0000644000175000017500000000331010776226110033320 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; /** * A generic collection exception. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class CollectionException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = 1470947618739421094L; /** * Construct a CollectionException with the specified * detail message. * * @param msg Detail message. */ public CollectionException(String msg) { super(msg); } /** * Construct a CollectionException with no detail. */ public CollectionException() { super(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SecurityActions.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SecurityAc0000644000175000017500000000427311015577255033317 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.security.AccessController; import java.security.PrivilegedAction; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ class SecurityActions { interface GetClassLoaderAction { ClassLoader getClassLoader(Class clazz); GetClassLoaderAction NON_PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(Class clazz) { return clazz.getClassLoader(); }}; GetClassLoaderAction PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { return clazz.getClassLoader(); }}); }}; } static ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() == null) { return GetClassLoaderAction.NON_PRIVILEGED.getClassLoader(clazz); } else { return GetClassLoaderAction.PRIVILEGED.getClassLoader(clazz); } } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReverseListIterator.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReverseLis0000644000175000017500000000446110774222622033322 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * An iterator that returns elements in reverse order from a list. * * @version $Revision: 2787 $ * @author Jason Dillon * @param */ public class ReverseListIterator implements Iterator { /** The list to get elements from */ protected final List list; /** The current index of the list */ protected int current; /** * Construct a ReverseListIterator for the given list. * * @param list List to iterate over. */ public ReverseListIterator(final List list) { this.list = list; current = list.size() - 1; } /** * Check if there are more elements. * * @return True if there are more elements. */ public boolean hasNext() { return current > 0; } /** * Get the next element. * * @return The next element. * * @throws NoSuchElementException */ public E next() { if (current <= 0) { throw new NoSuchElementException(); } return list.get(current--); } /** * Remove the current element. */ public void remove() { list.remove(current); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CachedCollection.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CachedColl0000644000175000017500000001003510774222622033212 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Collection; import java.util.AbstractCollection; import java.util.Iterator; import java.lang.ref.ReferenceQueue; import org.jboss.util.SoftObject; import org.jboss.util.Objects; /** * A wrapper around a Collection which translates added objects * into {@link SoftObject} references, allowing the VM to garbage collect * objects in the collection when memory is low. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class CachedCollection extends AbstractCollection { /** Reference queue */ protected final ReferenceQueue queue = new ReferenceQueue(); /** Wrapped collection */ protected final Collection collection; /** * Construct a CachedCollection. * * @param collection Collection to wrap. */ public CachedCollection(final Collection collection) { this.collection = collection; } /** * Returns an iterator over the elements contained in this collection. * * @return An iterator over the elements contained in this collection. */ public Iterator iterator() { maintain(); return new MyIterator(collection.iterator()); } /** * Returns the size of the collection. * * @return The number of elements in the collection. */ public int size() { maintain(); return collection.size(); } /** * Add an object to the collection. * * @param obj Object (or null to add to the collection. * @return True if object was added. */ public boolean add(final Object obj) { maintain(); SoftObject soft = SoftObject.create(obj, queue); return collection.add(soft); } /** * Maintains the collection by removing garbage collected objects. */ private void maintain() { SoftObject obj; int count = 0; while ((obj = (SoftObject)queue.poll()) != null) { count++; collection.remove(obj); } if (count != 0) { // some temporary debugging fluff System.err.println("vm reclaimed " + count + " objects"); } } ///////////////////////////////////////////////////////////////////////// // De-Referencing Iterator // ///////////////////////////////////////////////////////////////////////// /** * A dereferencing iterator. */ private final class MyIterator implements Iterator { private final Iterator iter; public MyIterator(final Iterator iter) { this.iter = iter; } public boolean hasNext() { maintain(); return iter.hasNext(); } private Object nextObject() { Object obj = iter.next(); return Objects.deref(obj); } public Object next() { maintain(); return nextObject(); } public void remove() { maintain(); iter.remove(); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftSet.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftSet.ja0000644000175000017500000001441510774222622033217 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.reflect.Array; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** * An implementation of Set that manages a map of soft references to * the set values. The map is keyed by the value hashCode and so this * is only useful for value whose hashCode is a valid identity * representation (String, primative wrappers, etc). * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class SoftSet implements Set { private HashMap map = new HashMap(); /** The queue of garbage collected soft references */ private ReferenceQueue gcqueue = new ReferenceQueue(); static class ComparableSoftReference extends SoftReference { private Integer key; ComparableSoftReference(Integer key, Object o, ReferenceQueue q) { super(o, q); this.key = key; } Integer getKey() { return key; } } static class ComparableSoftReferenceIterator implements Iterator { Iterator theIter; ComparableSoftReferenceIterator(Iterator theIter) { this.theIter = theIter; } public boolean hasNext() { return theIter.hasNext(); } public Object next() { ComparableSoftReference csr = (ComparableSoftReference) theIter.next(); return csr.get(); } public void remove() { theIter.remove(); } } /** * */ public SoftSet() { } public int size() { processQueue(); return map.size(); } public boolean isEmpty() { processQueue(); return map.isEmpty(); } public boolean contains(Object o) { processQueue(); Integer key = new Integer(o.hashCode()); boolean contains = map.containsKey(key); return contains; } public Iterator iterator() { processQueue(); Iterator theIter = map.values().iterator(); return new ComparableSoftReferenceIterator(theIter); } public Object[] toArray() { processQueue(); return toArray(new Object[0]); } public Object[] toArray(Object[] a) { processQueue(); int size = map.size(); Object[] array = {}; if( a.length >= size ) array = a; Iterator iter = map.values().iterator(); int index = 0; while( iter.hasNext() ) { ComparableSoftReference csr = (ComparableSoftReference) iter.next(); Object value = csr.get(); // Create the correct array type if( array.length == 0 ) { if( value == null ) { index ++; continue; } Array.newInstance(value.getClass(), size); } array[index] = value; index ++; } return array; } public boolean add(Object o) { processQueue(); Integer key = new Integer(o.hashCode()); ComparableSoftReference sr = new ComparableSoftReference(key, o, gcqueue); return map.put(key, sr) == null; } public boolean remove(Object o) { processQueue(); Integer key = new Integer(o.hashCode()); return map.remove(key) != null; } public boolean containsAll(Collection c) { processQueue(); Iterator iter = c.iterator(); boolean contains = true; while( iter.hasNext() ) { Object value = iter.next(); Integer key = new Integer(value.hashCode()); contains &= map.containsKey(key); } return contains; } public boolean addAll(Collection c) { processQueue(); Iterator iter = c.iterator(); boolean added = false; while( iter.hasNext() ) { Object value = iter.next(); Integer key = new Integer(value.hashCode()); ComparableSoftReference sr = new ComparableSoftReference(key, value, gcqueue); added |= map.put(key, sr) == null; } return added; } public boolean retainAll(Collection c) { Iterator iter = iterator(); boolean removed = false; while( iter.hasNext() ) { Object value = iter.next(); if( c.contains(value) == false ) { iter.remove(); removed = true; } } return removed; } public boolean removeAll(Collection c) { processQueue(); Iterator iter = c.iterator(); boolean removed = false; while( iter.hasNext() ) { Object value = iter.next(); removed |= remove(value); } return removed; } public void clear() { while( gcqueue.poll() != null ) ; map.clear(); } public boolean equals(Object o) { return map.equals(o); } public int hashCode() { return map.hashCode(); } /** * Iterate through the gcqueue for for any cleared reference, remove * the associated value from the underlying set. */ private void processQueue() { ComparableSoftReference cr; while( (cr = (ComparableSoftReference) gcqueue.poll()) != null ) { map.remove(cr.getKey()); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ListSet.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ListSet.ja0000644000175000017500000001161110776226110033210 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.AbstractSet; import java.util.Iterator; import java.util.Collection; import java.io.Serializable; import org.jboss.util.NullArgumentException; /** * A thin wrapper around a List transforming it into a * modifiable Set. * * @version $Revision: 2800 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class ListSet extends AbstractSet implements Set, Cloneable, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 7333619218072079496L; /** The List which will be used for element storage. */ protected final List list; /** * Construct a ListSet. * * @param list The List which will be used for element storage. * * @throws IllegalArgumentException List is null or contains * duplicate entries. */ public ListSet(final List list) { if (list == null) throw new NullArgumentException("list"); // make sure there are no duplicates int size = list.size(); for (int i=0; iListSet using an ArrayList for backing. */ public ListSet() { this(new ArrayList()); } /** * Construct a ListSet using an ArrayList for backing * and populated with the given elements. * * @param elements The elements for the list. */ public ListSet(final Collection elements) { this(new ArrayList(elements)); } public List getList() { return list; } /** * Return the size of the set. * * @return The size of the set. */ public int size() { return list.size(); } /** * Return an iteration over the elements in the set. * * @return An iteration over the elements in the set. */ public Iterator iterator() { return list.iterator(); } /** * Add an element to the set. * * @param obj Element to add to the set. * @return True if the element was added. */ public boolean add(final Object obj) { boolean added = false; if (!list.contains(obj)) { added = list.add(obj); } return added; } /** * Returns true if this set contains no elements. * * @return true if this set contains no elements. */ public boolean isEmpty() { return list.isEmpty(); } /** * Returns true if this set contains the specified element. * * @param obj Element whose presence in this set is to be tested. * @return true if this set contains the specified element. */ public boolean contains(final Object obj) { return list.contains(obj); } /** * Removes the given element from this set if it is present. * * @param obj Object to be removed from this set, if present. * @return true if the set contained the specified element. */ public boolean remove(final Object obj) { return list.remove(obj); } /** * Removes all of the elements from this set. */ public void clear() { list.clear(); } /** * Returns a shallow copy of this ListSet instance. * * @return A shallow copy of this set. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CompoundIterator.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CompoundIt0000644000175000017500000000554610774222622033325 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * A compound iterator, which iterates over all of the elements in the * given iterators. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class CompoundIterator implements Iterator { /** The array of iterators to iterate over. */ protected final Iterator iters[]; /** The index of the current iterator. */ protected int index; /** * Construct a CompoundIterator over the given array of iterators. * * @param iters Array of iterators to iterate over. * * @throws IllegalArgumentException Array is null or empty. */ public CompoundIterator(final Iterator iters[]) { if (iters == null || iters.length == 0) throw new IllegalArgumentException("array is null or empty"); this.iters = iters; } /** * Check if there are more elements. * * @return True if there are more elements. */ public boolean hasNext() { for (; index < iters.length; index++) { if (iters[index] != null && iters[index].hasNext()) { return true; } } return false; } /** * Return the next element from the current iterator. * * @return The next element from the current iterator. * * @throws NoSuchElementException There are no more elements. */ public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } return iters[index].next(); } /** * Remove the current element from the current iterator. * * @throws IllegalStateException * @throws UnsupportedOperationException */ public void remove() { iters[index].remove(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ArrayIterator.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ArrayItera0000644000175000017500000000563510776226110033304 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.io.Serializable; import org.jboss.util.NullArgumentException; /** * An array iterator. * * @version $Revision: 2800 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class ArrayIterator implements Iterator, Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = -6604583440222021075L; /** Array to iterate over. */ protected final Object[] array; /** The current position in the array. */ protected int index; /** * Construct an ArrayIterator. * * @param array The array to iterate over. */ public ArrayIterator(final Object[] array) { if (array == null) throw new NullArgumentException("array"); this.array = array; } /** * Returns true if there are more elements in the iteration. * * @return True if there are more elements in the iteration. */ public boolean hasNext() { return index < array.length; } /** * Returns the next element in the iteration. * * @return The next element in the iteration. * * @throws NoSuchElementException The are no more elements available. */ public Object next() { if (! hasNext()) throw new NoSuchElementException(); return array[index++]; } /** * Unsupported. * * @throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException(); } /** * Returns a shallow cloned copy of this object. * * @return A shallow cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CompoundKey.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CompoundKe0000644000175000017500000000662110776226110033301 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.io.Serializable; import org.jboss.util.NullArgumentException; import org.jboss.util.Objects; import org.jboss.util.HashCode; import org.jboss.util.Strings; /** * An immutable compound key class. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class CompoundKey implements Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = -1181463173922935047L; /** The elements of the key */ private final Object elements[]; /** * Construct a CompoundKey. * * @param elements Elements of the key. */ public CompoundKey(final Object elements[]) { if (elements == null) throw new NullArgumentException("elements"); this.elements = elements; } /** * Construct a CompoundKey. * * @param a Element. * @param b Element. */ public CompoundKey(final Object a, final Object b) { this(new Object[] { a, b }); } /** * Construct a CompoundKey. * * @param a Element. * @param b Element. * @param c Element. */ public CompoundKey(final Object a, final Object b, final Object c) { this(new Object[] { a, b, c }); } /** * Test the equality of an object with this. * * @param obj Object to test equality with. * @return True if object is equal. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { CompoundKey key = (CompoundKey)obj; return Objects.equals(key.elements, elements); } return false; } /** * Get the hash code of this object. * * @return Hash code. */ public int hashCode() { return HashCode.generate(elements); } /** * Return a string representation of this object. * * @return A string representation of this object. */ public String toString() { return super.toString() + Strings.join(elements, "[", ",", "]"); } /** * Return a shallow cloned copy of this object. * * @return Shallow cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceValueHashMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceV0000644000175000017500000000530411103262257033253 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Map; import java.util.HashMap; import java.util.Comparator; import java.util.SortedMap; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @param the key type * @param the value type * @author Bill Burke * @author Adrian Brock * @author Ales Justin */ public abstract class ReferenceValueHashMap extends ReferenceValueMap { protected ReferenceValueHashMap() { } protected ReferenceValueHashMap(int initialCapacity) { super(initialCapacity); } protected ReferenceValueHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } protected ReferenceValueHashMap(Map t) { super(t); } protected Map> createMap(int initialCapacity, float loadFactor) { return new HashMap>(initialCapacity, loadFactor); } protected Map> createMap(int initialCapacity) { return new HashMap>(initialCapacity); } protected Map> createMap() { return new HashMap>(); } protected Map> createMap(Comparator kComparator) { throw new UnsupportedOperationException("Cannot create HashMap with such parameters."); } protected Map> createMap(SortedMap> kValueRefSortedMap) { throw new UnsupportedOperationException("Cannot create HashMap with such parameters."); } }././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ValueRef.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ValueRef.j0000644000175000017500000000255311103042470033164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.io.Serializable; import java.util.Map; /** * ValueRef. * * @param the key type * @param the value type */ public interface ValueRef extends Map.Entry { /** * Get underlying value. * * @return the value */ V get(); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazyMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazyMap.ja0000644000175000017500000000606610774222622033210 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.io.Serializable; /** * LazyMap. * It's serializable if the elements are serializable. * * @param the key type * @param the value type * @author Adrian Brock * @version $Revision: 2787 $ */ public class LazyMap implements Map, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The delegate map */ private Map delegate = Collections.emptyMap(); /** * Create the map implementation * * @return the map */ private Map createImplementation() { if (delegate instanceof HashMap == false) return new HashMap(delegate); return delegate; } public void clear() { delegate = Collections.emptyMap(); } public boolean containsKey(Object key) { return delegate.containsKey(key); } public boolean containsValue(Object value) { return delegate.containsValue(value); } public Set> entrySet() { return delegate.entrySet(); } public V get(Object key) { return delegate.get(key); } public boolean isEmpty() { return delegate.isEmpty(); } public Set keySet() { return delegate.keySet(); } public V put(K key, V value) { if (delegate.isEmpty()) { delegate = Collections.singletonMap(key, value); return null; } else { delegate = createImplementation(); return delegate.put(key, value); } } public void putAll(Map t) { delegate = createImplementation(); delegate.putAll(t); } public V remove(Object key) { delegate = createImplementation(); return delegate.remove(key); } public int size() { return delegate.size(); } public Collection values() { return delegate.values(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/FullCollectionException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/FullCollec0000644000175000017500000000342310776226110033256 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; /** * Thrown to indicate that an operation can not be performed on a full * collection. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class FullCollectionException extends CollectionException { /** The serialVersionUID */ private static final long serialVersionUID = -1795773071357559465L; /** * Construct a FullCollectionException with the specified * detail message. * * @param msg Detail message. */ public FullCollectionException(String msg) { super(msg); } /** * Construct a FullCollectionException with no detail. */ public FullCollectionException() { super(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakClassCache.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakClassC0000644000175000017500000000717210774222622033221 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; /** * A weak class cache that instantiates does not a hold a * strong reference to either the classloader or class.

* * It creates the class specific data in two stages * to avoid recursion.

* * instantiate - creates the data
* generate - fills in the details * * @author Adrian Brock */ @SuppressWarnings("unchecked") public abstract class WeakClassCache { /** The cache */ protected Map cache = new WeakHashMap(); /** * Get the information for a class * * @param clazz the class * @return the info */ public Object get(Class clazz) { if (clazz == null) throw new IllegalArgumentException("Null class"); Map classLoaderCache = getClassLoaderCache(clazz.getClassLoader()); WeakReference weak = (WeakReference) classLoaderCache.get(clazz.getName()); if (weak != null) { Object result = weak.get(); if (result != null) return result; } Object result = instantiate(clazz); weak = new WeakReference(result); classLoaderCache.put(clazz.getName(), weak); generate(clazz, result); return result; } /** * Get the information for a class * * @param name the name * @param cl the classloader * @return the info * @throws ClassNotFoundException when the class cannot be found */ public Object get(String name, ClassLoader cl) throws ClassNotFoundException { if (name == null) throw new IllegalArgumentException("Null name"); if (cl == null) throw new IllegalArgumentException("Null classloader"); Class clazz = cl.loadClass(name); return get(clazz); } /** * Instantiate for a class * * @param clazz the class * @return the result */ protected abstract Object instantiate(Class clazz); /** * Fill in the result * * @param clazz the class * @param result the result */ protected abstract void generate(Class clazz, Object result); /** * Get the cache for the classloader * * @param cl the classloader * @return the map */ protected Map getClassLoaderCache(ClassLoader cl) { synchronized (cache) { Map result = (Map) cache.get(cl); if (result == null) { result = CollectionsFactory.createConcurrentReaderMap(); cache.put(cl, result); } return result; } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CachedList.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CachedList0000644000175000017500000001126010774222622033235 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.List; import java.util.LinkedList; import java.util.AbstractList; import java.lang.ref.ReferenceQueue; import org.jboss.util.SoftObject; import org.jboss.util.Objects; /** * A wrapper around a List which translates added objects * into {@link SoftObject} references, allowing the VM to garbage collect * objects in the collection when memory is low. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class CachedList extends AbstractList { /** Reference queue. */ protected final ReferenceQueue queue = new ReferenceQueue(); /** Wrapped list. */ protected final List list; /** * Construct a CachedList. * * @param list List to wrap. */ public CachedList(final List list) { this.list = list; } /** * Construct a CachedList using a LinkedList for * storage. */ public CachedList() { this(new LinkedList()); } /** * Dereference the object at the given index. */ private Object getObject(final int index) { Object obj = list.get(index); return Objects.deref(obj); } /** * Returns the element at the specified position in this list. * * @param index Index of element to return. * @return The element at the specified position. */ public Object get(final int index) { maintain(); return getObject(index); } /** * Return the size of the list. * * @return The number of elements in the list. */ public int size() { maintain(); return list.size(); } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index Index of element to replace. * @param obj Element to be stored at the specified postion. * @return The previous element at the given index. */ public Object set(final int index, final Object obj) { maintain(); SoftObject soft = SoftObject.create(obj, queue); soft = (SoftObject)list.set(index, soft); return Objects.deref(soft); } /** * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). * * @param index Index at which the specified element is to be inserted. * @param obj Element to be inserted. */ public void add(final int index, final Object obj) { maintain(); SoftObject soft = SoftObject.create(obj, queue); list.add(index, soft); } /** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the list. * * @param index The index of the element to remove. * @return The element previously at the specified position. */ public Object remove(final int index) { maintain(); Object obj = list.remove(index); return Objects.deref(obj); } /** * Maintains the collection by removing garbage collected objects. */ private void maintain() { SoftObject obj; int count = 0; while ((obj = (SoftObject)queue.poll()) != null) { count++; list.remove(obj); } if (count != 0) { // some temporary debugging fluff System.err.println("vm reclaimed " + count + " objects"); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakSet.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakSet.ja0000644000175000017500000001453210774222622033173 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.AbstractSet; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import org.jboss.util.NullArgumentException; import org.jboss.util.WeakObject; /** * A Set implementation with weak elements. An entry in * a WeakSet will automatically be removed when the element is no * longer in ordinary use. More precisely, the presence of an given element * will not prevent the element from being discarded by the garbage collector, * that is, made finalizable, finalized, and then reclaimed. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class WeakSet extends AbstractSet implements Set { /** The reference queue used to get object removal notifications. */ protected final ReferenceQueue queue = new ReferenceQueue(); /** The Set which will be used for element storage. */ protected final Set set; /** * Construct a WeakSet. Any elements in the given set will be * wrapped in {@link WeakObject} references. * * @param set The Set which will be used for element storage. * * @throws NullArgumentException Set is null. */ public WeakSet(final Set set) { if (set == null) throw new NullArgumentException("set"); // reset any elements to weak objects if (set.size() != 0) { Object elements[] = set.toArray(); set.clear(); for (int i=0; iWeakSet based on a HashSet. */ public WeakSet() { this(new HashSet()); } /** * Maintain the elements in the set. Removes objects from the set that * have been reclaimed due to GC. */ protected final void maintain() { WeakObject weak; while ((weak = (WeakObject)queue.poll()) != null) { set.remove(weak); } } /** * Return the size of the set. * * @return The size of the set. */ public int size() { maintain(); return set.size(); } /** * Return an iteration over the elements in the set. * * @return An iteration over the elements in the set. */ public Iterator iterator() { return new Iterator() { /** The set's iterator */ Iterator iter = set.iterator(); /** JBCOMMON-24, handle null values and multiple invocations of hasNext() */ Object UNKNOWN = new Object(); /** The next available object. */ Object next = UNKNOWN; public boolean hasNext() { if (next != UNKNOWN) { return true; } while (iter.hasNext()) { WeakObject weak = (WeakObject)iter.next(); Object obj = null; if (weak != null && (obj = weak.get()) == null) { // object has been reclaimed by the GC continue; } next = obj; return true; } return false; } public Object next() { if ((next == UNKNOWN) && !hasNext()) { throw new NoSuchElementException(); } Object obj = next; next = UNKNOWN; return obj; } public void remove() { iter.remove(); } }; } /** * Add an element to the set. * * @param obj Element to add to the set. * @return True if the element was added. */ public boolean add(final Object obj) { maintain(); return set.add(WeakObject.create(obj, queue)); } /** * Returns true if this set contains no elements. * * @return true if this set contains no elements. */ public boolean isEmpty() { maintain(); return set.isEmpty(); } /** * Returns true if this set contains the specified element. * * @param obj Element whose presence in this set is to be tested. * @return true if this set contains the specified element. */ public boolean contains(final Object obj) { maintain(); return set.contains(WeakObject.create(obj)); } /** * Removes the given element from this set if it is present. * * @param obj Object to be removed from this set, if present. * @return true if the set contained the specified element. */ public boolean remove(final Object obj) { maintain(); return set.remove(WeakObject.create(obj)); } /** * Removes all of the elements from this set. */ public void clear() { set.clear(); } /** * Returns a shallow copy of this WeakSet instance: the elements * themselves are not cloned. * * @return A shallow copy of this set. */ public Object clone() { maintain(); try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueRef.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueR0000644000175000017500000000464511103262257033270 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; /** * Soft value ref. * * @author Bill Burke * @author Adrian Brock * @author Ales Justin * @param the key type * @param the value type */ class SoftValueRef extends SoftReference implements ValueRef { /** * The key */ public K key; /** * Safely create a new SoftValueRef * * @param the key type * @param the value type * @param key the key * @param val the value * @param q the reference queue * @return the reference or null if the value is null */ static SoftValueRef create(K key, V val, ReferenceQueue q) { if (val == null) return null; else return new SoftValueRef(key, val, q); } /** * Create a new SoftValueRef. * * @param key the key * @param val the value * @param q the reference queue */ private SoftValueRef(K key, V val, ReferenceQueue q) { super(val, q); this.key = key; } public K getKey() { return key; } public V getValue() { return get(); } public V setValue(V value) { throw new UnsupportedOperationException("setValue"); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CollectionsFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Collection0000644000175000017500000000574111042105117033320 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** * Collections factory. * * @author Adrian Brock * @version $Revision: 2887 $ */ public class CollectionsFactory { /** * Defines the map implementation * * @param the key type * @param the value type * @return the map */ public static final Map createLazyMap() { return new LazyMap(); } /** * Defines the list implementation * * @param the type * @return the list */ public static final List createLazyList() { return new LazyList(); } /** * Defines the set implementation * * @param the type * @return the set */ public static final Set createLazySet() { return new LazySet(); } /** * Defines the concurrent map implementation * * @param the key type * @param the value type * @return the map */ public static final Map createConcurrentReaderMap() { return new ConcurrentHashMap(); } /** * Defines the concurrent list implementation * * @param the type * @return the list */ public static final List createCopyOnWriteList() { return new CopyOnWriteArrayList(); } /** * Defines the concurrent set implementation * * @param the type * @return the set */ public static final Set createCopyOnWriteSet() { return new CopyOnWriteArraySet(); } /** * Defines the concurrent set implementation * * @param the type * @return the set */ public static final Set createConcurrentSet() { return new ConcurrentSet(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakTypeCache.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakTypeCa0000644000175000017500000002024411015577255033235 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Map; import java.util.WeakHashMap; /** * A weak class cache that instantiates does not a hold a * strong reference to either the classloader or class.

* * It creates the class specific data in two stages * to avoid recursion.

* * instantiate - creates the data
* generate - fills in the details * * @param the cached type * @author Scott.Stark@jboss.org * @author Adrian Brock */ public abstract class WeakTypeCache { /** The cache */ private Map> cache = new WeakHashMap>(); /** * Get the information for a type * * @param type the type * @return the info */ @SuppressWarnings({"unchecked", "cast"}) public T get(Type type) { if (type == null) throw new IllegalArgumentException("Null type"); if (type instanceof ParameterizedType) return getParameterizedType((ParameterizedType) type); else if (type instanceof Class) return getClass((Class) type); else if (type instanceof TypeVariable) // TODO Figure out why we need this cast with the Sun compiler? return (T) getTypeVariable((TypeVariable) type); else if (type instanceof GenericArrayType) return getGenericArrayType((GenericArrayType) type); else if (type instanceof WildcardType) return getWildcardType((WildcardType) type); else throw new UnsupportedOperationException("Unknown type: " + type + " class=" + type.getClass()); } /** * Get the information for a class * * @param name the name * @param cl the classloader * @return the info * @throws ClassNotFoundException when the class cannot be found */ public T get(String name, ClassLoader cl) throws ClassNotFoundException { if (name == null) throw new IllegalArgumentException("Null name"); if (cl == null) throw new IllegalArgumentException("Null classloader"); Class clazz = cl.loadClass(name); return get(clazz); } /** * Instantiate for a class * * @param clazz the class * @return the result */ protected abstract T instantiate(Class clazz); /** * Fill in the result * * @param clazz the class * @param result the result */ protected abstract void generate(Class clazz, T result); /** * Instantiate for a parameterized type * * @param type the parameterized type * @return the result */ protected abstract T instantiate(ParameterizedType type); /** * Fill in the result * * @param type the parameterized type * @param result the result */ protected abstract void generate(ParameterizedType type, T result); /** * Get the information for a parameterized type * * @param type the parameterized type * @return the info */ protected T getParameterizedType(ParameterizedType type) { // First check if we already have it T result = peek(type); if (result != null) return result; // Instantiate result = instantiate(type); // Put the perlimanary result into the cache put(type, result); // Generate the details generate(type, result); return result; } /** * Get the information for a wildcard type * * @param type the paremeterized type * @return the info */ protected T getWildcardType(WildcardType type) { // TODO JBMICROCONT-131 improve this return get(type.getUpperBounds()[0]); } /** * Get the information for a type variable * * @param the declaration * @param type the type variable * @return the info */ protected T getTypeVariable(TypeVariable type) { // TODO JBMICROCONT-131 improve this return get(type.getBounds()[0]); } /** * Get the information for an array type * * @param type the array type * @return the info */ protected T getGenericArrayType(GenericArrayType type) { // TODO JBMICROCONT-131 this needs implementing properly return get(Object[].class); } /** * Peek into the cache * * @param type the type * @return the value */ protected T peek(ParameterizedType type) { Class rawType = (Class) type.getRawType(); ClassLoader cl = SecurityActions.getClassLoader(rawType); Map classLoaderCache = getClassLoaderCache(cl); synchronized (classLoaderCache) { return classLoaderCache.get(type.toString()); } } /** * Put a result into the cache * * @param type the type * @param result the value */ protected void put(ParameterizedType type, T result) { Class rawType = (Class) type.getRawType(); ClassLoader cl = SecurityActions.getClassLoader(rawType); Map classLoaderCache = getClassLoaderCache(cl); synchronized (classLoaderCache) { // TODO JBMICROCONT-131 something better than toString()? classLoaderCache.put(type.toString(), result); } } /** * Get the information for a class * * @param clazz the class * @return the info */ protected T getClass(Class clazz) { // First check if we already have it T result = peek(clazz); if (result != null) return result; // Instantiate result = instantiate(clazz); // Put the preliminary result into the cache put(clazz, result); // Generate the details generate(clazz, result); return result; } /** * Peek into the cache * * @param clazz the class * @return the value */ protected T peek(Class clazz) { ClassLoader cl = SecurityActions.getClassLoader(clazz); Map classLoaderCache = getClassLoaderCache(cl); synchronized (classLoaderCache) { return classLoaderCache.get(clazz.getName()); } } /** * Put a result into the cache * * @param clazz the class * @param result the value */ protected void put(Class clazz, T result) { ClassLoader cl = SecurityActions.getClassLoader(clazz); Map classLoaderCache = getClassLoaderCache(cl); synchronized (classLoaderCache) { classLoaderCache.put(clazz.getName(), result); } } /** * Get the cache for the classloader * * @param cl the classloader * @return the map */ protected Map getClassLoaderCache(ClassLoader cl) { synchronized (cache) { Map result = cache.get(cl); if (result == null) { result = new WeakValueHashMap(); cache.put(cl, result); } return result; } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceValueTreeMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceV0000644000175000017500000000467311103262257033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @param the key type * @param the value type * @author Ales Justin */ public abstract class ReferenceValueTreeMap extends ReferenceValueMap { protected ReferenceValueTreeMap() { } protected ReferenceValueTreeMap(Comparator comparator) { super(comparator); } protected ReferenceValueTreeMap(SortedMap> sorted) { super(sorted); } protected Map> createMap() { return new TreeMap>(); } protected Map> createMap(Comparator comparator) { return new TreeMap>(comparator); } protected Map> createMap(SortedMap> map) { return new TreeMap>(map); } protected Map> createMap(int initialCapacity) { throw new UnsupportedOperationException("Cannot create TreeMap with such parameters."); } protected Map> createMap(int initialCapacity, float loadFactor) { throw new UnsupportedOperationException("Cannot create TreeMap with such parameters."); } }././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueHashMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueH0000644000175000017500000000666011103262257033255 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.Map; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @author Bill Burke * @author Ales Justin */ public class SoftValueHashMap extends ReferenceValueHashMap { /** * Constructs a new, empty SoftValueHashMap with the given * initial capacity and the given load factor. * * @param initialCapacity The initial capacity of the * SoftValueHashMap * * @param loadFactor The load factor of the SoftValueHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero, or if the load factor is * nonpositive */ public SoftValueHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructs a new, empty SoftValueHashMap with the given * initial capacity and the default load factor, which is * 0.75. * * @param initialCapacity The initial capacity of the * SoftValueHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero */ public SoftValueHashMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty SoftValueHashMap with the default * initial capacity and the default load factor, which is * 0.75. */ public SoftValueHashMap() { } /** * Constructs a new SoftValueHashMap with the same mappings as the * specified Map. The SoftValueHashMap is created with an * initial capacity of twice the number of mappings in the specified map * or 11 (whichever is greater), and a default load factor, which is * 0.75. * * @param t the map whose mappings are to be placed in this map. * @since 1.3 */ public SoftValueHashMap(Map t) { super(t); } protected ValueRef create(K key, V value, ReferenceQueue q) { return SoftValueRef.create(key, value, q); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazyList.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazyList.j0000644000175000017500000001044710774222622033243 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.io.Serializable; /** * LazyList. * It's serializable if the elements are serializable. * * @param the collection type * @author Adrian Brock * @version $Revision: 2787 $ */ public class LazyList implements List, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The delegate list */ private List delegate = Collections.emptyList(); /** * Create the list implementation * * @return the list */ private List createImplementation() { if (delegate instanceof ArrayList == false) return new ArrayList(delegate); return delegate; } public void add(int index, T element) { delegate = createImplementation(); delegate.add(index, element); } public boolean add(T o) { if (delegate.isEmpty()) { delegate = Collections.singletonList(o); return true; } else { delegate = createImplementation(); return delegate.add(o); } } public boolean addAll(Collection c) { delegate = createImplementation(); return delegate.addAll(c); } public boolean addAll(int index, Collection c) { delegate = createImplementation(); return delegate.addAll(index, c); } public void clear() { delegate = Collections.emptyList(); } public boolean contains(Object o) { return delegate.contains(o); } public boolean containsAll(Collection c) { return delegate.containsAll(c); } public T get(int index) { return delegate.get(index); } public int indexOf(Object o) { return delegate.indexOf(o); } public boolean isEmpty() { return delegate.isEmpty(); } public Iterator iterator() { return delegate.iterator(); } public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } public ListIterator listIterator() { return delegate.listIterator(); } public ListIterator listIterator(int index) { return delegate.listIterator(index); } public T remove(int index) { delegate = createImplementation(); return delegate.remove(index); } public boolean remove(Object o) { delegate = createImplementation(); return delegate.remove(o); } public boolean removeAll(Collection c) { delegate = createImplementation(); return delegate.removeAll(c); } public boolean retainAll(Collection c) { delegate = createImplementation(); return delegate.retainAll(c); } public T set(int index, T element) { delegate = createImplementation(); return delegate.set(index, element); } public int size() { return delegate.size(); } public List subList(int fromIndex, int toIndex) { return delegate.subList(fromIndex, toIndex); } public Object[] toArray() { return delegate.toArray(); } public U[] toArray(U[] a) { return delegate.toArray(a); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/CollectionsUtil.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Collection0000644000175000017500000000307310774222622033330 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; /** * CollectionsUtil. * * @author Adrian Brock * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class CollectionsUtil { /** * Create a list from an enumeration * * @param e the enumeration * @return the list */ public static List list(Enumeration e) { ArrayList result = new ArrayList(); while (e.hasMoreElements()) result.add(e.nextElement()); return result; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Iterators.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Iterators.0000644000175000017500000002051610774222622033270 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Iterator; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Map; import java.util.HashMap; import org.jboss.util.Null; /** * A collection of Iterator and Enumeration * utilities. * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public final class Iterators { ///////////////////////////////////////////////////////////////////////// // Enumeration/Iterator Conversion // ///////////////////////////////////////////////////////////////////////// /** * An Enumeration to Iterator wrapper. */ private static final class Enum2Iterator implements Iterator { private final Enumeration enumeration; public Enum2Iterator(final Enumeration enumeration) { this.enumeration = enumeration; } public boolean hasNext() { return enumeration.hasMoreElements(); } public Object next() { return enumeration.nextElement(); } public void remove() { throw new UnsupportedOperationException("Enumerations are immutable"); } } /** * Return an Iterator wrapper for the given Enumeration * * @param enumeration Enumeration to wrap * @return Enumeration wrapped as an Iterator */ public static Iterator forEnumeration(final Enumeration enumeration) { return new Enum2Iterator(enumeration); } /** * An Iterator to Enumeration wrapper class. */ private static final class Iter2Enumeration implements Enumeration { private final Iterator iter; public Iter2Enumeration(final Iterator iter) { this.iter = iter; } public boolean hasMoreElements() { return iter.hasNext(); } public Object nextElement() { return iter.next(); } } /** * Return an Enumeration for the given Iterator. * * @param iter Iterator to wrap. * @return Enumeration wrapper. */ public static Enumeration toEnumeration(final Iterator iter) { return new Iter2Enumeration(iter); } ///////////////////////////////////////////////////////////////////////// // Iterator Wrappers // ///////////////////////////////////////////////////////////////////////// /** * Wraps an Iterator making it immutable, by disabling calls to * remove() */ private static final class ImmutableIterator implements Iterator { private final Iterator iter; public ImmutableIterator(final Iterator iter) { this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public Object next() { return iter.next(); } public void remove() { throw new UnsupportedOperationException("iterator is immutable"); } } /** * Make an Iterator immutable * * @param iter Iterator to make immutable * @return Imutable iterator */ public static Iterator makeImmutable(final Iterator iter) { return new ImmutableIterator(iter); } /** * Wraps an Iterator making it synchronized. */ private static final class SyncIterator implements Iterator { private final Iterator iter; public SyncIterator(final Iterator iter) { this.iter = iter; } public synchronized boolean hasNext() { return iter.hasNext(); } public synchronized Object next() { return iter.next(); } public synchronized void remove() { iter.remove(); } } /** * Returns a synchronized version of the given Iterator. * * @param iter Iterator to synchronize. * @return Synchronized Iterator. */ public static Iterator makeSynchronized(final Iterator iter) { return new SyncIterator(iter); } /** * Wraps an Enumeration making it synchronized. */ private static final class SyncEnumeration implements Enumeration { private final Enumeration enumeration; public SyncEnumeration(final Enumeration enumeration) { this.enumeration = enumeration; } public synchronized boolean hasMoreElements() { return enumeration.hasMoreElements(); } public synchronized Object nextElement() { return enumeration.nextElement(); } } /** * Returns a synchronized version of the given Enumeration. * * @param enumeration Enumeration to synchronize. * @return Synchronized Enumeration. */ public static Enumeration makeSynchronized(final Enumeration enumeration) { return new SyncEnumeration(enumeration); } ///////////////////////////////////////////////////////////////////////// // Empty Iterator // ///////////////////////////////////////////////////////////////////////// /** An empty Iterator */ public static final Iterator EMPTY_ITERATOR = new EmptyIterator(); /** * An empty Iterator */ private static final class EmptyIterator implements Iterator { public boolean hasNext() { return false; } public Object next() { throw new NoSuchElementException("no more elements"); } public void remove() { throw new IllegalStateException("no more elements"); } } ///////////////////////////////////////////////////////////////////////// // Misc Methods // ///////////////////////////////////////////////////////////////////////// /** * Returns an Iterator containing the union of all of the elements * in the given iterator array. * * @param iters Array of iterators. * @return Iterator containing the union. */ public static Iterator union(final Iterator iters[]) { Map map = new HashMap(); for (int i=0; i < iters.length; i++) { if (iters[i] != null) { while (iters[i].hasNext()) { Object obj = iters[i].next(); if (!map.containsKey(obj)) { map.put(obj, Null.VALUE); } } } } return map.keySet().iterator(); } /** * Return a delimited string representation of all of the elements * in the given Iterator. * * @param iter Iterator to convert to string. * @param delim Elemement delimiter. * @return Delimited string value. */ public static String toString(final Iterator iter, final String delim) { StringBuffer buff = new StringBuffer(); while (iter.hasNext()) { buff.append(iter.next()); if (iter.hasNext()) { buff.append(delim); } } return buff.toString(); } /** * Return a comma delimited string representation of all of the elements * in the given Iterator. * * @param iter Iterator to convert to string. * @return Delimited string value. */ public static String toString(final Iterator iter) { return toString(iter, ","); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueRef.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueR0000644000175000017500000000477211103262257033245 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; /** * Weak value ref. * * @author Bill Burke * @author Adrian Brock * @author Ales Justin * @param the key type * @param the value type */ class WeakValueRef extends WeakReference implements ValueRef { /** * The key */ public K key; /** * Safely create a new WeakValueRef * * @param the key type * @param the value type * @param key the key * @param val the value * @param q the reference queue * @return the reference or null if the value is null */ static WeakValueRef create(K key, V val, ReferenceQueue q) { if (val == null) return null; else return new WeakValueRef(key, val, q); } /** * Create a new WeakValueRef. * * @param key the key * @param val the value * @param q the reference queue */ private WeakValueRef(K key, V val, ReferenceQueue q) { super(val, q); this.key = key; } public K getKey() { return key; } public V getValue() { return get(); } public V setValue(V value) { throw new UnsupportedOperationException("setValue"); } }././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/package.ht0000644000175000017500000000155210470642610033236 0ustar twernertwerner

Extentions to the Java Collections framework.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ListQueue.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ListQueue.0000644000175000017500000001117310774222622033233 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import org.jboss.util.NullArgumentException; /** * A ListQueue implements a first-in, first-out container using a List as * a data structure. * * @param the element type * @version $Revision: 2787 $ * @author Jason Dillon */ public class ListQueue extends AbstractQueue { /** List container */ protected final List list; /** * Construct a new constrained ListQueue. * * @param list The list which will be used to store queued objects. * @param maxSize The maximum size of the queue. * * @exception IllegalArgumentException List is null. */ public ListQueue(final List list, final int maxSize) { super(maxSize); if (list == null) throw new NullArgumentException("list"); this.list = list; } /** * Construct a new constrained ListQueue using a * LinkedList for a data-structure. * * @param maxSize The maximum size of the queue. */ public ListQueue(final int maxSize) { super(maxSize); this.list = new LinkedList(); } /** * Construct a new unconstrained ListQueue. * * @param list The list which will be used to store queued objects. * * @exception IllegalArgumentException List is null */ public ListQueue(final List list) { this(list, UNLIMITED_MAXIMUM_SIZE); } /** * Construct a new unconstrained ListQueue using a * LinkedList for a data-structure. */ public ListQueue() { this(new LinkedList(), UNLIMITED_MAXIMUM_SIZE); } /** * Appends the given element to the end of this list. * * @param obj Object to append. */ protected boolean addLast(final E obj) { return list.add(obj); } /** * Remove the first object in the queue. * * @return First object in the queue. */ protected E removeFirst() { return list.remove(0); } /** * Get the size of the queue. * * @return The number of elements in the queue. */ public int size() { return list.size(); } /** * Returns an iterator over the elements in this list in proper sequence. * * @return An iterator over the elements in this list in proper sequence. */ public Iterator iterator() { return list.iterator(); } /** * Get the object at the front of the queue. * * @return Object at the front of the queue. * * @exception EmptyCollectionException The queue is empty. */ public E getFront() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(); return list.get(0); } /** * Get the object at the back of the queue. * * @return Object at the back of the queue. * * @exception EmptyCollectionException The queue is empty. */ public E getBack() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(); return list.get(list.size() - 1); } /** * Returns an iterator over the elements in this list in reverse sequence. * * @return An iterator over the elements in this list in reverse sequence. */ public Iterator reverseIterator() { return new ReverseListIterator(list); } /** * Return a String representation of this queue. * * @return String */ public String toString() { return list.toString(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Queue.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Queue.java0000644000175000017500000000601710774222622033242 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Collection; /** * An iterface used to implement a first-in, first-out container. * * @param the element type * @version $Revision: 2787 $ * @author Jason Dillon */ public interface Queue extends Collection { /** Unlimited maximum queue size identifier. */ int UNLIMITED_MAXIMUM_SIZE = -1; /** * Get the maximum size of the queue. * * @return Maximum pool size or {@link #UNLIMITED_MAXIMUM_SIZE}. */ int getMaximumSize(); /** * Set the maximum size of the queue. * * @param size New maximim pool size or {@link #UNLIMITED_MAXIMUM_SIZE}. * * @exception IllegalArgumentException Illegal size. */ void setMaximumSize(int size) throws IllegalArgumentException; /** * Check if the queue is full. * * @return True if the queue is full. */ boolean isFull(); /** * Check if the queue is empty. * * @return True if the queue is empty. */ boolean isEmpty(); /** * Enqueue an object onto the queue. * * @param obj Object to enqueue. * @return True if collection was modified. * * @exception FullCollectionException The queue is full. */ boolean add(E obj) throws FullCollectionException; /** * Dequeue an object from the queue. * * @return Dequeued object. * * @exception EmptyCollectionException The queue is empty. */ E remove() throws EmptyCollectionException; /** * Get the object at the front of the queue. * * @return Object at the front of the queue. * * @exception EmptyCollectionException The queue is empty. */ E getFront() throws EmptyCollectionException; /** * Get the object at the back of the queue. * * @return Object at the back of the queue. * * @exception EmptyCollectionException The queue is empty. */ E getBack() throws EmptyCollectionException; } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueTreeMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/SoftValueT0000644000175000017500000000336011103262257033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.Comparator; import java.util.SortedMap; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @author Ales Justin */ public class SoftValueTreeMap extends ReferenceValueTreeMap { public SoftValueTreeMap() { } public SoftValueTreeMap(Comparator comparator) { super(comparator); } public SoftValueTreeMap(SortedMap> sorted) { super(sorted); } protected ValueRef create(K key, V value, ReferenceQueue q) { return SoftValueRef.create(key, value, q); } }././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueHashMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/WeakValueH0000644000175000017500000000705011103262257033223 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.Map; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @param the key type * @param the value type * @author Bill Burke * @author Adrian Brock * @author Ales Justin */ public class WeakValueHashMap extends ReferenceValueHashMap { /** * Constructs a new, empty WeakValueHashMap with the given * initial capacity and the given load factor. * * @param initialCapacity The initial capacity of the * WeakValueHashMap * * @param loadFactor The load factor of the WeakValueHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero, or if the load factor is * nonpositive */ public WeakValueHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructs a new, empty WeakValueHashMap with the given * initial capacity and the default load factor, which is * 0.75. * * @param initialCapacity The initial capacity of the * WeakValueHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero */ public WeakValueHashMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty WeakValueHashMap with the default * initial capacity and the default load factor, which is * 0.75. */ public WeakValueHashMap() { } /** * Constructs a new WeakValueHashMap with the same mappings as the * specified Map. The WeakValueHashMap is created with an * initial capacity of twice the number of mappings in the specified map * or 11 (whichever is greater), and a default load factor, which is * 0.75. * * @param t the map whose mappings are to be placed in this map. * @since 1.3 */ public WeakValueHashMap(Map t) { super(t); } protected ValueRef create(K key, V value, ReferenceQueue q) { return WeakValueRef.create(key, value, q); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceValueMap.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ReferenceV0000644000175000017500000001436711103262257033264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.lang.ref.ReferenceQueue; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * This Map will remove entries when the value in the map has been * cleaned from garbage collection * * @param the key type * @param the value type * @author Bill Burke * @author Adrian Brock * @author Ales Justin */ public abstract class ReferenceValueMap extends AbstractMap { /** Hash table mapping keys to ref values */ private Map> map; /** Reference queue for cleared RefKeys */ private ReferenceQueue queue = new ReferenceQueue(); protected ReferenceValueMap() { map = createMap(); } protected ReferenceValueMap(int initialCapacity) { map = createMap(initialCapacity); } protected ReferenceValueMap(int initialCapacity, float loadFactor) { map = createMap(initialCapacity, loadFactor); } protected ReferenceValueMap(Map t) { this(Math.max(2*t.size(), 11), 0.75f); putAll(t); } protected ReferenceValueMap(Comparator comparator) { map = createMap(comparator); } protected ReferenceValueMap(SortedMap> sorted) { map = createMap(sorted); } /** * Create map. * * @return new map instance */ protected abstract Map> createMap(); /** * Create map. * * @param initialCapacity the initial capacity * @return new map instance */ protected abstract Map> createMap(int initialCapacity); /** * Create map. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @return new map instance */ protected abstract Map> createMap(int initialCapacity, float loadFactor); /** * Create map. * * @param comparator the comparator * @return new map instance */ protected abstract Map> createMap(Comparator comparator); /** * Create map. * * @param map the sorted map * @return new map instance */ protected abstract Map> createMap(SortedMap> map); @Override public int size() { processQueue(); return map.size(); } @Override public boolean containsKey(Object key) { processQueue(); return map.containsKey(key); } @Override public V get(Object key) { processQueue(); ValueRef ref = map.get(key); if (ref != null) return ref.get(); return null; } @Override public V put(K key, V value) { processQueue(); ValueRef ref = create(key, value, queue); ValueRef result = map.put(key, ref); if (result != null) return result.get(); return null; } @Override public V remove(Object key) { processQueue(); ValueRef result = map.remove(key); if (result != null) return result.get(); return null; } @Override public Set> entrySet() { processQueue(); return new EntrySet(); } @Override public void clear() { processQueue(); map.clear(); } /** * Remove all entries whose values have been discarded. */ @SuppressWarnings("unchecked") private void processQueue() { ValueRef ref = (ValueRef) queue.poll(); while (ref != null) { // only remove if it is the *exact* same WeakValueRef if (ref == map.get(ref.getKey())) map.remove(ref.getKey()); ref = (ValueRef) queue.poll(); } } /** * EntrySet. */ private class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntrySetIterator(map.entrySet().iterator()); } @Override public int size() { return ReferenceValueMap.this.size(); } } /** * EntrySet iterator */ private class EntrySetIterator implements Iterator> { /** The delegate */ private Iterator>> delegate; /** * Create a new EntrySetIterator. * * @param delegate the delegate */ public EntrySetIterator(Iterator>> delegate) { this.delegate = delegate; } public boolean hasNext() { return delegate.hasNext(); } public Entry next() { Entry> next = delegate.next(); return next.getValue(); } public void remove() { throw new UnsupportedOperationException("remove"); } } /** * Create new value ref instance. * * @param key the key * @param value the value * @param q the ref queue * @return new value ref instance */ protected abstract ValueRef create(K key, V value, ReferenceQueue q); }././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazySet.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/LazySet.ja0000644000175000017500000000626310774222622033225 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.io.Serializable; /** * LazySet. * It's serializable if the elements are serializable. * * @param the element type * @author Adrian Brock * @version $Revision: 2787 $ */ public class LazySet implements Set, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The delegate set */ private Set delegate = Collections.emptySet(); /** * Create the set implementation * * @return the set */ private Set createImplementation() { if (delegate instanceof HashSet == false) return new HashSet(delegate); return delegate; } public boolean add(T o) { if (delegate.isEmpty()) { delegate = Collections.singleton(o); return true; } else { delegate = createImplementation(); return delegate.add(o); } } public boolean addAll(Collection c) { delegate = createImplementation(); return delegate.addAll(c); } public void clear() { delegate = Collections.emptySet(); } public boolean contains(Object o) { return delegate.contains(o); } public boolean containsAll(Collection c) { return delegate.containsAll(c); } public boolean isEmpty() { return delegate.isEmpty(); } public Iterator iterator() { return delegate.iterator(); } public boolean remove(Object o) { delegate = createImplementation(); return delegate.remove(o); } public boolean removeAll(Collection c) { delegate = createImplementation(); return delegate.removeAll(c); } public boolean retainAll(Collection c) { delegate = createImplementation(); return delegate.retainAll(c); } public int size() { return delegate.size(); } public Object[] toArray() { return delegate.toArray(); } public U[] toArray(U[] a) { return delegate.toArray(a); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/ConcurrentSet.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/collection/Concurrent0000644000175000017500000001370311042105117033344 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.collection; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; /** * ConcurrentSet based on top of ConcurrenthashMap. * It's serializable if the elements are serializable. * * @param the element type * @author Ales Justin */ public class ConcurrentSet extends AbstractSet implements Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The delegate set */ private ConcurrentHashMap map; /** The dummy object */ private static final Object PRESENT = new Object(); /** * Constructs a new, empty set; the backing ConcurrentHashMap instance has * default initial capacity (16) and load factor (0.75). */ public ConcurrentSet() { map = new ConcurrentHashMap(); } /** * Constructs a new set containing the elements in the specified * collection. The ConcurrentHashMap is created with default load factor * (0.75) and an initial capacity sufficient to contain the elements in * the specified collection. * * @param c the collection whose elements are to be placed into this set. * @throws NullPointerException if the specified collection is null. */ public ConcurrentSet(Collection c) { map = new ConcurrentHashMap(Math.max((int)(c.size() / .75f) + 1, 16)); addAll(c); } /** * Constructs a new, empty set; the backing ConcurrentHashMap instance has * the specified initial capacity and the specified load factor. * * @param initialCapacity the initial capacity. The implementation * performs internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of elements per * bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently * updating threads. The implementation performs internal sizing * to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive. */ public ConcurrentSet(int initialCapacity, float loadFactor, int concurrencyLevel) { map = new ConcurrentHashMap(initialCapacity, loadFactor, concurrencyLevel); } /** * Constructs a new, empty set; the backing ConcurrentHashMap instance has * the specified initial capacity and default load factor, which is * 0.75. * * @param initialCapacity the initial capacity of the hash table. * @throws IllegalArgumentException if the initial capacity is less * than zero. */ public ConcurrentSet(int initialCapacity) { map = new ConcurrentHashMap(initialCapacity); } /** * Returns an iterator over the elements in this set. The elements * are returned in no particular order. * * @return an Iterator over the elements in this set. * @see java.util.ConcurrentModificationException */ public Iterator iterator() { return map.keySet().iterator(); } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality). */ public int size() { return map.size(); } /** * Returns true if this set contains no elements. * * @return true if this set contains no elements. */ public boolean isEmpty() { return map.isEmpty(); } /** * Returns true if this set contains the specified element. * * @param o element whose presence in this set is to be tested. * @return true if this set contains the specified element. */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean contains(Object o) { return map.containsKey(o); } /** * Adds the specified element to this set if it is not already * present. * * @param o element to be added to this set. * @return true if the set did not already contain the specified * element. */ public boolean add(E o) { return map.put(o, PRESENT) == null; } /** * Removes the specified element from this set if it is present. * * @param o object to be removed from this set, if present. * @return true if the set contained the specified element. */ public boolean remove(Object o) { return map.remove(o) == PRESENT; } /** * Removes all of the elements from this set. */ public void clear() { map.clear(); } }libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Classes.java0000644000175000017500000006243210774222622031423 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Array; import java.lang.NoSuchMethodException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.*; /** * A collection of Class utilities. * * @version $Revision: 2787 $ * @author Jason Dillon * @author Scott Stark * @author Dimitris Andreadis */ @SuppressWarnings("unchecked") public final class Classes { /** The string used to separator packages */ public static final String PACKAGE_SEPARATOR = "."; /** The characther used to separator packages */ public static final char PACKAGE_SEPARATOR_CHAR = '.'; /** The default package name. */ public static final String DEFAULT_PACKAGE_NAME = ""; /** Format a string buffer containing the Class, Interfaces, CodeSource, and ClassLoader information for the given object clazz. @param clazz the Class @param results - the buffer to write the info to */ public static void displayClassInfo(Class clazz, StringBuffer results) { // Print out some codebase info for the clazz ClassLoader cl = clazz.getClassLoader(); results.append("\n"); results.append(clazz.getName()); results.append("("); results.append(Integer.toHexString(clazz.hashCode())); results.append(").ClassLoader="); results.append(cl); ClassLoader parent = cl; while( parent != null ) { results.append("\n.."); results.append(parent); URL[] urls = getClassLoaderURLs(parent); int length = urls != null ? urls.length : 0; for(int u = 0; u < length; u ++) { results.append("\n...."); results.append(urls[u]); } if( parent != null ) parent = parent.getParent(); } CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource(); if( clazzCS != null ) { results.append("\n++++CodeSource: "); results.append(clazzCS); } else results.append("\n++++Null CodeSource"); results.append("\nImplemented Interfaces:"); Class[] ifaces = clazz.getInterfaces(); for(int i = 0; i < ifaces.length; i ++) { Class iface = ifaces[i]; results.append("\n++"); results.append(iface); results.append("("); results.append(Integer.toHexString(iface.hashCode())); results.append(")"); ClassLoader loader = ifaces[i].getClassLoader(); results.append("\n++++ClassLoader: "); results.append(loader); ProtectionDomain pd = ifaces[i].getProtectionDomain(); CodeSource cs = pd.getCodeSource(); if( cs != null ) { results.append("\n++++CodeSource: "); results.append(cs); } else results.append("\n++++Null CodeSource"); } } /** Use reflection to access a URL[] getURLs or URL[] getClasspath method so that non-URLClassLoader class loaders, or class loaders that override getURLs to return null or empty, can provide the true classpath info. * @param cl * @return the urls */ public static URL[] getClassLoaderURLs(ClassLoader cl) { URL[] urls = {}; try { Class returnType = urls.getClass(); Class[] parameterTypes = {}; Class clClass = cl.getClass(); Method getURLs = clClass.getMethod("getURLs", parameterTypes); if( returnType.isAssignableFrom(getURLs.getReturnType()) ) { Object[] args = {}; urls = (URL[]) getURLs.invoke(cl, args); } if( urls == null || urls.length == 0 ) { Method getCp = clClass.getMethod("getClasspath", parameterTypes); if( returnType.isAssignableFrom(getCp.getReturnType()) ) { Object[] args = {}; urls = (URL[]) getCp.invoke(cl, args); } } } catch(Exception ignore) { } return urls; } /** * Describe the class of an object * * @param object the object * @return the description */ public static String getDescription(Object object) { StringBuffer buffer = new StringBuffer(); describe(buffer, object); return buffer.toString(); } /** * Describe the class of an object * * @param buffer the string buffer * @param object the object */ public static void describe(StringBuffer buffer, Object object) { if (object == null) buffer.append("**null**"); else describe(buffer, object.getClass()); } /** * Describe the class * * @param buffer the string buffer * @param clazz the clazz */ public static void describe(StringBuffer buffer, Class clazz) { if (clazz == null) buffer.append("**null**"); else { buffer.append("{class=").append(clazz.getName()); Class[] intfs = clazz.getInterfaces(); if (intfs.length > 0) { buffer.append(" intfs="); for (int i = 0; i < intfs.length; ++i) { buffer.append(intfs[i].getName()); if (i < intfs.length-1) buffer.append(", "); } } buffer.append("}"); } } /** * Get the short name of the specified class by striping off the package * name. * * @param classname Class name. * @return Short class name. */ public static String stripPackageName(final String classname) { int idx = classname.lastIndexOf(PACKAGE_SEPARATOR); if (idx != -1) return classname.substring(idx + 1, classname.length()); return classname; } /** * Get the short name of the specified class by striping off the package * name. * * @param type Class name. * @return Short class name. */ public static String stripPackageName(final Class type) { return stripPackageName(type.getName()); } /** * Get the package name of the specified class. * * @param classname Class name. * @return Package name or "" if the classname is in the * default package. * * @throws EmptyStringException Classname is an empty string. */ public static String getPackageName(final String classname) { if (classname.length() == 0) throw new EmptyStringException(); int index = classname.lastIndexOf(PACKAGE_SEPARATOR); if (index != -1) return classname.substring(0, index); return ""; } /** * Get the package name of the specified class. * * @param type Class. * @return Package name. */ public static String getPackageName(final Class type) { return getPackageName(type.getName()); } /** * Force the given class to be loaded fully. * *

This method attempts to locate a static method on the given class * the attempts to invoke it with dummy arguments in the hope that * the virtual machine will prepare the class for the method call and * call all of the static class initializers. * * @param type Class to force load. * * @throws NullArgumentException Type is null. */ public static void forceLoad(final Class type) { if (type == null) throw new NullArgumentException("type"); // don't attempt to force primitives to load if (type.isPrimitive()) return; // don't attempt to force java.* classes to load String packageName = Classes.getPackageName(type); // System.out.println("package name: " + packageName); if (packageName.startsWith("java.") || packageName.startsWith("javax.")) { return; } // System.out.println("forcing class to load: " + type); try { Method methods[] = type.getDeclaredMethods(); Method method = null; for (int i = 0; i < methods.length; i++) { int modifiers = methods[i].getModifiers(); if (Modifier.isStatic(modifiers)) { method = methods[i]; break; } } if (method != null) { method.invoke(null, (Object[]) null); } else { type.newInstance(); } } catch (Exception ignore) { ThrowableHandler.add(ignore); } } ///////////////////////////////////////////////////////////////////////// // Primitives // ///////////////////////////////////////////////////////////////////////// /** Primitive type name -> class map. */ private static final Map PRIMITIVE_NAME_TYPE_MAP = new HashMap(); /** Setup the primitives map. */ static { PRIMITIVE_NAME_TYPE_MAP.put("boolean", Boolean.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("byte", Byte.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("char", Character.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("short", Short.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("int", Integer.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("long", Long.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("float", Float.TYPE); PRIMITIVE_NAME_TYPE_MAP.put("double", Double.TYPE); } /** * Get the primitive type for the given primitive name. * *

* For example, "boolean" returns Boolean.TYPE and so on... * * @param name Primitive type name (boolean, int, byte, ...) * @return Primitive type or null. * * @exception IllegalArgumentException Type is not a primitive class */ public static Class getPrimitiveTypeForName(final String name) { return (Class) PRIMITIVE_NAME_TYPE_MAP.get(name); } /** Map of primitive types to their wrapper classes */ private static final Class[] PRIMITIVE_WRAPPER_MAP = { Boolean.TYPE, Boolean.class, Byte.TYPE, Byte.class, Character.TYPE, Character.class, Double.TYPE, Double.class, Float.TYPE, Float.class, Integer.TYPE, Integer.class, Long.TYPE, Long.class, Short.TYPE, Short.class, }; /** * Get the wrapper class for the given primitive type. * * @param type Primitive class. * @return Wrapper class for primitive. * * @exception IllegalArgumentException Type is not a primitive class */ public static Class getPrimitiveWrapper(final Class type) { if (!type.isPrimitive()) { throw new IllegalArgumentException("type is not a primitive class"); } for (int i = 0; i < PRIMITIVE_WRAPPER_MAP.length; i += 2) { if (type.equals(PRIMITIVE_WRAPPER_MAP[i])) return PRIMITIVE_WRAPPER_MAP[i + 1]; } // should never get here, if we do then PRIMITIVE_WRAPPER_MAP // needs to be updated to include the missing mapping throw new UnreachableStatementException(); } /** * Populates a list with all the interfaces implemented by the argument * class c and all its superclasses. * * @param allIfaces - the list to populate with the interfaces * @param c - the class to start scanning for interfaces */ public static void getAllInterfaces(List allIfaces, Class c) { while (c != null) { Class[] ifaces = c.getInterfaces(); for (int n = 0; n < ifaces.length; n ++) { allIfaces.add(ifaces[n]); } c = c.getSuperclass(); } } /** * Returns an array containing all the unique interfaces implemented * by the argument class c and all its superclasses. Interfaces that * appear multiple times through inheritence are only accounted for once. * * @param c - the class to start scanning for interfaces * @return the interfaces */ public static Class[] getAllUniqueInterfaces(Class c) { Set uniqueIfaces = new HashSet(); while (c != null ) { Class[] ifaces = c.getInterfaces(); for (int n = 0; n < ifaces.length; n ++) { uniqueIfaces.add(ifaces[n]); } c = c.getSuperclass(); } return (Class[])uniqueIfaces.toArray(new Class[uniqueIfaces.size()]); } /** * Check if the given class is a primitive wrapper class. * * @param type Class to check. * @return True if the class is a primitive wrapper. */ public static boolean isPrimitiveWrapper(final Class type) { for (int i = 0; i < PRIMITIVE_WRAPPER_MAP.length; i += 2) { if (type.equals(PRIMITIVE_WRAPPER_MAP[i + 1])) { return true; } } return false; } /** * Check if the given class is a primitive class or a primitive * wrapper class. * * @param type Class to check. * @return True if the class is a primitive or primitive wrapper. */ public static boolean isPrimitive(final Class type) { if (type.isPrimitive() || isPrimitiveWrapper(type)) { return true; } return false; } /** Check type against boolean, byte, char, short, int, long, float, double. * @param type The java type name * @return true if this is a primative type name. */ public static boolean isPrimitive(final String type) { return PRIMITIVE_NAME_TYPE_MAP.containsKey(type); } /** * @param wrapper a primitive wrapper type * @return primitive type the passed in wrapper type corresponds to */ public static Class getPrimitive(Class wrapper) { Class primitive; if(Integer.class == wrapper) { primitive = int.class; } else if(Long.class == wrapper) { primitive = long.class; } else if(Double.class == wrapper) { primitive = double.class; } else if(Boolean.class == wrapper) { primitive = boolean.class; } else if(Short.class == wrapper) { primitive = short.class; } else if(Float.class == wrapper) { primitive = float.class; } else if(Byte.class == wrapper) { primitive = byte.class; } else if(Character.class == wrapper) { primitive = char.class; } else { throw new IllegalArgumentException("The class is not a primitive wrapper type: " + wrapper); } return primitive; } /** * Instantiate a java class object * * @param expected the expected class type * @param property the system property defining the class * @param defaultClassName the default class name * @return the instantiated object */ public static Object instantiate(Class expected, String property, String defaultClassName) { String className = getProperty(property, defaultClassName); Class clazz = null; try { clazz = loadClass(className); } catch (ClassNotFoundException e) { throw new NestedRuntimeException("Cannot load class " + className, e); } Object result = null; try { result = clazz.newInstance(); } catch (InstantiationException e) { throw new NestedRuntimeException("Error instantiating " + className, e); } catch (IllegalAccessException e) { throw new NestedRuntimeException("Error instantiating " + className, e); } if (expected.isAssignableFrom(clazz) == false) throw new NestedRuntimeException("Class " + className + " from classloader " + clazz.getClassLoader() + " is not of the expected class " + expected + " loaded from " + expected.getClassLoader()); return result; } ///////////////////////////////////////////////////////////////////////// // Class Loading // ///////////////////////////////////////////////////////////////////////// /** * This method acts equivalently to invoking * Thread.currentThread().getContextClassLoader().loadClass(className); but it also * supports primitive types and array classes of object types or primitive types. * * @param className the qualified name of the class or the name of primitive type or * array in the same format as returned by the * java.lang.Class.getName() method. * @return the Class object for the requested className * * @throws ClassNotFoundException when the classLoader can not find the requested class */ public static Class loadClass(String className) throws ClassNotFoundException { return loadClass(className, Thread.currentThread().getContextClassLoader()); } /** * This method acts equivalently to invoking classLoader.loadClass(className) * but it also supports primitive types and array classes of object types or * primitive types. * * @param className the qualified name of the class or the name of primitive * type or array in the same format as returned by the * java.lang.Class.getName() method. * @param classLoader the ClassLoader used to load classes * @return the Class object for the requested className * * @throws ClassNotFoundException when the classLoader can not * find the requested class */ public static Class loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { // ClassLoader.loadClass() does not handle primitive types: // // B byte // C char // D double // F float // I int // J long // S short // Z boolean // V void // if (className.length() == 1) { char type = className.charAt(0); if (type == 'B') return Byte.TYPE; if (type == 'C') return Character.TYPE; if (type == 'D') return Double.TYPE; if (type == 'F') return Float.TYPE; if (type == 'I') return Integer.TYPE; if (type == 'J') return Long.TYPE; if (type == 'S') return Short.TYPE; if (type == 'Z') return Boolean.TYPE; if (type == 'V') return Void.TYPE; // else throw... throw new ClassNotFoundException(className); } // Check for a primative type if( isPrimitive(className) == true ) return (Class) Classes.PRIMITIVE_NAME_TYPE_MAP.get(className); // Check for the internal vm format: Lclassname; if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') return classLoader.loadClass(className.substring(1, className.length() - 1)); // first try - be optimistic // this will succeed for all non-array classes and array classes that have already been resolved // try { return classLoader.loadClass(className); } catch (ClassNotFoundException e) { // if it was non-array class then throw it if (className.charAt(0) != '[') throw e; } // we are now resolving array class for the first time // count opening braces int arrayDimension = 0; while (className.charAt(arrayDimension) == '[') arrayDimension++; // resolve component type - use recursion so that we can resolve primitive types also Class componentType = loadClass(className.substring(arrayDimension), classLoader); // construct array class return Array.newInstance(componentType, new int[arrayDimension]).getClass(); } /** * Convert a list of Strings from an Interator into an array of * Classes (the Strings are taken as classnames). * * @param it A java.util.Iterator pointing to a Collection of Strings * @param cl The ClassLoader to use * * @return Array of Classes * * @throws ClassNotFoundException When a class could not be loaded from * the specified ClassLoader */ public final static Class[] convertToJavaClasses(Iterator it, ClassLoader cl) throws ClassNotFoundException { ArrayList> classes = new ArrayList>(); while (it.hasNext()) { classes.add(convertToJavaClass(it.next(), cl)); } return classes.toArray(new Class[classes.size()]); } /** * Returns attribute's getter method. If the method not found then NoSuchMethodException will be thrown. * @param cls the class the attribute belongs too * @param attr the attribute's name * @return attribute's getter method * @throws NoSuchMethodException if the getter was not found */ public final static Method getAttributeGetter(Class cls, String attr) throws NoSuchMethodException { StringBuffer buf = new StringBuffer(attr.length() + 3); buf.append("get"); if(Character.isLowerCase(attr.charAt(0))) { buf.append(Character.toUpperCase(attr.charAt(0))) .append(attr.substring(1)); } else { buf.append(attr); } try { return cls.getMethod(buf.toString(), (Class[]) null); } catch (NoSuchMethodException e) { buf.replace(0, 3, "is"); return cls.getMethod(buf.toString(), (Class[]) null); } } /** * Returns attribute's setter method. If the method not found then NoSuchMethodException will be thrown. * @param cls the class the attribute belongs to * @param attr the attribute's name * @param type the attribute's type * @return attribute's setter method * @throws NoSuchMethodException if the setter was not found */ public final static Method getAttributeSetter(Class cls, String attr, Class type) throws NoSuchMethodException { StringBuffer buf = new StringBuffer(attr.length() + 3); buf.append("set"); if(Character.isLowerCase(attr.charAt(0))) { buf.append(Character.toUpperCase(attr.charAt(0))) .append(attr.substring(1)); } else { buf.append(attr); } return cls.getMethod(buf.toString(), new Class[]{type}); } /** * Convert a given String into the appropriate Class. * * @param name Name of class * @param cl ClassLoader to use * * @return The class for the given name * * @throws ClassNotFoundException When the class could not be found by * the specified ClassLoader */ private final static Class convertToJavaClass(String name, ClassLoader cl) throws ClassNotFoundException { int arraySize = 0; while (name.endsWith("[]")) { name = name.substring(0, name.length() - 2); arraySize++; } // Check for a primitive type Class c = (Class) PRIMITIVE_NAME_TYPE_MAP.get(name); if (c == null) { // No primitive, try to load it from the given ClassLoader try { c = cl.loadClass(name); } catch (ClassNotFoundException cnfe) { throw new ClassNotFoundException("Parameter class not found: " + name); } } // if we have an array get the array class if (arraySize > 0) { int[] dims = new int[arraySize]; for (int i = 0; i < arraySize; i++) { dims[i] = 1; } c = Array.newInstance(c, dims).getClass(); } return c; } /** * Get a system property * * @param name the property name * @param defaultValue the default value */ private static String getProperty(final String name, final String defaultValue) { return (String) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return System.getProperty(name, defaultValue); } }); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedRuntimeException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NestedRuntimeExceptio0000644000175000017500000001031010776226110033357 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; /** * A common superclass for RuntimeException classes that can * contain a nested Throwable detail object. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NestedRuntimeException extends RuntimeException implements NestedThrowable { /** The serialVersionUID */ private static final long serialVersionUID = 9017248167673450852L; /** The nested throwable */ protected final Throwable nested; /** * Construct a NestedRuntimeException with the specified * detail message. * * @param msg Detail message. */ public NestedRuntimeException(final String msg) { super(msg); this.nested = null; } /** * Construct a NestedRuntimeException with the specified * detail message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public NestedRuntimeException(final String msg, final Throwable nested) { super(msg); this.nested = nested; NestedThrowable.Util.checkNested(this, nested); } /** * Construct a NestedRuntimeException with the specified * nested Throwable. * * @param nested Nested Throwable. */ public NestedRuntimeException(final Throwable nested) { this(nested.getMessage(), nested); } /** * Construct a NestedRuntimeException with no detail. */ public NestedRuntimeException() { super(); this.nested = null; } /** * Return the nested Throwable. * * @return Nested Throwable. */ public Throwable getNested() { return nested; } /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ public Throwable getCause() { return nested; } /** * Returns the composite throwable message. * * @return The composite throwable message. */ public String getMessage() { return NestedThrowable.Util.getMessage(super.getMessage(), nested); } /** * Prints the composite message and the embedded stack trace to the * specified print stream. * * @param stream Stream to print to. */ public void printStackTrace(final PrintStream stream) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(stream); } NestedThrowable.Util.print(nested, stream); } /** * Prints the composite message and the embedded stack trace to the * specified print writer. * * @param writer Writer to print to. */ public void printStackTrace(final PrintWriter writer) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(writer); } NestedThrowable.Util.print(nested, writer); } /** * Prints the composite message and the embedded stack trace to * System.err. */ public void printStackTrace() { printStackTrace(System.err); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/SysPropertyActions.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/SysPropertyActions.ja0000644000175000017500000000454410774222622033343 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.security.PrivilegedAction; import java.security.AccessController; /** * Priviledged actions for the package * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") class SysPropertyActions { interface SysProps { SysProps NON_PRIVILEDGED = new SysProps() { public String getProperty(final String name, final String defaultValue) { return System.getProperty(name, defaultValue); } }; SysProps PRIVILEDGED = new SysProps() { public String getProperty(final String name, final String defaultValue) { PrivilegedAction action = new PrivilegedAction() { public Object run() { return System.getProperty(name, defaultValue); } }; return (String) AccessController.doPrivileged(action); } }; String getProperty(String name, String defaultValue); } public static String getProperty(String name, String defaultValue) { String prop; if( System.getSecurityManager() == null ) prop = SysProps.NON_PRIVILEDGED.getProperty(name, defaultValue); else prop = SysProps.PRIVILEDGED.getProperty(name, defaultValue); return prop; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/0000755000175000017500000000000011105642365030273 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/xml/0000755000175000017500000000000011105642364031072 5ustar twernertwerner././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/xml/StateMachineParser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/xml/StateMachin0000755000175000017500000001414410774222622033226 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.state.xml; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import org.jboss.logging.Logger; import org.jboss.util.state.State; import org.jboss.util.state.StateMachine; import org.jboss.util.state.Transition; import org.jboss.util.xml.DOMUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** Parse an xml representation of a state machine. A sample document is: @author Scott.Stark@jboss.org @author Dimitris.Andreadis@jboss.org @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class StateMachineParser { private static Logger log = Logger.getLogger(StateMachineParser.class); public StateMachine parse(URL source) throws Exception { // parse the XML document into a DOM structure InputStream in = source.openConnection().getInputStream(); Element root = DOMUtils.parse(in); String description = root.getAttribute("description"); HashMap nameToStateMap = new HashMap(); HashMap nameToTransitionsMap = new HashMap(); HashSet states = new HashSet(); State startState = null; // parse states NodeList stateList = root.getChildNodes(); for (int i = 0; i < stateList.getLength(); i++) { Node stateNode = stateList.item(i); if (stateNode.getNodeName().equals("state")) { Element stateElement = (Element)stateNode; String stateName = stateElement.getAttribute("name"); State s = new State(stateName); states.add(s); nameToStateMap.put(stateName, s); HashMap transitions = new HashMap(); // parse transitions NodeList transitionList = stateElement.getChildNodes(); for (int j = 0; j < transitionList.getLength(); j++) { Node transitionNode = transitionList.item(j); if (transitionNode.getNodeName().equals("transition")) { Element transitionElement = (Element)transitionNode; String name = transitionElement.getAttribute("name"); String targetName = transitionElement.getAttribute("target"); transitions.put(name, targetName); } } nameToTransitionsMap.put(stateName, transitions); if (Boolean.valueOf(stateElement.getAttribute("isStartState")) == Boolean.TRUE) startState = s; } } // Resolve all transition targets Iterator transitions = nameToTransitionsMap.keySet().iterator(); StringBuffer resolveFailed = new StringBuffer(); while (transitions.hasNext()) { String stateName = (String)transitions.next(); State s = (State)nameToStateMap.get(stateName); HashMap stateTransitions = (HashMap)nameToTransitionsMap.get(stateName); Iterator it = stateTransitions.keySet().iterator(); while (it.hasNext()) { String name = (String)it.next(); String targetName = (String)stateTransitions.get(name); State target = (State)nameToStateMap.get(targetName); if (target == null) { String msg = "Failed to resolve target state: " + targetName + " for transition: " + name; resolveFailed.append(msg); log.debug(msg); } Transition t = new Transition(name, target); s.addTransition(t); } } if (resolveFailed.length() > 0) throw new Exception("Failed to resolve transition targets: " + resolveFailed); StateMachine sm = new StateMachine(states, startState, description); return sm; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/State.java0000644000175000017500000000675010774222622032227 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.state; import java.util.HashMap; import java.util.Map; import java.util.Iterator; /** The respresentation of a state in a state machine. * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class State { /** The name of the state */ private String name; /** HashMap */ private HashMap allowedTransitions = new HashMap(); /** Arbitrary state data */ private Object data; public State(String name) { this(name, null); } public State(String name, Map transitions) { this.name = name; if( transitions != null ) { allowedTransitions.putAll(transitions); } } /** Get the state name. * @return the name of the state. */ public String getName() { return name; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } /** An accept state is indicated by no transitions * @return true if this is an accept state, false otherwise. */ public boolean isAcceptState() { return allowedTransitions.size() == 0; } /** Add a transition to the allowed transition map. * * @param transition * @return this to allow chained addTransition calls */ public State addTransition(Transition transition) { allowedTransitions.put(transition.getName(), transition); return this; } /** Lookup an allowed transition given its name. * * @param name - the name of a valid transition from this state. * @return the valid transition if it exists, null otherwise. */ public Transition getTransition(String name) { Transition t = (Transition) allowedTransitions.get(name); return t; } /** Get the Map of allowed transitions for this state. * @return the allowed transitions map. */ public Map getTransitions() { return allowedTransitions; } public String toString() { StringBuffer tmp = new StringBuffer("State(name="); tmp.append(name); Iterator i = allowedTransitions.entrySet().iterator(); while( i.hasNext() ) { Map.Entry e = (Map.Entry) i.next(); tmp.append("\n\t on: "); tmp.append(e.getKey()); Transition t = (Transition) e.getValue(); tmp.append(" go to: "); tmp.append(t.getTarget().getName()); } tmp.append(')'); return tmp.toString(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/StateMachine.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/StateMachine.ja0000644000175000017500000001116010774222622033154 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.state; import java.util.HashSet; import java.util.Set; import java.util.Iterator; import org.jboss.logging.Logger; /** The representation of a finite state machine. * * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class StateMachine implements Cloneable { private static Logger log = Logger.getLogger(StateMachine.class); /** A description of the state machine */ private String description; /** The set of states making up the state machine */ private HashSet states; /** The starting state */ private State startState; /** The current state of the state machine */ private State currentState; /** Create a state machine given its states and start state. * * @param states - Set for the state machine * @param startState - the starting state */ public StateMachine(Set states, State startState) { this(states, startState, null); } /** Create a state machine given its states and start state. * * @param states - Set for the state machine * @param startState - the starting state * @param description - an optional description of the state machine */ public StateMachine(Set states, State startState, String description) { this.states = new HashSet(states); this.startState = startState; this.currentState = startState; this.description = description; } /** Make a copy of the StateMachine maintaining the current state. * * @return a copy of the StateMachine. */ public Object clone() { StateMachine clone = new StateMachine(states, startState, description); clone.currentState = currentState; return clone; } /** Get the state machine description. * @return an possibly null description. */ public String getDescription() { return description; } /** Get the current state of the state machine. * @return the current state. */ public State getCurrentState() { return currentState; } /** Get the start state of the state machine. * @return the start state. */ public State getStartState() { return startState; } /** Get the states of the state machine. * @return the machine states. */ public Set getStates() { return states; } /** Transition to the next state given the name of a valid transition. * @param actionName - the name of transition that is valid for the * current state. * @return the next state * @throws IllegalTransitionException */ public State nextState(String actionName) throws IllegalTransitionException { Transition t = currentState.getTransition(actionName); if( t == null ) { String msg = "No transition for action: '" + actionName + "' from state: '" + currentState.getName() + "'"; throw new IllegalTransitionException(msg); } State nextState = t.getTarget(); log.trace("nextState("+actionName+") = "+nextState); currentState = nextState; return currentState; } /** Reset the state machine back to the start state * * @return the start state */ public State reset() { this.currentState = startState; return currentState; } public String toString() { StringBuffer tmp = new StringBuffer("StateMachine[:\n"); tmp.append("\tCurrentState: "+currentState.getName()); Iterator i = states.iterator(); while( i.hasNext() ) { tmp.append('\n').append(i.next()); } tmp.append(']'); return tmp.toString(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/Transition.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/Transition.java0000755000175000017500000000272410470642610033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.state; /** A representation of a transition from a state to another state. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class Transition { private String name; private State target; public Transition(String name, State target) { this.name = name; this.target = target; } public String getName() { return name; } public State getTarget() { return target; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/IllegalTransitionException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/state/IllegalTransiti0000755000175000017500000000263310776226110033313 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.state; /** An exception thrown when an invalid transition is attempted from a state. * * @author Scott.Stark@jboss.org * @version $Revision: 2800 $ */ public class IllegalTransitionException extends Exception { /** The serialVersionUID */ private static final long serialVersionUID = -3392564168782896452L; public IllegalTransitionException(String msg) { super(msg); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/0000755000175000017500000000000011105642365030641 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutTarget.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutTarget0000644000175000017500000000255010774222622033364 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; /** * The interface of objects that can receive timeouts. * * @author Ole Husgaard * @version $Revision: 2787 $ */ public interface TimeoutTarget { /** * The timeout callback function is invoked when the timeout expires. * @param timeout */ public void timedOut(Timeout timeout); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutExt.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutExt.ja0000644000175000017500000000265410774222622033274 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; /** * Timeout Extension. * * @author Adrian Brock * @version $Revision: 2787 $ */ public interface TimeoutExt extends Timeout { /** * Get the target of this timeout * * @return the target */ TimeoutTarget getTimeoutTarget(); /** * @return the time of this timeout */ long getTime(); /** * Mark the work as done */ void done(); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/Timeout.java0000644000175000017500000000347210774222622033141 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; /** * The public interface of timeouts. * * @author Ole Husgaard * @version $Revision: 2787 $ */ public interface Timeout { /** * Cancel this timeout. * * It is guaranteed that on return from this method this timer is * no longer active. This means that either it has been cancelled and * the timeout will not happen, or (in case of late cancel) the * timeout has happened and the timeout callback function has returned. * * On return from this method this instance should no longer be * used. The reason for this is that an implementation may reuse * cancelled timeouts, and at return the instance may already be * in use for another timeout. * * @return true when cancelled */ public boolean cancel(); }././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutPriorityQueueImpl.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutPriori0000644000175000017500000003772010774222622033411 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; /** * TimeoutPriorityQueueImpl. * * This is a balanced binary tree. If nonempty, the root is at index 1, * and all nodes are at indices 1..size. Nodes with index greater than * size are null. Index 0 is never used. * Children of the node at index j are at j*2 * and j*2+1. The children of a node always fire the timeout * no earlier than the node. * * * Or, more formally: * * Only indices 1..size of this array are used. * All other indices contain the null reference. * This array represent a balanced binary tree. * * If size is 0 the tree is empty, otherwise * the root of the tree is at index 1. * * Given an arbitrary node at index n that is not the root * node, the parent node of n is at index n/2. * * Given an arbitrary node at index n; if * 2*n <= size the node at n has its left child * at index 2*n, otherwise the node at n has * no left child. * * Given an arbitrary node at index n; if * 2*n+1 <= size the node at n has its right child * at index 2*n+1, otherwise the node at n has * no right child. * * The priority function is called T. Given a node n, * T(n) denotes the absolute time (in milliseconds since * the epoch) that the timeout for node n should happen. * Smaller values of T means higher priority. * * The tree satisfies the following invariant: * * For any node n in the tree: * If node n has a left child l, * T(n) <= T(l). * If node n has a right child r, * T(n) <= T(r). * * * * The invariant may be temporarily broken while executing synchronized * on this instance, but is always reestablished before * leaving the synchronized code. * * The node at index 1 is always the first node to timeout, * as can be deduced from the invariant. * * For the following algorithm pseudocode, the operation * swap(n,m) denotes the exchange of the nodes at indices * n and m in the tree. * * Insertion of a new node happend as follows: *

 *    IF size = q.length THEN
 *      "expand q array to be larger";
 *    ENDIF
 *    size <- size + 1;
 *    q[size] <- "new node";
 *    n <- size;
 *    WHILE n > 1 AND T(n/2) > T(n) DO
 *      swap(n/2, n);
 *      n <- n/2;
 *    ENDWHILE
 *  
* Proof that this insertion algorithm respects the invariant is left to * the interested reader. * * The removal algorithm is a bit more complicated. To remove the node * at index n: *
 *    swap(n, size);
 *    size <- size - 1;
 *    IF n > 1 AND T(n/2) > T(n) THEN
 *      WHILE n > 1 AND T(n/2) > T(n) DO
 *        swap(n/2, n);
 *        n <- n/2;
 *      ENDWHILE
 *    ELSE
 *      WHILE 2*n <= size DO
 *        IF 2*n+1 <= size THEN
 *          // Both children present
 *          IF T(2*n) <= T(2*n+1) THEN
 *            IF T(n) <= T(2*n) THEN
 *              EXIT;
 *            ENDIF
 *            swap(n, 2*n);
 *            n <- 2*n;
 *          ELSE
 *            IF T(n) <= T(2*n+1) THEN
 *              EXIT;
 *            ENDIF
 *            swap(n, 2*n+1);
 *            n <- 2*n+1;
 *          ENDIF
 *        ELSE
 *          // Only left child, right child not present.
 *          IF T(n) <= T(2*n) THEN
 *            EXIT;
 *          ENDIF
 *          swap(n, 2*n);
 *          n <- 2*n;
 *        ENDIF
 *      ENDWHILE
 *    ENDIF
 *  
* Proof that this removal algorithm respects the invariant is left to * the interested reader. Really, I am not going to prove it here. * * If you are interested, you can find this data structure and its * associated operations in most textbooks on algorithmics. * * @author Ole Husgaard * @author Dimitris Andreadis * @author Elias Ross * @author Adrian Brock * @version $Revision: 2787 $ */ public class TimeoutPriorityQueueImpl implements TimeoutPriorityQueue { // Code commented out with the mark "INV:" are runtime checks // of invariants that are not needed for a production system. // For problem solving, you can remove these comments. // Multithreading notes: // // While a TimeoutImpl is enqueued, its index field contains the index // of the instance in the queue; that is, for 1 <= n <= size, // q[n].index = n. // Modifications of an enqueued TimeoutImpl instance may only happen // in code synchronized on the TimeoutFactory instance that has it // enqueued. // Modifications on the priority queue may only happen while running in // code synchronized on the TimeoutFactory instance that holds the queue. // When a TimeoutImpl instance is no longer enqueued, its index field // changes to one of the negative constants declared in the TimeoutImpl // class. // // Cancellation may race with the timeout. // To avoid problems with this, the TimeoutImpl index field is set to // TimeoutImpl.TIMEOUT when the TimeoutImpl is taken out of the queue. // Finally the index field is set to TimeoutImpl.DONE, and // the TimeoutImpl instance is discarded. /** The lock object */ private Object lock = new Object(); /** The size of the timeout queue. */ private int size; /** The timeouts */ private TimeoutExtImpl[] queue; /** * Create a new TimeoutPriorityQueueImpl. */ public TimeoutPriorityQueueImpl() { queue = new TimeoutExtImpl[16]; size = 0; } public TimeoutExt offer(long time, TimeoutTarget target) { if (queue == null) throw new IllegalStateException("TimeoutPriorityQueue has been cancelled"); if (time < 0) throw new IllegalArgumentException("Negative time"); if (target == null) throw new IllegalArgumentException("Null timeout target"); synchronized (lock) { // INV: checkTree(); // INV: assertExpr(size < queue.length); if (++size == queue.length) { TimeoutExtImpl[] newQ = new TimeoutExtImpl[2 * queue.length]; System.arraycopy(queue, 0, newQ, 0, queue.length); queue = newQ; } // INV: assertExpr(size < queue.length); // INV: assertExpr(queue[size] == null); TimeoutExtImpl timeout; timeout = queue[size] = new TimeoutExtImpl(); timeout.index = size; timeout.time = time; timeout.target = target; normalizeUp(size); if (timeout.index == 1) lock.notify(); // INV: checkTree(); return timeout; } } public TimeoutExt take() { return poll(-1); } public TimeoutExt poll() { return poll(1); } public TimeoutExt poll(long wait) { long endWait = -1; if (wait > 0) endWait = System.currentTimeMillis() + wait; // Look for work synchronized (lock) { while (queue != null && (wait >= 0 || endWait == -1)) { if (size == 0) { try { if (endWait == -1) lock.wait(); else lock.wait(wait); } catch (InterruptedException ex) { } } else { long now = System.currentTimeMillis(); if (queue[1].time > now) { long waitForFirst = queue[1].time - now; if (endWait != -1 && waitForFirst > wait) waitForFirst = wait; try { lock.wait(waitForFirst); } catch (InterruptedException ex) { } } if (size > 0 && queue != null && queue[1].time <= System.currentTimeMillis()) { TimeoutExtImpl result = removeNode(1); result.index = TimeoutExtImpl.TIMEOUT; return result; } } if (endWait != -1) wait = endWait - System.currentTimeMillis(); } } return null; } public TimeoutExt peek() { synchronized (lock) { if (size > 0) return queue[1]; else return null; } } public boolean remove(TimeoutExt timeout) { TimeoutExtImpl timeoutImpl = (TimeoutExtImpl) timeout; synchronized (lock) { if (timeoutImpl.index > 0) { // Active timeout, remove it. // INV: assertExpr(queue[timeoutImpl.index] == timeout); // INV: checkTree(); removeNode(timeoutImpl.index); // INV: checkTree(); timeoutImpl.index = TimeoutExtImpl.DONE; // execution cancelled return true; } else { // has already been executed (DONE) or // is currently executing (TIMEOUT) return false; } } } public void clear() { synchronized (lock) { if (queue == null) return; // cleanup queue for (int i = 1; i <= size; ++i) queue[i] = cleanupTimeoutExtImpl(queue[i]); } } public void cancel() { synchronized (lock) { if (queue == null) return; clear(); queue = null; size = 0; lock.notifyAll(); } } public int size() { return size; } /** * Whether the queue is cancelled * * @return true when cancelled */ public boolean isCancelled() { return queue == null; } /** * A new node has been added at index index. * Normalize the tree by moving the new node up the tree. * * @return true if the tree was modified. */ private boolean normalizeUp(int index) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); // INV: assertExpr(queue[index] != null); if (index == 1) return false; // at root boolean ret = false; long t = queue[index].time; int p = index >> 1; while (queue[p].time > t) { // INV: assertExpr(queue[index].time == t); swap(p, index); ret = true; if (p == 1) break; // at root index = p; p >>= 1; } return ret; } /** * Swap two nodes in the tree. * * @param a the first index * @param b the second index */ private void swap(int a, int b) { // INV: assertExpr(a > 0); // INV: assertExpr(a <= size); // INV: assertExpr(b > 0); // INV: assertExpr(b <= size); // INV: assertExpr(queue[a] != null); // INV: assertExpr(queue[b] != null); // INV: assertExpr(queue[a].index == a); // INV: assertExpr(queue[b].index == b); TimeoutExtImpl temp = queue[a]; queue[a] = queue[b]; queue[a].index = a; queue[b] = temp; queue[b].index = b; } /** * Remove a node from the tree and normalize. * * @param index the index in the queue * @return the removed node. */ private TimeoutExtImpl removeNode(int index) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); TimeoutExtImpl res = queue[index]; // INV: assertExpr(res != null); // INV: assertExpr(res.index == index); if (index == size) { --size; queue[index] = null; return res; } swap(index, size); // Exchange removed node with last leaf node --size; // INV: assertExpr(res.index == size + 1); queue[res.index] = null; if (normalizeUp(index)) return res; // Node moved up, so it shouldn't move down long t = queue[index].time; int c = index << 1; while (c <= size) { // INV: assertExpr(q[index].time == t); TimeoutExtImpl l = queue[c]; // INV: assertExpr(l != null); // INV: assertExpr(l.index == c); if (c + 1 <= size) { // two children, swap with smallest TimeoutExtImpl r = queue[c + 1]; // INV: assertExpr(r != null); // INV: assertExpr(r.index == c+1); if (l.time <= r.time) { if (t <= l.time) break; // done swap(index, c); index = c; } else { if (t <= r.time) break; // done swap(index, c + 1); index = c + 1; } } else { // one child if (t <= l.time) break; // done swap(index, c); index = c; } c = index << 1; } return res; } /** * Recursive cleanup of a TimeoutImpl * * @return null */ private TimeoutExtImpl cleanupTimeoutExtImpl(TimeoutExtImpl timeout) { if (timeout != null) timeout.target = null; return null; } /** * Check invariants of the queue. */ void checkTree() { assertExpr(size >= 0); assertExpr(size < queue.length); assertExpr(queue[0] == null); if (size > 0) { assertExpr(queue[1] != null); assertExpr(queue[1].index == 1); for (int i = 2; i <= size; ++i) { assertExpr(queue[i] != null); assertExpr(queue[i].index == i); assertExpr(queue[i >> 1].time <= queue[i].time); // parent fires first } for (int i = size + 1; i < queue.length; ++i) assertExpr(queue[i] == null); } } /** * Debugging helper. */ private void assertExpr(boolean expr) { if (!expr) throw new IllegalStateException("***** assert failed *****"); } /** * Our private Timeout implementation. */ private class TimeoutExtImpl implements TimeoutExt { /** Done */ static final int DONE = -1; /** In timeout */ static final int TIMEOUT = -2; /** Index in the queue */ int index; /** Time of the timeout */ long time; /** The timeout target */ TimeoutTarget target; public long getTime() { return time; } public TimeoutTarget getTimeoutTarget() { return target; } public void done() { index = DONE; } public boolean cancel() { return remove(this); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutFactory.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutFactor0000644000175000017500000002025410774222622033355 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.util.NestedRuntimeException; import org.jboss.util.ThrowableHandler; import org.jboss.util.threadpool.BasicThreadPool; import org.jboss.util.threadpool.BlockingMode; import org.jboss.util.threadpool.ThreadPool; /** * The timeout factory. * * @author Ole Husgaard * @author Dimitris Andreadis * @author Elias Ross * @author Adrian Brock * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class TimeoutFactory { /** The priority queue property */ private static final String priorityQueueProperty = TimeoutPriorityQueue.class.getName(); /** The priority queue default */ private static final String priorityQueueName = TimeoutPriorityQueueImpl.class.getName(); /** Our singleton instance */ private static TimeoutFactory singleton; /** Number of TimeoutFactories created */ private static int timeoutFactoriesCount = 0; /** The priority queue class */ private static Class priorityQueueClass; /** The default threadpool used to execute timeouts */ private static BasicThreadPool DEFAULT_TP = new BasicThreadPool("Timeouts"); static { DEFAULT_TP.setBlockingMode(BlockingMode.RUN); String priorityQueueClassName = priorityQueueName; ClassLoader cl = TimeoutFactory.class.getClassLoader(); try { priorityQueueClassName = System.getProperty(priorityQueueProperty, priorityQueueName); cl = Thread.currentThread().getContextClassLoader(); } catch (Exception ignored) { } try { priorityQueueClass = cl.loadClass(priorityQueueClassName); } catch (Exception e) { throw new NestedRuntimeException(e.toString(), e); } } /** Used for graceful exiting */ private AtomicBoolean cancelled = new AtomicBoolean(false); /** The daemon thread that dequeues timeouts tasks and issues them for execution to the thread pool */ private Thread workerThread; /** Per TimeoutFactory thread pool used to execute timeouts */ private ThreadPool threadPool; /** The priority queue */ private TimeoutPriorityQueue queue; public synchronized static TimeoutFactory getSingleton() { if (singleton == null) { singleton = new TimeoutFactory(DEFAULT_TP); } return singleton; } /** * Schedules a new timeout using the singleton TimeoutFactory * @param time * @param target * @return the timeout */ static public Timeout createTimeout(long time, TimeoutTarget target) { return getSingleton().schedule(time, target); } /** * Constructs a new TimeoutFactory that uses the provided ThreadPool * @param threadPool */ public TimeoutFactory(ThreadPool threadPool) { this.threadPool = threadPool; try { queue = (TimeoutPriorityQueue) priorityQueueClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Cannot instantiate " + priorityQueueClass,e); } // setup the workerThread workerThread = new Thread("TimeoutFactory-" + timeoutFactoriesCount++) { public void run() { doWork(); } }; workerThread.setDaemon(true); workerThread.start(); } /** * Constructs a new TimeoutFactory that uses the default thread pool */ public TimeoutFactory() { this(DEFAULT_TP); } /** * Schedules a new timeout. * * @param time absolute time * @param target target to fire * @return the timeout */ public Timeout schedule(long time, TimeoutTarget target) { if (cancelled.get()) throw new IllegalStateException("TimeoutFactory has been cancelled"); if (time < 0) throw new IllegalArgumentException("Negative time"); if (target == null) throw new IllegalArgumentException("Null timeout target"); return queue.offer(time, target); } /** * Schedules a new timeout. * * @param time absolute time * @param run runnable to run * @return the timeout */ public Timeout schedule(long time, Runnable run) { return schedule(time, new TimeoutTargetImpl(run)); } /** * Cancels all submitted tasks, stops the worker * thread and clean-ups everything except for the * thread pool. Scheduling new timeouts after cancel * is called results in a IllegalStateException. */ public void cancel() { // obviously the singleton TimeoutFactory cannot // be cancelled since its reference is not accessible // let the worker thread cleanup if (cancelled.getAndSet(true) == false) { // Cancel the priority queue queue.cancel(); } } /** * @return true if the TimeoutFactory has been cancelled, * false if it is operational (i.e. accepts timeout schedules). */ public boolean isCancelled() { return cancelled.get(); } /** * Timeout worker method. */ private void doWork() { while (cancelled.get() == false) { TimeoutExt work = queue.take(); // Do work, if any if (work != null) { // Wrap the TimeoutExt with a runnable that invokes the target callback TimeoutWorker worker = new TimeoutWorker(work); try { threadPool.run(worker); } catch (Throwable t) { // protect the worker thread from pool enqueue errors ThrowableHandler.add(ThrowableHandler.Type.ERROR, t); } synchronized (work) { work.done(); } } } // TimeoutFactory was cancelled queue.cancel(); } /** * A runnable that fires the timeout callback */ private static class TimeoutWorker implements Runnable { private TimeoutExt work; /** * Create a new instance. * * @param work The timeout that should be fired. */ TimeoutWorker(TimeoutExt work) { this.work = work; } /** * Override to fire the timeout. */ public void run() { try { work.getTimeoutTarget().timedOut(work); } catch (Throwable t) { // protect the thread pool thread from receiving this error ThrowableHandler.add(ThrowableHandler.Type.ERROR, t); } synchronized (work) { work.done(); } } } /** * Simple TimeoutTarget implementation that wraps a Runnable */ private static class TimeoutTargetImpl implements TimeoutTarget { Runnable runnable; TimeoutTargetImpl(Runnable runnable) { this.runnable = runnable; } public void timedOut(Timeout ignored) { runnable.run(); } } }././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/HashedTimeoutPriorityQueueImpl.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/HashedTimeout0000644000175000017500000005215610774222622033341 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.util.JBossStringBuilder; /** * HashedTimeoutPriorityQueueImpl. * * This is a balanced binary tree. If nonempty, the root is at index 1, * and all nodes are at indices 1..size. Nodes with index greater than * size are null. Index 0 is never used. * Children of the node at index j are at j*2 * and j*2+1. The children of a node always fire the timeout * no earlier than the node. * * * Or, more formally: * * Only indices 1..size of this array are used. * All other indices contain the null reference. * This array represent a balanced binary tree. * * If size is 0 the tree is empty, otherwise * the root of the tree is at index 1. * * Given an arbitrary node at index n that is not the root * node, the parent node of n is at index n/2. * * Given an arbitrary node at index n; if * 2*n <= size the node at n has its left child * at index 2*n, otherwise the node at n has * no left child. * * Given an arbitrary node at index n; if * 2*n+1 <= size the node at n has its right child * at index 2*n+1, otherwise the node at n has * no right child. * * The priority function is called T. Given a node n, * T(n) denotes the absolute time (in milliseconds since * the epoch) that the timeout for node n should happen. * Smaller values of T means higher priority. * * The tree satisfies the following invariant: * * For any node n in the tree: * If node n has a left child l, * T(n) <= T(l). * If node n has a right child r, * T(n) <= T(r). * * * * The invariant may be temporarily broken while executing synchronized * on this instance, but is always reestablished before * leaving the synchronized code. * * The node at index 1 is always the first node to timeout, * as can be deduced from the invariant. * * For the following algorithm pseudocode, the operation * swap(n,m) denotes the exchange of the nodes at indices * n and m in the tree. * * Insertion of a new node happend as follows: *
 *    IF size = q.length THEN
 *      "expand q array to be larger";
 *    ENDIF
 *    size <- size + 1;
 *    q[size] <- "new node";
 *    n <- size;
 *    WHILE n > 1 AND T(n/2) > T(n) DO
 *      swap(n/2, n);
 *      n <- n/2;
 *    ENDWHILE
 *  
* Proof that this insertion algorithm respects the invariant is left to * the interested reader. * * The removal algorithm is a bit more complicated. To remove the node * at index n: *
 *    swap(n, size);
 *    size <- size - 1;
 *    IF n > 1 AND T(n/2) > T(n) THEN
 *      WHILE n > 1 AND T(n/2) > T(n) DO
 *        swap(n/2, n);
 *        n <- n/2;
 *      ENDWHILE
 *    ELSE
 *      WHILE 2*n <= size DO
 *        IF 2*n+1 <= size THEN
 *          // Both children present
 *          IF T(2*n) <= T(2*n+1) THEN
 *            IF T(n) <= T(2*n) THEN
 *              EXIT;
 *            ENDIF
 *            swap(n, 2*n);
 *            n <- 2*n;
 *          ELSE
 *            IF T(n) <= T(2*n+1) THEN
 *              EXIT;
 *            ENDIF
 *            swap(n, 2*n+1);
 *            n <- 2*n+1;
 *          ENDIF
 *        ELSE
 *          // Only left child, right child not present.
 *          IF T(n) <= T(2*n) THEN
 *            EXIT;
 *          ENDIF
 *          swap(n, 2*n);
 *          n <- 2*n;
 *        ENDIF
 *      ENDWHILE
 *    ENDIF
 *  
* Proof that this removal algorithm respects the invariant is left to * the interested reader. Really, I am not going to prove it here. * * If you are interested, you can find this data structure and its * associated operations in most textbooks on algorithmics. * * @author Ole Husgaard * @author Dimitris Andreadis * @author Elias Ross * @author Adrian Brock * @version $Revision: 2787 $ */ public class HashedTimeoutPriorityQueueImpl implements TimeoutPriorityQueue { // Code commented out with the mark "INV:" are runtime checks // of invariants that are not needed for a production system. // For problem solving, you can remove these comments. // Multithreading notes: // // While a TimeoutImpl is enqueued, its index field contains the index // of the instance in the queue; that is, for 1 <= n <= size, // q[n].index = n. // Modifications of an enqueued TimeoutImpl instance may only happen // in code synchronized on the TimeoutFactory instance that has it // enqueued. // Modifications on the priority queue may only happen while running in // code synchronized on the TimeoutFactory instance that holds the queue. // When a TimeoutImpl instance is no longer enqueued, its index field // changes to one of the negative constants declared in the TimeoutImpl // class. // // Cancellation may race with the timeout. // To avoid problems with this, the TimeoutImpl index field is set to // TimeoutImpl.TIMEOUT when the TimeoutImpl is taken out of the queue. // Finally the index field is set to TimeoutImpl.DONE, and // the TimeoutImpl instance is discarded. /** The lock object */ private Object topLock = new Object(); /** The top element */ private TimeoutExtImpl top; /** The hashed queues */ private InternalPriorityQueue[] queues; private AtomicBoolean cancelled = new AtomicBoolean(false); /** * Create a new TimeoutPriorityQueueImpl. */ public HashedTimeoutPriorityQueueImpl() { queues = new InternalPriorityQueue[40]; for (int i = 0; i < queues.length; ++ i) queues[i] = new InternalPriorityQueue(); } public TimeoutExt offer(long time, TimeoutTarget target) { if (cancelled.get()) throw new IllegalStateException("TimeoutPriorityQueue has been cancelled"); if (time < 0) throw new IllegalArgumentException("Negative time"); if (target == null) throw new IllegalArgumentException("Null timeout target"); TimeoutExtImpl timeout = new TimeoutExtImpl(); timeout.time = time; timeout.target = target; int index = timeout.hashCode() % queues.length; return queues[index].offer(timeout); } public TimeoutExt take() { return poll(-1); } public TimeoutExt poll() { return poll(1); } public TimeoutExt poll(long wait) { long endWait = -1; if (wait > 0) endWait = System.currentTimeMillis() + wait; // Look for work synchronized (topLock) { while (cancelled.get() == false && (wait >= 0 || endWait == -1)) { if (top == null) { try { if (endWait == -1) topLock.wait(); else topLock.wait(wait); } catch (InterruptedException ex) { } } else { long now = System.currentTimeMillis(); if (top.time > now) { long waitForFirst = top.time - now; if (endWait != -1 && waitForFirst > wait) waitForFirst = wait; try { topLock.wait(waitForFirst); } catch (InterruptedException ex) { } } if (cancelled.get() == false && top != null && top.time <= System.currentTimeMillis()) { TimeoutExtImpl result = top; result.queue = null; result.index = TimeoutExtImpl.TIMEOUT; top = null; recalculateTop(false); return result; } } if (endWait != -1) wait = endWait - System.currentTimeMillis(); } } return null; } public TimeoutExt peek() { synchronized (topLock) { return top; } } public boolean remove(TimeoutExt timeout) { TimeoutExtImpl timeoutImpl = (TimeoutExtImpl) timeout; // Fast way of doing it InternalPriorityQueue queue = timeoutImpl.queue; if (queue != null && queue.remove(timeoutImpl)) return true; synchronized (topLock) { // Check the top element if (top == timeout) { top.done(); top = null; recalculateTop(true); return true; } // Double check, it might have been the top then // just got moved back into the queue queue = timeoutImpl.queue; if (queue != null) return queue.remove(timeoutImpl); } return false; } public void clear() { synchronized (topLock) { if (cancelled.get()) return; // cleanup queues for (int i = 1; i < queues.length; ++i) queues[i].clear(); // cleanup the top top = cleanupTimeoutExtImpl(top); } } public void cancel() { synchronized (topLock) { if (cancelled.get()) return; clear(); topLock.notifyAll(); } } public int size() { int size = 0; if (top != null) size =1; for (int i = 0; i < queues.length; ++i) size += queues[i].size(); return size; } /** * Whether the queue is cancelled * * @return true when cancelled */ public boolean isCancelled() { return cancelled.get(); } private void recalculateTop(boolean notify) { for (int i = 0; i < queues.length; ++i) queues[i].compareAndSwapWithTop(notify); } /** * Recursive cleanup of a TimeoutImpl * * @return null */ private TimeoutExtImpl cleanupTimeoutExtImpl(TimeoutExtImpl timeout) { if (timeout != null) timeout.target = null; return null; } /** * Debugging helper. */ private void assertExpr(boolean expr) { if (!expr) throw new IllegalStateException("***** assert failed *****"); } /** * Internal priority queue */ private class InternalPriorityQueue { /** The lock object */ private Object lock = new Object(); /** The size of the timeout queue. */ private int size; /** The timeouts */ private TimeoutExtImpl[] queue; /** * Create a new InternalPriorityQueue. */ InternalPriorityQueue() { queue = new TimeoutExtImpl[16]; size = 0; } TimeoutExt offer(TimeoutExtImpl timeout) { boolean checkTop = false; synchronized (lock) { // INV: checkTree(); // INV: assertExpr(size < queue.length); if (++size == queue.length) { TimeoutExtImpl[] newQ = new TimeoutExtImpl[2 * queue.length]; System.arraycopy(queue, 0, newQ, 0, queue.length); queue = newQ; } // INV: assertExpr(size < queue.length); // INV: assertExpr(queue[size] == null); queue[size] = timeout; timeout.queue = this; timeout.index = size; normalizeUp(size); if (timeout.index == 1) checkTop = true; // INV: checkTree(); } if (checkTop) { synchronized (topLock) { compareAndSwapWithTop(true); } } return timeout; } boolean compareAndSwapWithTop(boolean notify) { synchronized (lock) { if (size == 0) return false; if (top == null) { top = removeNode(1); top.queue = null; top.index = TimeoutExtImpl.TOP; if (notify) topLock.notify(); return top != null; } if (top.time > queue[1].time) { TimeoutExtImpl temp = top; top = queue[1]; top.queue = null; top.index = TimeoutExtImpl.TOP; queue[1] = temp; temp.queue = this; temp.index = 1; if (size > 1) normalizeDown(1); if (notify) topLock.notify(); } } return false; } boolean remove(TimeoutExt timeout) { synchronized (lock) { TimeoutExtImpl timeoutImpl = (TimeoutExtImpl) timeout; if (timeoutImpl.queue == this && timeoutImpl.index > 0) { // Active timeout, remove it. // INV: assertExpr(queue[timeoutImpl.index] == timeout); // INV: checkTree(); removeNode(timeoutImpl.index); // INV: checkTree(); timeoutImpl.queue = null; timeoutImpl.index = TimeoutExtImpl.DONE; // execution cancelled return true; } else { // has already been executed (DONE) or // is currently executing (TIMEOUT) return false; } } } public void clear() { synchronized (lock) { if (cancelled.get()) return; // cleanup queue for (int i = 1; i <= size; ++i) queue[i] = cleanupTimeoutExtImpl(queue[i]); } } public void cancel() { synchronized (lock) { if (cancelled.get()) return; clear(); } } public int size() { return size; } /** * A new node has been added at index index. * Normalize the tree by moving the new node up the tree. * * @return true if the tree was modified. */ private boolean normalizeUp(int index) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); // INV: assertExpr(queue[index] != null); if (index == 1) return false; // at root boolean ret = false; long t = queue[index].time; int p = index >> 1; while (queue[p].time > t) { // INV: assertExpr(queue[index].time == t); swap(p, index); ret = true; if (p == 1) break; // at root index = p; p >>= 1; } return ret; } void normalizeDown(int index) { long t = queue[index].time; int c = index << 1; while (c <= size) { // INV: assertExpr(q[index].time == t); TimeoutExtImpl l = queue[c]; // INV: assertExpr(l != null); // INV: assertExpr(l.index == c); if (c + 1 <= size) { // two children, swap with smallest TimeoutExtImpl r = queue[c + 1]; // INV: assertExpr(r != null); // INV: assertExpr(r.index == c+1); if (l.time <= r.time) { if (t <= l.time) break; // done swap(index, c); index = c; } else { if (t <= r.time) break; // done swap(index, c + 1); index = c + 1; } } else { // one child if (t <= l.time) break; // done swap(index, c); index = c; } c = index << 1; } } /** * Swap two nodes in the tree. * * @param a the first index * @param b the second index */ private void swap(int a, int b) { // INV: assertExpr(a > 0); // INV: assertExpr(a <= size); // INV: assertExpr(b > 0); // INV: assertExpr(b <= size); // INV: assertExpr(queue[a] != null); // INV: assertExpr(queue[b] != null); // INV: assertExpr(queue[a].index == a); // INV: assertExpr(queue[b].index == b); TimeoutExtImpl temp = queue[a]; queue[a] = queue[b]; queue[a].index = a; queue[b] = temp; queue[b].index = b; } /** * Remove a node from the tree and normalize. * * @param index the index in the queue * @return the removed node. */ private TimeoutExtImpl removeNode(int index) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); TimeoutExtImpl res = queue[index]; // INV: assertExpr(res != null); // INV: assertExpr(res.index == index); if (index == size) { --size; queue[index] = null; return res; } swap(index, size); // Exchange removed node with last leaf node --size; // INV: assertExpr(res.index == size + 1); queue[res.index] = null; if (normalizeUp(index)) return res; // Node moved up, so it shouldn't move down normalizeDown(index); return res; } /** * Check invariants of the queue. */ void checkTree() { assertExpr(size >= 0); assertExpr(size < queue.length); assertExpr(queue[0] == null); if (size > 0) { assertExpr(queue[1] != null); assertExpr(queue[1].index == 1); assertExpr(queue[1].queue == this); for (int i = 2; i <= size; ++i) { assertExpr(queue[i] != null); assertExpr(queue[i].index == i); assertExpr(queue[i].queue == this); assertExpr(queue[i >> 1].time <= queue[i].time); // parent fires first } for (int i = size + 1; i < queue.length; ++i) assertExpr(queue[i] == null); } } } /** * Our private Timeout implementation. */ private class TimeoutExtImpl implements TimeoutExt { /** Top */ static final int TOP = 0; /** Done */ static final int DONE = -1; /** In timeout */ static final int TIMEOUT = -2; /** The internal priority queue */ InternalPriorityQueue queue; /** Index in the queue */ int index; /** Time of the timeout */ long time; /** The timeout target */ TimeoutTarget target; public long getTime() { return time; } public TimeoutTarget getTimeoutTarget() { return target; } public void done() { queue = null; index = DONE; } public boolean cancel() { return remove(this); } } public String dump() { JBossStringBuilder buffer = new JBossStringBuilder(); buffer.append("TOP="); if (top == null) buffer.append("null"); else buffer.append(top.time); buffer.append(" size=").append(size()).append('\n'); for (int i = 0; i < queues.length; ++i) { buffer.append(i).append("="); for (int j = 1; j <= queues[i].size; ++j) buffer.append(queues[i].queue[j].time).append(','); buffer.append('\n'); } return buffer.toString(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutPriorityQueue.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/TimeoutPriori0000644000175000017500000000523310774222622033403 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.timeout; /** * TimeoutPriorityQueue. * * @author Adrian Brock * @version $Revision: 2787 $ */ public interface TimeoutPriorityQueue { /** * Add a timeout to the queue * * @param time the time of the timeout * @param target the timeout target * @return timeout when it was added to the queue, false otherwise */ TimeoutExt offer(long time, TimeoutTarget target); /** * Take a timeout when it times out * * @return the top the queue or null if the queue is cancelled */ TimeoutExt take(); /** * Retrieves and removes the top of the queue if it times out * or null if there is no such element * * @return the top the queue or null if the queue is empty */ TimeoutExt poll(); /** * Retrieves and removes the top of the queue if it times out * or null if there is no such element * * @param wait how to long to wait in milliseconds * if the queue is empty * @return the top of the queue or null if the queue is empty */ TimeoutExt poll(long wait); /** * Retrieves but does not remove the top of the queue * or null if there is no such element * * @return the top of the queue or null if the queue is empty */ TimeoutExt peek(); /** * Removes the passed timeout from the queue * @param timeout * * @return true when the timeout was removed */ boolean remove(TimeoutExt timeout); /** * Clears the queue */ void clear(); /** * Cancels the queue */ void cancel(); /** * @return the size of the queue */ int size(); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/timeout/package.html0000644000175000017500000000144310470642610033121 0ustar twernertwerner

Timeout utilties.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/TimedCachePolicy.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/TimedCachePolicy.java0000644000175000017500000003134510774222622033173 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /** An implementation of a timed cache. This is a cache whose entries have a limited lifetime with the ability to refresh their lifetime. The entries managed by the cache implement the TimedCachePolicy.TimedEntry interface. If an object inserted into the cache does not implement this interface, it will be wrapped in a DefaultTimedEntry and will expire without the possibility of refresh after getDefaultLifetime() seconds. This is a lazy cache policy in that objects are not checked for expiration until they are accessed. @author Scott Stark. @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class TimedCachePolicy extends TimerTask /* A legacy base class that is no longer used as this level */ implements CachePolicy { /** The interface that cache entries support. */ public static interface TimedEntry { /** Initializes an entry with the current cache time. This is called when the entry is first inserted into the cache so that entries do not have to know the absolute system time. * @param now */ public void init(long now); /** Is the entry still valid basis the current time * @param now @return true if the entry is within its lifetime, false if it is expired. */ public boolean isCurrent(long now); /** Attempt to extend the entry lifetime by refreshing it. @return true if the entry was refreshed successfully, false otherwise. */ public boolean refresh(); /** Notify the entry that it has been removed from the cache. */ public void destroy(); /** @return the value component of the TimedEntry. This may or may not be the TimedEntry implementation. */ public Object getValue(); } protected static Timer resolutionTimer = new Timer(true); /** The map of cached TimedEntry objects. */ protected Map entryMap; /** The lifetime in seconds to use for objects inserted that do not implement the TimedEntry interface. */ protected int defaultLifetime; /** A flag indicating if entryMap should be synchronized */ protected boolean threadSafe; /** The caches notion of the current time */ protected long now; /** The resolution in seconds of the cach current time */ protected int resolution; /** */ protected ResolutionTimer theTimer; /** Creates a new TimedCachePolicy with a default entry lifetime of 30 mins that does not synchronized access to its policy store and uses a 60 second resolution. */ public TimedCachePolicy() { this(30*60, false, 0); } /** Creates a new TimedCachePolicy with the given default entry lifetime that does not synchronized access to its policy store and uses a 60 second resolution. * @param defaultLifetime */ public TimedCachePolicy(int defaultLifetime) { this(defaultLifetime, false, 0); } /** Creates a new TimedCachePolicy with the given default entry lifetime that does/does not synchronized access to its policy store depending on the value of threadSafe. @param defaultLifetime - the lifetime in seconds to use for objects inserted that do not implement the TimedEntry interface. @param threadSafe - a flag indicating if the cach store should be synchronized to allow correct operation under multi-threaded access. If true, the cache store is synchronized. If false the cache store is unsynchronized and the cache is not thread safe. @param resolution - the resolution in seconds of the cache timer. A cache does not query the system time on every get() invocation. Rather the cache updates its notion of the current time every 'resolution' seconds. */ public TimedCachePolicy(int defaultLifetime, boolean threadSafe, int resolution) { this.defaultLifetime = defaultLifetime; this.threadSafe = threadSafe; if( resolution <= 0 ) resolution = 60; this.resolution = resolution; } // Service implementation ---------------------------------------------- /** Initializes the cache for use. Prior to this the cache has no store. */ public void create() { if( threadSafe ) entryMap = Collections.synchronizedMap(new HashMap()); else entryMap = new HashMap(); now = System.currentTimeMillis(); } /** Schedules this with the class resolutionTimer Timer object for execution every resolution seconds. */ public void start() { theTimer = new ResolutionTimer(); resolutionTimer.scheduleAtFixedRate(theTimer, 0, 1000*resolution); } /** Stop cancels the resolution timer and flush()es the cache. */ public void stop() { theTimer.cancel(); flush(); } /** Clears the cache of all entries. */ public void destroy() { entryMap.clear(); } // --- Begin CachePolicy interface methods /** Get the cache value for key if it has not expired. If the TimedEntry is expired its destroy method is called and then removed from the cache. @return the TimedEntry value or the original value if it was not an instance of TimedEntry if key is in the cache, null otherwise. */ public Object get(Object key) { TimedEntry entry = (TimedEntry) entryMap.get(key); if( entry == null ) return null; if( entry.isCurrent(now) == false ) { // Try to refresh the entry if( entry.refresh() == false ) { // Failed, remove the entry and return null entry.destroy(); entryMap.remove(key); return null; } } Object value = entry.getValue(); return value; } /** Get the cache value for key. This method does not check to see if the entry has expired. @return the TimedEntry value or the original value if it was not an instancee of TimedEntry if key is in the cache, null otherwise. */ public Object peek(Object key) { TimedEntry entry = (TimedEntry) entryMap.get(key); Object value = null; if( entry != null ) value = entry.getValue(); return value; } /** Insert a value into the cache. In order to have the cache entry reshresh itself value would have to implement TimedEntry and implement the required refresh() method logic. @param key - the key for the cache entry @param value - Either an instance of TimedEntry that will be inserted without change, or an abitrary value that will be wrapped in a non-refreshing TimedEntry. */ public void insert(Object key, Object value) { if( entryMap.containsKey(key) ) throw new IllegalStateException("Attempt to insert duplicate entry"); TimedEntry entry = null; if( (value instanceof TimedEntry) == false ) { // Wrap the value in a DefaultTimedEntry entry = new DefaultTimedEntry(defaultLifetime, value); } else { entry = (TimedEntry) value; } entry.init(now); entryMap.put(key, entry); } /** Remove the entry associated with key and call destroy on the entry if found. */ public void remove(Object key) { TimedEntry entry = (TimedEntry) entryMap.remove(key); if( entry != null ) entry.destroy(); } /** Remove all entries from the cache. */ public void flush() { Map tmpMap = null; synchronized( this ) { tmpMap = entryMap; if( threadSafe ) entryMap = Collections.synchronizedMap(new HashMap()); else entryMap = new HashMap(); } // Notify the entries of their removal Iterator iter = tmpMap.values().iterator(); while( iter.hasNext() ) { TimedEntry entry = (TimedEntry) iter.next(); entry.destroy(); } tmpMap.clear(); } public int size() { return entryMap.size(); } // --- End CachePolicy interface methods /** Get the list of keys for entries that are not expired. * * @return A List of the keys corresponding to valid entries */ public List getValidKeys() { ArrayList validKeys = new ArrayList(); synchronized( entryMap ) { Iterator iter = entryMap.entrySet().iterator(); while( iter.hasNext() ) { Map.Entry entry = (Map.Entry) iter.next(); TimedEntry value = (TimedEntry) entry.getValue(); if( value.isCurrent(now) == true ) validKeys.add(entry.getKey()); } } return validKeys; } /** Get the default lifetime of cache entries. @return default lifetime in seconds of cache entries. */ public int getDefaultLifetime() { return defaultLifetime; } /** Set the default lifetime of cache entries for new values added to the cache. @param defaultLifetime - lifetime in seconds of cache values that do not implement TimedEntry. */ public synchronized void setDefaultLifetime(int defaultLifetime) { this.defaultLifetime = defaultLifetime; } /** * Get the frequency of the current time snapshot. * @return the current timer resolution in seconds. */ public int getResolution() { return resolution; } /** Set the cache timer resolution * @param resolution - the resolution in seconds of the cache timer. A cache does not query the system time on every get() invocation. Rather the cache updates its notion of the current time every 'resolution' seconds. */ public synchronized void setResolution(int resolution) { if( resolution <= 0 ) resolution = 60; if( resolution != this.resolution ) { this.resolution = resolution; theTimer.cancel(); theTimer = new ResolutionTimer(); resolutionTimer.scheduleAtFixedRate(theTimer, 0, 1000*resolution); } } /** The TimerTask run method. It updates the cache time to the current system time. */ public void run() { now = System.currentTimeMillis(); } /** Get the cache time. @return the cache time last obtained from System.currentTimeMillis() */ public long currentTimeMillis() { return now; } /** Get the raw TimedEntry for key without performing any expiration check. * @param key @return the TimedEntry value associated with key if one exists, null otherwise. */ public TimedEntry peekEntry(Object key) { TimedEntry entry = (TimedEntry) entryMap.get(key); return entry; } /** The default implementation of TimedEntry used to wrap non-TimedEntry objects inserted into the cache. */ static class DefaultTimedEntry implements TimedEntry { long expirationTime; Object value; DefaultTimedEntry(long lifetime, Object value) { this.expirationTime = 1000 * lifetime; this.value = value; } public void init(long now) { expirationTime += now; } public boolean isCurrent(long now) { return expirationTime > now; } public boolean refresh() { return false; } public void destroy() { } public Object getValue() { return value; } } /** */ private class ResolutionTimer extends TimerTask { public void run() { TimedCachePolicy.this.run(); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/WaitSemaphore.java0000644000175000017500000000536010470642610032567 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Wait exclusive semaphore with wait - notify primitives * * @author Simone Bordet * @version $Revision: 1958 $ */ public class WaitSemaphore extends Semaphore implements WaitSync { // Constants ----------------------------------------------------- private final static int MAX_USERS_ALLOWED = 1; // Attributes ---------------------------------------------------- private int m_waiters; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public WaitSemaphore() { super(MAX_USERS_ALLOWED); } // Public -------------------------------------------------------- public void doWait() throws InterruptedException { synchronized (this) { release(); ++m_waiters; waitImpl(this); --m_waiters; acquire(); } } public void doNotify() throws InterruptedException { synchronized (this) { if (getWaiters() > 0) { acquire(); notify(); release(); } } } public int getWaiters() { synchronized (this) { return m_waiters; } } // Object overrides --------------------------------------------------- public String toString() { return super.toString() + " - " + m_waiters; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Throwables.java0000644000175000017500000000342110470642610032125 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintStream; import java.io.ByteArrayOutputStream; /** * A collection of Throwable utilities. * * @version $Revision: 1958 $ * @author Jason Dillon */ public final class Throwables { /** * Return a string that consists of the stack trace of the given * Throwable. * * @param t Throwable to get stack trace from. * @return Throwable stack trace as a string. */ public static String toString(final Throwable t) { ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(output); t.printStackTrace(stream); return output.toString(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/FieldInstance.java0000644000175000017500000000616510470642610032533 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.lang.reflect.Field; /** * A FieldInstance refers to a specific reflected field on an object. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FieldInstance { /** Field */ protected final Field field; /** Instance */ protected final Object instance; /** * Construct a new field instance. * * @param instance The instance object the given field belongs to. * @param fieldName The name of the field to find in the instance. * * @throws NullArgumentException Instance or fieldName is null. * @throws NoSuchFieldException */ public FieldInstance(final Object instance, final String fieldName) throws NoSuchFieldException { if (instance == null) throw new NullArgumentException("instance"); if (fieldName == null) throw new NullArgumentException("fieldName"); // Get the field object field = instance.getClass().getField(fieldName); // Check if the field is assignable ? if (! field.getDeclaringClass().isAssignableFrom(instance.getClass())) throw new IllegalArgumentException ("field does not belong to instance class"); this.instance = instance; } /** * Get the field. * * @return Field. */ public final Field getField() { return field; } /** * Get the instance. * * @return Instance. */ public final Object getInstance() { return instance; } /** * Get the value of the field instance. * * @return Field value. * * @throws IllegalAccessException Failed to get field value. */ public final Object get() throws IllegalAccessException { return field.get(instance); } /** * Set the value of the field instance * * @param value Field value. * * @throws IllegalAccessException Failed to set field value. */ public final void set(final Object value) throws IllegalAccessException { field.set(instance, value); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/StopWatch.java0000644000175000017500000002067510776226110031743 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; /** * Simulates a stop watch with a lap counter. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class StopWatch implements Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = 4628094303187435707L; /** Total time */ protected long total = 0; /** Start time */ protected long start = -1; /** Stop time */ protected long stop = -1; /** The lap count */ protected int count = 0; /** Is the watch started */ protected boolean running = false; /** * Default constructor. */ public StopWatch() {} /** * Construct a StopWatch. * * @param running Start the watch */ public StopWatch(final boolean running) { if (running) start(); } /** * Start the watch. * * @param reset True to reset the watch prior to starting. */ public void start(final boolean reset) { if (!running) { if (reset) reset(); start = System.currentTimeMillis(); running = true; } } /** * Start the watch. */ public void start() { start(false); } /** * Stop the watch. * * @return Elapsed time or 0 if the watch was never started. */ public long stop() { long lap = 0; if (running) { count++; stop = System.currentTimeMillis(); lap = stop - start; total += lap; running = false; } return lap; } /** * Reset the watch. */ public void reset() { start = -1; stop = -1; total = 0; count = 0; running = false; } /** * Get the lap count. * * @return The lap count. */ public int getLapCount() { return count; } /** * Get the elapsed lap time since the watch was started. * * @return Elapsed lap time or 0 if the watch was never started */ public long getLapTime() { if (start == -1) { return 0; } else if (running) { return System.currentTimeMillis() - start; } else { return stop - start; } } /** * Get the average lap time since the watch was started. * * @return Average lap time since the watch was started. */ public long getAverageLapTime() { return (count == 0) ? 0 : getLapTime() / getLapCount(); } /** * Get the elapsed time since the watch was created or last reset. * * @return Elapsed time or 0 if the watch was never started. */ public long getTime() { if (start == -1) { return 0; } else if (running) { return total + System.currentTimeMillis() - start; } else { return total; } } /** * Check if the watch is running. * * @return True if the watch is running. */ public boolean isRunning() { return running; } /** * Return a string representation. */ public String toString() { StringBuffer buff = new StringBuffer(); if (running) { // the watch has not been stopped formatElapsedTime(buff, getTime()); // add the current lap time too if there is more than one lap if (count >= 1) { buff.append(", count=").append(count); buff.append(", current="); formatElapsedTime(buff, getLapTime()); } } else { // the watch has been stopped formatElapsedTime(buff, getTime()); // add extra info if there is more than one lap if (count > 1) { buff.append(", count=").append(count); buff.append(", average="); formatElapsedTime(buff, getAverageLapTime()); } } return buff.toString(); } private void formatElapsedTime(final StringBuffer buff, final long lapsed) { long m = lapsed / 60000; if (m != 0) { buff.append(m).append("m:"); } long s = (lapsed - 60000 * m) / 1000; if (s != 0) { buff.append(s).append("s:"); } // ms is always there, even if it was 0 too long ms = (lapsed - 60000 * m - 1000 * s); buff.append(ms).append("ms"); } /** * Return a cloned copy of this object. * * @return A cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ///////////////////////////////////////////////////////////////////////// // Wrappers // ///////////////////////////////////////////////////////////////////////// /** * Base wrapper class for other wrappers. */ private static class Wrapper extends StopWatch { /** The serialVersionUID */ private static final long serialVersionUID = 6859401939735540773L; protected StopWatch watch; public Wrapper(final StopWatch watch) { this.watch = watch; } public void start(final boolean reset) { watch.start(reset); } public void start() { watch.start(); } public long stop() { return watch.stop(); } public void reset() { watch.reset(); } public long getLapTime() { return watch.getLapTime(); } public long getAverageLapTime() { return watch.getAverageLapTime(); } public int getLapCount() { return watch.getLapCount(); } public long getTime() { return watch.getTime(); } public boolean isRunning() { return watch.isRunning(); } public String toString() { return watch.toString(); } } /** * Return a synchronized stop watch. * * @param watch StopWatch to synchronize. * @return Synchronized stop watch. */ public static StopWatch makeSynchronized(final StopWatch watch) { return new Wrapper(watch) { /** The serialVersionUID */ private static final long serialVersionUID = -6284244000894114817L; public synchronized void start(final boolean reset) { this.watch.start(reset); } public synchronized void start() { this.watch.start(); } public synchronized long stop() { return this.watch.stop(); } public synchronized void reset() { this.watch.reset(); } public synchronized long getLapTime() { return this.watch.getLapTime(); } public synchronized long getAverageLapTime() { return this.watch.getAverageLapTime(); } public synchronized int getLapCount() { return this.watch.getLapCount(); } public synchronized long getTime() { return this.watch.getTime(); } public synchronized boolean isRunning() { return this.watch.isRunning(); } public synchronized String toString() { return this.watch.toString(); } }; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/0000755000175000017500000000000011105642365032246 5ustar twernertwerner././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/AtomicIntegerEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Atomic0000644000175000017500000000300111033507723033375 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.util.concurrent.atomic.AtomicInteger; /** * AtomicInteger property editor. * * @author Ales Justin */ public class AtomicIntegerEditor extends PropertyEditorSupport { public void setAsText(final String text) { if (PropertyEditors.isNull(text)) setValue(null); else setValue(new AtomicInteger(Integer.parseInt(text))); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/IntArrayEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/IntArr0000644000175000017500000000412510470642610033367 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.util.StringTokenizer; /** * A property editor for int[]. * * @version $Revision: 1958 $ */ public class IntArrayEditor extends PropertyEditorSupport { /** Build a int[] from comma or eol seperated elements * */ public void setAsText(final String text) { StringTokenizer stok = new StringTokenizer(text, ",\r\n"); int[] theValue = new int[stok.countTokens()]; int i = 0; while (stok.hasMoreTokens()) { theValue[i++] = Integer.decode(stok.nextToken()).intValue(); } setValue(theValue); } /** * @return a comma seperated string of the array elements */ public String getAsText() { int[] theValue = (int[]) getValue(); StringBuffer text = new StringBuffer(); int length = theValue == null ? 0 : theValue.length; for(int n = 0; n < length; n ++) { if (n > 0) text.append(','); text.append(theValue[n]); } return text.toString(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ElementEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Elemen0000644000175000017500000000275310774222622033406 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import org.w3c.dom.Document; /** * A property editor for {@link org.w3c.dom.Element}. * * @version $Revision: 2787 $ * @author Elias Ross */ public class ElementEditor extends DocumentEditor { /** * Sets as an Element created by a String. */ public void setAsText(String text) { Document d = getAsDocument(text); setValue(d.getDocumentElement()); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/AtomicLongEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Atomic0000644000175000017500000000276111033507723033411 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.util.concurrent.atomic.AtomicLong; /** * AtomicLong property editor. * * @author Ales Justin */ public class AtomicLongEditor extends PropertyEditorSupport { public void setAsText(final String text) { if (PropertyEditors.isNull(text)) setValue(null); else setValue(new AtomicLong(Long.parseLong(text))); } }././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/CharacterEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Charac0000644000175000017500000000330510470642610033350 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor for {@link java.lang.Character}. * * @todo REVIEW: look at possibly parsing escape sequences? * @version $Revision: 1958 $ * @author adrian@jboss.org */ public class CharacterEditor extends PropertyEditorSupport { public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } if (text.length() != 1) throw new IllegalArgumentException("Too many (" + text.length() + ") characters: '" + text + "'"); Object newValue = new Character(text.charAt(0)); setValue(newValue); } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/BlockingModeEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Blocki0000644000175000017500000000314510470642610033374 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import org.jboss.util.threadpool.BlockingMode; /** * A property editor for {@link org.jboss.util.threadpool.BlockingMode} enum. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class BlockingModeEditor extends TextPropertyEditorSupport { /** * Returns a BlockingMode for the input object converted to a string. * * @return a BlockingMode enum instance * */ public Object getValue() { String text = getAsText(); BlockingMode mode = BlockingMode.toBlockingMode(text); return mode; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/PropertiesEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Proper0000644000175000017500000000540710774222622033447 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import org.jboss.util.NestedRuntimeException; import org.jboss.util.StringPropertyReplacer; /** * A property editor for {@link java.util.Properties}. * * @author Jason Dillon * @author Scott.Stark@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class PropertiesEditor extends TextPropertyEditorSupport { /** * Returns a Properties object initialized with current getAsText value * interpretted as a .properties file contents. This replaces any * references of the form ${x} with the corresponding system property. * * @return a Properties object * * @throws NestedRuntimeException An IOException occured. */ public Object getValue() { try { // Load the current key=value properties into a Properties object String propsText = getAsText(); Properties rawProps = new Properties(System.getProperties()); ByteArrayInputStream bais = new ByteArrayInputStream(propsText.getBytes()); rawProps.load(bais); // Now go through the rawProps and replace any ${x} refs Properties props = new Properties(); Iterator keys = rawProps.keySet().iterator(); while( keys.hasNext() ) { String key = (String) keys.next(); String value = rawProps.getProperty(key); String value2 = StringPropertyReplacer.replaceProperties(value, rawProps); props.setProperty(key, value2); } rawProps.clear(); return props; } catch (IOException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/LocaleEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Locale0000644000175000017500000000277410772712041033400 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import org.jboss.util.Strings; /** * Locale editor. * * @author Ales Justin */ public class LocaleEditor extends PropertyEditorSupport { public void setAsText(String text) { setValue(Strings.parseLocaleString(text)); } public String getAsText() { Object value = getValue(); return (value != null ? value.toString() : ""); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/IntegerEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Intege0000644000175000017500000000307710470642610033410 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** A property editor for {@link java.lang.Integer}. * * @version $Revision: 1958 $ * @author Scott.Stark@jboss.org */ public class IntegerEditor extends PropertyEditorSupport { /** Map the argument text into and Integer using Integer.decode. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Integer.decode(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ByteArrayEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ByteAr0000644000175000017500000000306110470642610033354 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** A property editor for byte[]. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class ByteArrayEditor extends PropertyEditorSupport { /** Map the argument text into and Byte using Byte.decode. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text, false, false)) { setValue(null); return; } Object newValue = text.getBytes(); setValue(newValue); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/LongEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/LongEd0000644000175000017500000000307210470642610033340 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor for {@link Integer}. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class LongEditor extends PropertyEditorSupport { /** * Map the argument text into and Integer using Integer.valueOf. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Long.valueOf(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ShortEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ShortE0000644000175000017500000000306610470642610033377 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** A property editor for {@link java.lang.Short}. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class ShortEditor extends PropertyEditorSupport { /** Map the argument text into and Short using Short.decode. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Short.decode(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/URIEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/URIEdi0000644000175000017500000000342510774222622033257 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.net.URISyntaxException; import org.jboss.util.NestedRuntimeException; import org.jboss.util.Strings; /** * A property editor for {@link java.net.URI}. * * @version $Revision: 2787 $ * @author Dimitris Andreadis */ public class URIEditor extends TextPropertyEditorSupport { /** * Returns a URI for the input object converted to a string. * * @return a URI object * * @throws NestedRuntimeException An MalformedURLException occured. */ public Object getValue() { try { return Strings.toURI(getAsText()); } catch (URISyntaxException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ByteEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ByteEd0000644000175000017500000000301710470642610033343 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** A property editor for {@link java.lang.Byte}. * * @version $Revision: 1958 $ */ public class ByteEditor extends PropertyEditorSupport { /** Map the argument text into and Byte using Byte.decode. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Byte.decode(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/URLEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/URLEdi0000644000175000017500000000342510470642610033256 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.net.MalformedURLException; import org.jboss.util.NestedRuntimeException; import org.jboss.util.Strings; /** * A property editor for {@link java.net.URL}. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class URLEditor extends TextPropertyEditorSupport { /** * Returns a URL for the input object converted to a string. * * @return a URL object * * @throws NestedRuntimeException An MalformedURLException occured. */ public Object getValue() { try { return Strings.toURL(getAsText()); } catch (MalformedURLException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/AtomicBooleanEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Atomic0000644000175000017500000000300311033507723033377 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.util.concurrent.atomic.AtomicBoolean; /** * AtomicBoolean property editor. * * @author Ales Justin */ public class AtomicBooleanEditor extends PropertyEditorSupport { public void setAsText(final String text) { if (PropertyEditors.isNull(text)) setValue(null); else setValue(new AtomicBoolean(Boolean.parseBoolean(text))); } }././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ClassArrayEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ClassA0000755000175000017500000000524010774222622033344 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.util.ArrayList; import java.util.StringTokenizer; import java.beans.PropertyEditorSupport; /** A property editor for Class[]. * * @version $Revision: 2787 $ * @author Scott.Stark@jboss.org */ public class ClassArrayEditor extends PropertyEditorSupport { /** Build a Class[] from a comma/whitespace seperated list of classes * @param text - the class name list */ public void setAsText(final String text) throws IllegalArgumentException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); StringTokenizer tokenizer = new StringTokenizer(text, ", \t\r\n"); ArrayList> classes = new ArrayList>(); while( tokenizer.hasMoreTokens() == true ) { String name = tokenizer.nextToken(); try { Class c = loader.loadClass(name); classes.add(c); } catch(ClassNotFoundException e) { throw new IllegalArgumentException("Failed to find class: "+name); } } Class[] theValue = new Class[classes.size()]; classes.toArray(theValue); setValue(theValue); } /** * @return a comma seperated string of the class array */ public String getAsText() { Class[] theValue = (Class[]) getValue(); StringBuffer text = new StringBuffer(); int length = theValue == null ? 0 : theValue.length; for(int n = 0; n < length; n ++) { text.append(theValue[n].getName()); text.append(','); } // Remove the trailing ',' text.setLength(text.length()-1); return text.toString(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ClassEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/ClassE0000644000175000017500000000354210774222622033350 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import org.jboss.util.NestedRuntimeException; /** * A property editor for {@link java.lang.Class}. * * @version $Revision: 2787 $ * @author Jason Dillon */ public class ClassEditor extends TextPropertyEditorSupport { /** * Returns a Class for the input object converted to a string. * * @return a Class object * * @throws NestedRuntimeException Failed to create Class instance. */ public Object getValue() { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String classname = getAsText(); Class type = loader.loadClass(classname); return type; } catch (Exception e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/FloatEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/FloatE0000644000175000017500000000273210470642610033344 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor for {@link Integer}. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class FloatEditor extends PropertyEditorSupport { /** * Map the argument text into and Integer using Integer.valueOf. */ public void setAsText(final String text) { Object newValue = Float.valueOf(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/InetAddressEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/InetAd0000644000175000017500000000434110470642610033334 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.net.InetAddress; import java.net.UnknownHostException; import org.jboss.util.NestedRuntimeException; import org.jboss.util.StringPropertyReplacer; /** * A property editor for {@link java.net.InetAddress}. * * @version $Revision: 1958 $ * @author Adrian Brock */ public class InetAddressEditor extends TextPropertyEditorSupport { /** * Returns a InetAddress for the input object converted to a string. * * @return an InetAddress * * @throws NestedRuntimeException An UnknownHostException occured. */ public Object getValue() { try { String text = getAsText(); if (text == null) { return null; } if (text.startsWith("/")) { // seems like localhost sometimes will look like: // /127.0.0.1 and the getByNames barfs on the slash - JGH text = text.substring(1); } return InetAddress.getByName(StringPropertyReplacer.replaceProperties(text)); } catch (UnknownHostException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/StringArrayEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/String0000644000175000017500000000665210774222622033451 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.util.ArrayList; import java.util.regex.Pattern; /** * A property editor for String[]. The text format of a string array is a * comma or \n, \r seperated list with \, representing an escaped comma to * include in the string element. * * @version $Revision: 2787 $ * @author Jason Dillon * @author Scott.Stark@jboss.org */ public class StringArrayEditor extends PropertyEditorSupport { Pattern commaDelim = Pattern.compile("','|[^,\r\n]+"); static String[] parseList(String text) { ArrayList list = new ArrayList(); StringBuffer tmp = new StringBuffer(); for(int n = 0; n < text.length(); n ++) { char c = text.charAt(n); switch( c) { case '\\': tmp.append(c); if( n < text.length() && text.charAt(n+1) == ',' ) { tmp.setCharAt(tmp.length()-1, ','); n ++; } break; case ',': case '\n': case '\r': if( tmp.length() > 0 ) list.add(tmp.toString()); tmp.setLength(0); break; default: tmp.append(c); break; } } if( tmp.length() > 0 ) list.add(tmp.toString()); String[] x = new String[list.size()]; list.toArray(x); return x; } /** Build a String[] from comma or eol seperated elements with a \, * representing a ',' to include in the current string element. * */ public void setAsText(final String text) { String[] theValue = parseList(text); setValue(theValue); } /** * @return a comma seperated string of the array elements */ public String getAsText() { String[] theValue = (String[]) getValue(); StringBuffer text = new StringBuffer(); int length = theValue == null ? 0 : theValue.length; for(int n = 0; n < length; n ++) { String s = theValue[n]; if( s.equals(",") ) text.append('\\'); text.append(s); text.append(','); } // Remove the trailing ',' if( text.length() > 0 ) text.setLength(text.length()-1); return text.toString(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/StringEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/String0000644000175000017500000000330710470642610033437 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor for {@link java.lang.String}. * * It is really a no-op but it is hoped to provide * slightly better performance, by avoiding the continuous * lookup/failure of a property editor for plain Strings * within the org.jboss.util.propertyeditor package, * before falling back to the jdk provided String editor. * * @author Dimitris Andreadis * @version $Revision: 1958 $ */ public class StringEditor extends PropertyEditorSupport { /** * Keep the provided String as is. */ public void setAsText(String text) { setValue(text); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/PropertyEditors.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Proper0000644000175000017500000004003510774222622033443 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import org.jboss.logging.Logger; import org.jboss.util.Classes; /** * A collection of PropertyEditor utilities. Provides the same interface * as PropertyEditorManager plus more... * *

Installs the default PropertyEditors. * * @author Jason Dillon * @author Scott Stark * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class PropertyEditors { /** The Logger object */ private static Logger log = Logger.getLogger(PropertyEditors.class); /** The null string */ private static final String NULL = "null"; /** Whether we handle nulls */ private static boolean disableIsNull = false; /** Whether or not initialization of the editor search path has been done */ private static boolean initialized = false; static { init(); } /** * Augment the PropertyEditorManager search path to incorporate the JBoss * specific editors by appending the org.jboss.util.propertyeditor package * to the PropertyEditorManager editor search path. */ public synchronized static void init() { if( initialized == false ) { AccessController.doPrivileged(Initialize.instance); initialized = true; } } /** * Whether a string is interpreted as the null value, * including the empty string. * * @param value the value * @return true when the string has the value null */ public static final boolean isNull(final String value) { return isNull(value, true, true); } /** * Whether a string is interpreted as the null value * * @param value the value * @param trim whether to trim the string * @param empty whether to include the empty string as null * @return true when the string has the value null */ public static final boolean isNull(final String value, final boolean trim, final boolean empty) { // For backwards compatibility if (disableIsNull) return false; // No value? if (value == null) return true; // Trim the text when requested String trimmed = trim ? value.trim() : value; // Is the empty string null? if (empty && trimmed.length() == 0) return true; // Just check it. return NULL.equalsIgnoreCase(trimmed); } /** * Will the standard editors return null from their * {@link PropertyEditor#setAsText(String)} method for non-primitive targets? * * @return True if nulls can be returned; false otherwise. */ public static boolean isNullHandlingEnabled() { return !disableIsNull; } /** * Locate a value editor for a given target type. * * @param type The class of the object to be edited. * @return An editor for the given type or null if none was found. */ public static PropertyEditor findEditor(final Class type) { return PropertyEditorManager.findEditor(type); } /** * Locate a value editor for a given target type. * * @param typeName The class name of the object to be edited. * @return An editor for the given type or null if none was found. * @throws ClassNotFoundException when the class could not be found */ public static PropertyEditor findEditor(final String typeName) throws ClassNotFoundException { // see if it is a primitive type first Class type = Classes.getPrimitiveTypeForName(typeName); if (type == null) { // nope try look up ClassLoader loader = Thread.currentThread().getContextClassLoader(); type = loader.loadClass(typeName); } return PropertyEditorManager.findEditor(type); } /** * Get a value editor for a given target type. * * @param type The class of the object to be edited. * @return An editor for the given type. * * @throws RuntimeException No editor was found. */ public static PropertyEditor getEditor(final Class type) { PropertyEditor editor = findEditor(type); if (editor == null) { throw new RuntimeException("No property editor for type: " + type); } return editor; } /** * Get a value editor for a given target type. * * @param typeName The class name of the object to be edited. * @return An editor for the given type. * * @throws RuntimeException No editor was found. * @throws ClassNotFoundException when the class is not found */ public static PropertyEditor getEditor(final String typeName) throws ClassNotFoundException { PropertyEditor editor = findEditor(typeName); if (editor == null) { throw new RuntimeException("No property editor for type: " + typeName); } return editor; } /** * Register an editor class to be used to editor values of a given target class. * * @param type The class of the objetcs to be edited. * @param editorType The class of the editor. */ public static void registerEditor(final Class type, final Class editorType) { PropertyEditorManager.registerEditor(type, editorType); } /** * Register an editor class to be used to editor values of a given target class. * * @param typeName The classname of the objetcs to be edited. * @param editorTypeName The class of the editor. * @throws ClassNotFoundException when the class could not be found */ public static void registerEditor(final String typeName, final String editorTypeName) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class type = loader.loadClass(typeName); Class editorType = loader.loadClass(editorTypeName); PropertyEditorManager.registerEditor(type, editorType); } /** Convert a string value into the true value for typeName using the * PropertyEditor associated with typeName. * * @param text the string represention of the value. This is passed to * the PropertyEditor.setAsText method. * @param typeName the fully qualified class name of the true value type * @return the PropertyEditor.getValue() result * @exception ClassNotFoundException thrown if the typeName class cannot * be found * @exception IntrospectionException thrown if a PropertyEditor for typeName * cannot be found */ public static Object convertValue(String text, String typeName) throws ClassNotFoundException, IntrospectionException { // see if it is a primitive type first Class typeClass = Classes.getPrimitiveTypeForName(typeName); if (typeClass == null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); typeClass = loader.loadClass(typeName); } PropertyEditor editor = PropertyEditorManager.findEditor(typeClass); if (editor == null) { throw new IntrospectionException ("No property editor for type=" + typeClass); } editor.setAsText(text); return editor.getValue(); } /** * This method takes the properties found in the given beanProps * to the bean using the property editor registered for the property. * Any property in beanProps that does not have an associated java bean * property will result in an IntrospectionException. The string property * values are converted to the true java bean property type using the * java bean PropertyEditor framework. If a property in beanProps does not * have a PropertyEditor registered it will be ignored. * * @param bean - the java bean instance to apply the properties to * @param beanProps - map of java bean property name to property value. * @throws IntrospectionException thrown on introspection of bean and if * a property in beanProps does not map to a property of bean. */ public static void mapJavaBeanProperties(Object bean, Properties beanProps) throws IntrospectionException { mapJavaBeanProperties(bean, beanProps, true); } /** * This method takes the properties found in the given beanProps * to the bean using the property editor registered for the property. * Any property in beanProps that does not have an associated java bean * property will result in an IntrospectionException. The string property * values are converted to the true java bean property type using the * java bean PropertyEditor framework. If a property in beanProps does not * have a PropertyEditor registered it will be ignored. * * @param bean - the java bean instance to apply the properties to * @param beanProps - map of java bean property name to property value. * @param isStrict - indicates if should throw exception if bean property can not * be matched. True for yes, false for no. * @throws IntrospectionException thrown on introspection of bean and if * a property in beanProps does not map to a property of bean. */ public static void mapJavaBeanProperties(Object bean, Properties beanProps, boolean isStrict) throws IntrospectionException { HashMap propertyMap = new HashMap(); BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (int p = 0; p < props.length; p++) { String fieldName = props[p].getName(); propertyMap.put(fieldName, props[p]); } boolean trace = log.isTraceEnabled(); Iterator keys = beanProps.keySet().iterator(); if( trace ) log.trace("Mapping properties for bean: "+bean); while( keys.hasNext() ) { String name = (String) keys.next(); String text = beanProps.getProperty(name); PropertyDescriptor pd = propertyMap.get(name); if (pd == null) { /* Try the property name with the first char uppercased to handle a property name like dLQMaxResent whose expected introspected property name would be DLQMaxResent since the JavaBean Introspector would view setDLQMaxResent as the setter for a DLQMaxResent property whose Introspector.decapitalize() method would also return "DLQMaxResent". */ if (name.length() > 1) { char first = name.charAt(0); String exName = Character.toUpperCase(first) + name.substring(1); pd = propertyMap.get(exName); // Be lenient and check the other way around, e.g. ServerName -> serverName if (pd == null) { exName = Character.toLowerCase(first) + name.substring(1); pd = propertyMap.get(exName); } } if (pd == null) { if (isStrict) { String msg = "No property found for: "+name+" on JavaBean: "+bean; throw new IntrospectionException(msg); } else { // since is not strict, ignore that this property was not found continue; } } } Method setter = pd.getWriteMethod(); if( trace ) log.trace("Property editor found for: "+name+", editor: "+pd+", setter: "+setter); if (setter != null) { Class ptype = pd.getPropertyType(); PropertyEditor editor = PropertyEditorManager.findEditor(ptype); if (editor == null) { if( trace ) log.trace("Failed to find property editor for: "+name); } try { editor.setAsText(text); Object args[] = {editor.getValue()}; setter.invoke(bean, args); } catch (Exception e) { if( trace ) log.trace("Failed to write property", e); } } } } /** * Gets the package names that will be searched for property editors. * * @return The package names that will be searched for property editors. */ public String[] getEditorSearchPath() { return PropertyEditorManager.getEditorSearchPath(); } /** * Sets the package names that will be searched for property editors. * * @param path The serach path. */ public void setEditorSearchPath(final String[] path) { PropertyEditorManager.setEditorSearchPath(path); } private static class Initialize implements PrivilegedAction { static Initialize instance = new Initialize(); public Object run() { String[] currentPath = PropertyEditorManager.getEditorSearchPath(); int length = currentPath != null ? currentPath.length : 0; String[] newPath = new String[length+2]; System.arraycopy(currentPath, 0, newPath, 2, length); // Put the JBoss editor path first // The default editors are not very flexible newPath[0] = "org.jboss.util.propertyeditor"; newPath[1] = "org.jboss.mx.util.propertyeditor"; PropertyEditorManager.setEditorSearchPath(newPath); /* Register the editor types that will not be found using the standard class name to editor name algorithm. For example, the type String[] has a name '[Ljava.lang.String;' which does not map to a XXXEditor name. */ Class strArrayType = String[].class; PropertyEditorManager.registerEditor(strArrayType, StringArrayEditor.class); Class clsArrayType = Class[].class; PropertyEditorManager.registerEditor(clsArrayType, ClassArrayEditor.class); Class intArrayType = int[].class; PropertyEditorManager.registerEditor(intArrayType, IntArrayEditor.class); Class byteArrayType = byte[].class; PropertyEditorManager.registerEditor(byteArrayType, ByteArrayEditor.class); // There is no default char editor. PropertyEditorManager.registerEditor(Character.TYPE, CharacterEditor.class); try { if (System.getProperty("org.jboss.util.property.disablenull") != null) disableIsNull = true; } catch (Throwable ignored) { log.trace("Error retrieving system property org.jboss.util.property.diablenull", ignored); } return null; } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/packag0000644000175000017500000000157310470642610033422 0ustar twernertwerner

Property editors for use with java.beans.PropertyEditorManager.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/DoubleEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Double0000644000175000017500000000307610470642610033406 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor for {@link Integer}. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class DoubleEditor extends PropertyEditorSupport { /** * Map the argument text into and Integer using Integer.valueOf. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Double.valueOf(text); setValue(newValue); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/DocumentEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Docume0000644000175000017500000000545010470642610033406 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jboss.util.NestedRuntimeException; import org.jboss.util.xml.DOMWriter; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * A property editor for {@link org.w3c.dom.Document}. * * @version $Revision: 1958 $ * @author Elias Ross */ public class DocumentEditor extends PropertyEditorSupport { /** * Returns the property as a String. * * @throws NestedRuntimeException conversion exception occured */ public String getAsText() { return DOMWriter.printNode((Node)getValue(), false); } /** * Sets as an Document created by a String. * * @throws NestedRuntimeException A parse exception occured */ public void setAsText(String text) { setValue(getAsDocument(text)); } protected Document getAsDocument(String text) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(text); InputSource is = new InputSource(sr); Document d = db.parse(is); return d; } catch (ParserConfigurationException e) { throw new NestedRuntimeException(e); } catch (SAXException e) { throw new NestedRuntimeException(e); } catch (IOException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/DateEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/DateEd0000644000175000017500000001224710774222622033326 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.jboss.util.NestedRuntimeException; import org.jboss.util.Strings; /** * A property editor for {@link java.util.Date}. * * @author Jason Dillon * @author David Jencks * @author Scott Stark * @author Adrian Brock * @author Ales Justin * @author Dimitris Andreadis * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class DateEditor extends PropertyEditorSupport { /** The formats to use when parsing the string date */ private static DateFormat[] formats; static { initialize(); } /** * Setup the parsing formats. Offered as a separate static method to allow * testing of locale changes, since SimpleDateFormat will use the default * locale upon construction. Should not be normally used! */ public static void initialize() { PrivilegedAction action = new PrivilegedAction() { public Object run() { String defaultFormat = System.getProperty("org.jboss.util.propertyeditor.DateEditor.format", "MMM d, yyyy"); String defaultLocale = System.getProperty("org.jboss.util.propertyeditor.DateEditor.locale"); DateFormat defaultDateFormat; if (defaultLocale == null || defaultLocale.length() == 0) { defaultDateFormat = new SimpleDateFormat(defaultFormat); } else { defaultDateFormat = new SimpleDateFormat(defaultFormat, Strings.parseLocaleString(defaultLocale)); } formats = new DateFormat[] { defaultDateFormat, // Tue Jan 04 00:00:00 PST 2005 new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"), // Wed, 4 Jul 2001 12:08:56 -0700 new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z") }; return null; } }; AccessController.doPrivileged(action); } /** Keep the text version of the date */ private String text; /** * Sets directly the java.util.Date value * * @param value a java.util.Date */ public void setValue(Object value) { if (value instanceof Date || value == null) { this.text = null; super.setValue(value); } else { throw new IllegalArgumentException("setValue() expected java.util.Date value, got " + value.getClass().getName()); } } /** * Parse the text into a java.util.Date by trying * one by one the registered DateFormat(s). * * @param text the string date */ public void setAsText(String text) { ParseException pe = null; for (int i = 0; i < formats.length; i++) { try { // try to parse the date DateFormat df = formats[i]; Date date = df.parse(text); // store the date in both forms this.text = text; super.setValue(date); // done return; } catch (ParseException e) { // remember the last seen exception pe = e; } } // couldn't parse throw new NestedRuntimeException(pe); } /** * Returns either the cached string date, or the stored * java.util.Date instance formated to string using the * last of the registered DateFormat(s) * * @return date as string */ public String getAsText() { if (text == null) { DateFormat df = formats[formats.length - 1]; Date date = (Date)getValue(); text = df.format(date); } return text; } }././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/BigDecimalEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/BigDec0000644000175000017500000000313610470642610033306 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.math.BigDecimal; /** * A property editor for {@link java.math.BigDecimal}. * * @version $Revision: 1958 $ * @author Jason Dillon * @author David Jencks */ public class BigDecimalEditor extends TextPropertyEditorSupport { /** * Returns a BigDecimal for the input object converted to a string. * * @return a BigDecimal object * */ public Object getValue() { return new BigDecimal(getAsText()); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/FileEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/FileEd0000644000175000017500000000337310470642610033324 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.io.File; import java.io.IOException; import org.jboss.util.NestedRuntimeException; /** * A property editor for {@link java.io.File}. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FileEditor extends TextPropertyEditorSupport { /** * Returns a URL for the input object converted to a string. * * @return a URL object * * @throws NestedRuntimeException An IOException occured. */ public Object getValue() { try { return new File(getAsText()).getCanonicalFile(); } catch (IOException e) { throw new NestedRuntimeException(e); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/BooleanEditor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/Boolea0000644000175000017500000000342310470642610033371 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** A property editor for {@link java.lang.Boolean}. * * @version $Revision: 1958 $ * @author Scott.Stark@jboss.org */ public class BooleanEditor extends PropertyEditorSupport { private static final String[] BOOLEAN_TAGS = {"true", "false"}; /** Map the argument text into Boolean.TRUE or Boolean.FALSE using Boolean.valueOf. */ public void setAsText(final String text) { if (PropertyEditors.isNull(text)) { setValue(null); return; } Object newValue = Boolean.valueOf(text); setValue(newValue); } /** @return the values {"true", "false"} */ public String[] getTags() { return BOOLEAN_TAGS; } }././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/TextPropertyEditorSupport.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/propertyeditor/TextPr0000644000175000017500000000327210470642610033420 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.propertyeditor; import java.beans.PropertyEditorSupport; /** * A property editor support class for textual properties. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class TextPropertyEditorSupport extends PropertyEditorSupport { protected TextPropertyEditorSupport(final Object source) { super(source); } protected TextPropertyEditorSupport() { super(); } /** * Sets the property value by parsing a given String. * * @param text The string to be parsed. */ public void setAsText(final String text) { setValue(text); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/0000755000175000017500000000000011105642365027547 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/package.html0000644000175000017500000000154510470642610032032 0ustar twernertwerner

Unique and globally unique identifier classes.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/VMID.java0000644000175000017500000001606010776226110031153 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.id; import java.net.InetAddress; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import org.jboss.util.HashCode; import org.jboss.util.platform.PID; /** * An object that uniquely identifies a virtual machine. * *

The identifier is composed of: *

    *
  1. The Internet address of the physical machine.
  2. *
  3. The process identifier of the virtual machine.
  4. *
  5. A UID to guarantee uniqness across multipule virtual * machines on the same physical machine.
  6. *
* *
 *    [ address ] - [ process id ] - [ time ] - [ counter ]
 *                                   |------- UID --------|
 * 
* *

Numbers are converted to radix(Character.MAX_RADIX) when converting * to strings. * * @see UID * * @version $Revision: 2800 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class VMID implements ID { /** The serialVersionUID */ private static final long serialVersionUID = -4339675822939194520L; /** The address of the current virtual machine */ protected final byte[] address; /** The process identifier of the current virtual machine */ protected final PID pid; /** A unique identifier to ensure uniqueness across the host machine */ protected final UID uid; /** The hash code of this VMID */ protected final int hashCode; /** * Construct a new VMID. * * @param address The address of the current virtual machine. * @param pid Process identifier. * @param uid Unique identifier. * * @see #getInstance() For getting a VMID instance reference. */ protected VMID(final byte[] address, final PID pid, final UID uid) { this.address = address; this.pid = pid; this.uid = uid; // generate a hashCode for this VMID int code = pid.hashCode(); code ^= uid.hashCode(); code ^= HashCode.generate(address); hashCode = code; } /** * Copy a VMID. * * @param vmid VMID to copy. */ protected VMID(final VMID vmid) { this.address = vmid.address; this.pid = vmid.pid; this.uid = vmid.uid; this.hashCode = vmid.hashCode; } /** * Get the address portion of this VMID. * * @return The address portion of this VMID. */ public final byte[] getAddress() { return address; } /** * Get the process identifier portion of this VMID. * * @return The process identifier portion of this VMID. */ public final PID getProcessID() { return pid; } /** * Get the UID portion of this VMID. * * @return The UID portion of this VMID. */ public final UID getUID() { return uid; } /** * Return a string representation of this VMID. * * @return A string representation of this VMID. */ public String toString() { StringBuffer buff = new StringBuffer(); for (int i=0; iA VMID is equals to another VMID if the address, * process identifer and UID portions are equal. * * @param obj Object to test equality with. * @return True if object is equals to this VMID. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { VMID vmid = (VMID)obj; return Arrays.equals(vmid.address, address) && vmid.pid.equals(pid) && vmid.uid.equals(uid); } return false; } /** * Returns a copy of this VMID. * * @return A copy of this VMID. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Returns a VMID as a string. * * @return VMID as a string. */ public static String asString() { return getInstance().toString(); } ///////////////////////////////////////////////////////////////////////// // Instance Access // ///////////////////////////////////////////////////////////////////////// /** The single instance of VMID for the running Virtual Machine */ private static VMID instance = null; /** * Get the VMID for the current virtual machine. * * @return Virtual machine identifier. * */ public synchronized static VMID getInstance() { if (instance == null) { instance = create(); } return instance; } /** * The address used when conventional methods fail to return the address * of the current machine. */ public static final byte[] UNKNOWN_HOST = { 0, 0, 0, 0 }; /** * Return the current host internet address. */ private static byte[] getHostAddress() { return (byte[]) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { return InetAddress.getLocalHost().getAddress(); } catch (Exception e) { return UNKNOWN_HOST; } } }); } /** * Create the VMID for the current virtual mahcine. * * @return Virtual machine identifer. */ private static VMID create() { // get the local internet address for the current host byte[] address = getHostAddress(); return new VMID(address, PID.getInstance(), new UID()); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/UID.java0000644000175000017500000001011710774222622031034 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.id; import java.util.concurrent.atomic.AtomicLong; /** * A unique identifier (uniqueness only guarantied inside of the virtual * machine in which it was created). * *

The identifier is composed of: *

    *
  1. A long generated from the current system time (in milliseconds).
  2. *
  3. A long generated from a counter (which is the number of UID objects * that have been created durring the life of the executing virtual * machine).
  4. *
* *
 *    [ time ] - [ counter ]
 * 
* *

Numbers are converted to radix(Character.MAX_RADIX) when converting * to strings. * *

This should provide adequate uniqueness for most purposes. * * @version $Revision: 2787 $ * @author Jason Dillon */ public class UID implements ID { private static final long serialVersionUID = -8093336932569424512L; /** A counter for generating identity values */ protected static final AtomicLong COUNTER = new AtomicLong(0); /** The time portion of the UID */ protected final long time; /** The identity portion of the UID */ protected final long id; /** * Construct a new UID. */ public UID() { time = System.currentTimeMillis(); id = COUNTER.incrementAndGet(); } /** * Copy a UID. * @param uid */ protected UID(final UID uid) { time = uid.time; id = uid.id; } /** * Get the time portion of this UID. * * @return The time portion of this UID. */ public final long getTime() { return time; } /** * Get the identity portion of this UID. * * @return The identity portion of this UID. */ public final long getID() { return id; } /** * Return a string representation of this UID. * * @return A string representation of this UID. */ public String toString() { return Long.toString(time, Character.MAX_RADIX) + "-" + Long.toString(id, Character.MAX_RADIX); } /** * Return the hash code of this UID. * * @return The hash code of this UID. */ public int hashCode() { return (int)id; } /** * Checks if the given object is equal to this UID. * * @param obj Object to test equality with. * @return True if object is equal to this UID. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { UID uid = (UID)obj; return uid.time == time && uid.id == id; } return false; } /** * Returns a copy of this UID. * * @return A copy of this UID. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Returns a UID as a string. * * @return UID as a string. */ public static String asString() { return new UID().toString(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/GUID.java0000644000175000017500000001046510774222622031151 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.id; /** * A globally unique identifier (globally across a cluster of virtual * machines). * *

The identifier is composed of: *

    *
  1. The VMID for the virtual machine.
  2. *
  3. A UID to provide uniqueness over a VMID.
  4. *
* *
 *    [ address ] - [ process id ] - [ time ] - [ counter ] - [ time ] - [ counter ]
 *                                   |------- UID --------|   |------- UID --------|
 *    |---------------------- VMID -----------------------|
 * 
* * @see VMID * @see UID * * @version $Revision: 2787 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public class GUID implements ID, Comparable { /** The serial version id, @since 1.6 */ static final long serialVersionUID = 3289509836244263718L; /** The virtual machine identifier */ protected final VMID vmid; /** The unique identifier */ protected final UID uid; /** The hash code of this GUID */ protected final int hashCode; /** * Construct a new GUID. */ public GUID() { this.vmid = VMID.getInstance(); this.uid = new UID(); // generate a hash code for this GUID int code = vmid.hashCode(); code ^= uid.hashCode(); hashCode = code; } /** * Copy a GUID. * * @param guid GUID to copy. */ protected GUID(final GUID guid) { this.vmid = guid.vmid; this.uid = guid.uid; this.hashCode = guid.hashCode; } /** * Get the VMID portion of this GUID. * * @return The VMID portion of this GUID. */ public final VMID getVMID() { return vmid; } /** * Get the UID portion of this GUID. * * @return The UID portion of this GUID. */ public final UID getUID() { return uid; } /** * Return a string representation of this GUID. * * @return A string representation of this GUID. */ public String toString() { return vmid.toString() + "-" + uid.toString(); } /** * Return the hash code of this GUID. * * @return The hash code of this GUID. */ public int hashCode() { return hashCode; } /** * Check if the given object is equal to this GUID. * *

A GUID is equal to another GUID if the VMID and UID portions are * equal. * * @param obj Object to test equality with. * @return True if object is equal to this GUID. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { GUID guid = (GUID)obj; return guid.vmid.equals(vmid) && guid.uid.equals(uid); } return false; } /** * Returns a copy of this GUID. * * @return A copy of this GUID. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Returns a GUID as a string. * * @return GUID as a string. */ public static String asString() { return new GUID().toString(); } public int compareTo(Object o) { GUID guid = (GUID)o; return this.toString().compareTo(guid.toString()); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/SerialVersion.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/SerialVersion.java0000644000175000017500000000476210774222622033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.id; import java.security.AccessController; import java.security.PrivilegedAction; /** * Serialization version compatibility mode constants.

* * Contains static constants and attributes to help with serialization * versioning.

* * Set the system property

org.jboss.j2ee.LegacySerialization
* to serialization compatibility with jboss-4.0.1 and earlier. The * serialVersionUID values were synched with the j2ee 1.4 ri classes and * explicitly set in jboss-4.0.2 which is what * * @author Adrian Brock. * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class SerialVersion { // Static -------------------------------------------------------- /** Legacy, jboss-4.0.1 through jboss-4.0.0 */ public static final int LEGACY = 0; /** The serialization compatible with Sun's RI, jboss-4.0.2+ */ public static final int JBOSS_402 = 1; /** * The serialization version to use */ public static int version = JBOSS_402; /** Determine the serialization version */ static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { if (System.getProperty("org.jboss.j2ee.LegacySerialization") != null) version = LEGACY; } catch (Throwable ignored) { } return null; } }); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/id/ID.java0000644000175000017500000000245010470642610030704 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.id; import java.io.Serializable; /** * A tagging interface for an identifier. * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface ID extends Serializable, Cloneable { // empty } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/jmx/0000755000175000017500000000000011105642365027751 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/jmx/package.html0000644000175000017500000000155510470642610032235 0ustar twernertwerner

Utilities for the Java Management Extentions API.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/AbstractNestedThrowable.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/AbstractNestedThrowab0000644000175000017500000001015010470642610033325 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.PrintWriter; import java.io.PrintStream; /** * A common superclass for Throwable classes that can contain * a nested Throwable detail object. * * @version $Revision: 1958 $ * @author Jason Dillon */ public abstract class AbstractNestedThrowable extends Throwable implements NestedThrowable { /** The nested throwable */ protected final Throwable nested; /** * Construct a AbstractNestedThrowable with the specified * detail message. * * @param msg Detail message. */ public AbstractNestedThrowable(final String msg) { super(msg); this.nested = null; } /** * Construct a AbstractNestedThrowable with the specified detail * message and nested Throwable. * * @param msg Detail message. * @param nested Nested Throwable. */ public AbstractNestedThrowable(final String msg, final Throwable nested) { super(msg); this.nested = nested; NestedThrowable.Util.checkNested(this, nested); } /** * Construct a AbstractNestedThrowable with the specified * nested Throwable. * * @param nested Nested Throwable. */ public AbstractNestedThrowable(final Throwable nested) { this(nested.getMessage(), nested); } /** * Construct a AbstractNestedThrowable with no detail. */ public AbstractNestedThrowable() { super(); this.nested = null; } /** * Return the nested Throwable. * * @return Nested Throwable. */ public Throwable getNested() { return nested; } /** * Return the nested Throwable. * *

For JDK 1.4 compatibility. * * @return Nested Throwable. */ public Throwable getCause() { return nested; } /** * Returns the composite throwable message. * * @return The composite throwable message. */ public String getMessage() { return NestedThrowable.Util.getMessage(super.getMessage(), nested); } /** * Prints the composite message and the embedded stack trace to the * specified print stream. * * @param stream Stream to print to. */ public void printStackTrace(final PrintStream stream) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(stream); } NestedThrowable.Util.print(nested, stream); } /** * Prints the composite message and the embedded stack trace to the * specified print writer. * * @param writer Writer to print to. */ public void printStackTrace(final PrintWriter writer) { if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) { super.printStackTrace(writer); } NestedThrowable.Util.print(nested, writer); } /** * Prints the composite message and the embedded stack trace to * System.err. */ public void printStackTrace() { printStackTrace(System.err); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NotImplementedException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/NotImplementedExcepti0000644000175000017500000000343710776226110033352 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Thrown to indicate that a method has not been implemented yet. * *

This exception is used to help stub out implementations. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class NotImplementedException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = -3915801189311749818L; /** * Construct a NotImplementedException with a detail message. * * @param msg Detail message. */ public NotImplementedException(final String msg) { super(msg); } /** * Construct a NotImplementedException with no detail. */ public NotImplementedException() { super(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/EmptyStringException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/EmptyStringException.0000644000175000017500000000332610776226110033323 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Thrown to indicate that a string was empty (aka. "") * where it must not be. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class EmptyStringException extends IllegalArgumentException { /** The serialVersionUID */ private static final long serialVersionUID = -7958716001355854762L; /** * Construct a EmptyStringException. * * @param msg Exception message. */ public EmptyStringException(final String msg) { super(msg); } /** * Construct a EmptyStringException. */ public EmptyStringException() { super(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Sync.java0000644000175000017500000000276310774222622030743 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Interface that gives synchronization semantic to implementors * * @see Semaphore * * @author Simone Bordet * @version $Revision: 2787 $ */ public interface Sync { /** * Acquires this sync * * @see #release * @throws InterruptedException */ void acquire() throws InterruptedException; /** * Releases this sync * * @see #acquire */ void release(); } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/0000755000175000017500000000000011105642366027754 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/0000755000175000017500000000000011105642366031366 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/0000755000175000017500000000000011105642366033030 5ustar twernertwerner././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/p0000644000175000017500000000150110470642610033203 0ustar twernertwerner

XML utilities.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/Debug.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/D0000644000175000017500000001200410774222622033133 0ustar twernertwerner// Debug.java - Print debug messages /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.helpers; /** * Static debugging/messaging class for Catalogs. * *

This class defines a set of static methods that can be called * to produce debugging messages. Messages have an associated "debug * level" and messages below the current setting are not displayed.

* * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public class Debug { /** The internal debug level. */ protected int debug = 0; /** Constructor */ public Debug() { // nop } /** Set the debug level for future messages. * @param newDebug */ public void setDebug(int newDebug) { debug = newDebug; } /** @return the current debug level. */ public int getDebug() { return debug; } /** * Print debug message (if the debug level is high enough). * *

Prints "the message"

* * @param level The debug level of this message. This message * will only be * displayed if the current debug level is at least equal to this * value. * @param message The text of the message. */ public void message(int level, String message) { if (debug >= level) { System.out.println(message); } } /** * Print debug message (if the debug level is high enough). * *

Prints "the message: spec"

* * @param level The debug level of this message. This message * will only be * displayd if the current debug level is at least equal to this * value. * @param message The text of the message. * @param spec An argument to the message. */ public void message(int level, String message, String spec) { if (debug >= level) { System.out.println(message + ": " + spec); } } /** * Print debug message (if the debug level is high enough). * *

Prints "the message: spec1" and "spec2" indented on the next line.

* * @param level The debug level of this message. This message * will only be * displayed if the current debug level is at least equal to this * value. * @param message The text of the message. * @param spec1 An argument to the message. * @param spec2 Another argument to the message. */ public void message(int level, String message, String spec1, String spec2) { if (debug >= level) { System.out.println(message + ": " + spec1); System.out.println("\t" + spec2); } } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/BootstrapResolver.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/B0000644000175000017500000002011310774222622033131 0ustar twernertwerner// BootstrapResolver.java - Resolve entities and URIs internally /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.helpers; import java.util.Hashtable; import java.net.URL; import java.net.MalformedURLException; import java.io.InputStream; import javax.xml.transform.URIResolver; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.TransformerException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** * A simple bootstrapping resolver. * *

This class is used as the entity resolver when reading XML Catalogs. * It searches for the OASIS XML Catalog DTD, Relax NG Grammar and W3C XML Schema * as resources (e.g., in the resolver jar file).

* *

If you have your own DTDs or schemas, you can extend this class and * set the BootstrapResolver in your CatalogManager.

* * @see org.jboss.util.xml.catalog.CatalogManager * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class BootstrapResolver implements EntityResolver, URIResolver { /** URI of the W3C XML Schema for OASIS XML Catalog files. */ public static final String xmlCatalogXSD = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.xsd"; /** URI of the RELAX NG Grammar for OASIS XML Catalog files. */ public static final String xmlCatalogRNG = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.rng"; /** Public identifier for OASIS XML Catalog files. */ public static final String xmlCatalogPubId = "-//OASIS//DTD XML Catalogs V1.0//EN"; /** System identifier for OASIS XML Catalog files. */ public static final String xmlCatalogSysId = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd"; /** Private hash used for public identifiers. */ private Hashtable publicMap = new Hashtable(); /** Private hash used for system identifiers. */ private Hashtable systemMap = new Hashtable(); /** Private hash used for URIs. */ private Hashtable uriMap = new Hashtable(); /** Constructor. */ public BootstrapResolver() { URL url = this.getClass().getResource("/org/apache/xml/resolver/etc/catalog.dtd"); if (url != null) { publicMap.put(xmlCatalogPubId, url.toString()); systemMap.put(xmlCatalogSysId, url.toString()); } url = this.getClass().getResource("/org/apache/xml/resolver/etc/catalog.rng"); if (url != null) { uriMap.put(xmlCatalogRNG, url.toString()); } url = this.getClass().getResource("/org/apache/xml/resolver/etc/catalog.xsd"); if (url != null) { uriMap.put(xmlCatalogXSD, url.toString()); } } /** SAX resolveEntity API. */ public InputSource resolveEntity (String publicId, String systemId) { String resolved = null; if (systemId != null && systemMap.containsKey(systemId)) { resolved = (String) systemMap.get(systemId); } else if (publicId != null && publicMap.containsKey(publicId)) { resolved = (String) publicMap.get(publicId); } if (resolved != null) { try { InputSource iSource = new InputSource(resolved); iSource.setPublicId(publicId); // Ideally this method would not attempt to open the // InputStream, but there is a bug (in Xerces, at least) // that causes the parser to mistakenly open the wrong // system identifier if the returned InputSource does // not have a byteStream. // // It could be argued that we still shouldn't do this here, // but since the purpose of calling the entityResolver is // almost certainly to open the input stream, it seems to // do little harm. // URL url = new URL(resolved); InputStream iStream = url.openStream(); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { // FIXME: silently fail? return null; } } return null; } /** Transformer resolve API. */ public Source resolve(String href, String base) throws TransformerException { String uri = href; int hashPos = href.indexOf("#"); if (hashPos >= 0) { uri = href.substring(0, hashPos); } String result = null; if (href != null && uriMap.containsKey(href)) { result = (String) uriMap.get(href); } if (result == null) { try { URL url = null; if (base==null) { url = new URL(uri); result = url.toString(); } else { URL baseURL = new URL(base); url = (href.length()==0 ? baseURL : new URL(baseURL, uri)); result = url.toString(); } } catch (java.net.MalformedURLException mue) { // try to make an absolute URI from the current base String absBase = makeAbsolute(base); if (!absBase.equals(base)) { // don't bother if the absBase isn't different! return resolve(href, absBase); } else { throw new TransformerException("Malformed URL " + href + "(base " + base + ")", mue); } } } SAXSource source = new SAXSource(); source.setInputSource(new InputSource(result)); return source; } /** Attempt to construct an absolute URI */ private String makeAbsolute(String uri) { if (uri == null) { uri = ""; } try { URL url = new URL(uri); return url.toString(); } catch (MalformedURLException mue) { String dir = System.getProperty("user.dir"); String file = ""; if (dir.endsWith("/")) { file = "file://" + dir + uri; } else { file = "file://" + dir + "/" + uri; } try { URL fileURL = new URL(file); return fileURL.toString(); } catch (MalformedURLException mue2) { // bail return uri; } } } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/Namespaces.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/N0000644000175000017500000001211310470642610033142 0ustar twernertwerner// Namespaces.java - Analyze namespace nodes in a DOM tree /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.helpers; import org.w3c.dom.*; /** * Static Namespace query methods. * *

This class defines a set of static methods that can be called * to analyze the namespace properties of DOM nodes.

* * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public class Namespaces { /** * Returns the "prefix" part of a QName or the empty string (not * null) if the name has no prefix. * * @param element The QName of an element. * @return The prefix part of the element name. */ public static String getPrefix(Element element) { String name = element.getTagName(); String prefix = ""; if (name.indexOf(':') > 0) { prefix = name.substring(0, name.indexOf(':')); } return prefix; } /** * Returns the "localname" part of a QName, which is the whole * name if it has no prefix. * * @param element The QName of an element. * @return The local part of a QName. */ public static String getLocalName(Element element) { String name = element.getTagName(); if (name.indexOf(':') > 0) { name = name.substring(name.indexOf(':')+1); } return name; } /** * Returns the namespace URI for the specified prefix at the * specified context node. * * @param node The context node. * @param prefix The prefix. * @return The namespace URI associated with the prefix, or * null if no namespace declaration exists for the prefix. */ public static String getNamespaceURI(Node node, String prefix) { if (node == null || node.getNodeType() != Node.ELEMENT_NODE) { return null; } if (prefix.equals("")) { if (((Element) node).hasAttribute("xmlns")) { return ((Element) node).getAttribute("xmlns"); } } else { String nsattr = "xmlns:" + prefix; if (((Element) node).hasAttribute(nsattr)) { return ((Element) node).getAttribute(nsattr); } } return getNamespaceURI(node.getParentNode(), prefix); } /** * Returns the namespace URI for the namespace to which the * element belongs. * * @param element The element. * @return The namespace URI associated with the namespace of the * element, or null if no namespace declaration exists for it. */ public static String getNamespaceURI(Element element) { String prefix = getPrefix(element); return getNamespaceURI(element, prefix); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/PublicId.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/helpers/P0000644000175000017500000001517210774222622033160 0ustar twernertwerner// PublicId.java - Information about public identifiers /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.helpers; /** * Static methods for dealing with public identifiers. * *

This class defines a set of static methods that can be called * to handle public identifiers.

* * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public abstract class PublicId { protected PublicId() { } /** * Normalize a public identifier. * *

Public identifiers must be normalized according to the following * rules before comparisons between them can be made:

* *
    *
  • Whitespace characters are normalized to spaces (e.g., line feeds, * tabs, etc. become spaces).
  • *
  • Leading and trailing whitespace is removed.
  • *
  • Multiple internal whitespaces are normalized to a single * space.
  • *
* *

This method is declared static so that other classes * can use it directly.

* * @param publicId The unnormalized public identifier. * * @return The normalized identifier. */ public static String normalize(String publicId) { String normal = publicId.replace('\t', ' '); normal = normal.replace('\r', ' '); normal = normal.replace('\n', ' '); normal = normal.trim(); int pos; while ((pos = normal.indexOf(" ")) >= 0) { normal = normal.substring(0, pos) + normal.substring(pos+1); } return normal; } /** * Encode a public identifier as a "publicid" URN. * *

This method is declared static so that other classes * can use it directly.

* * @param publicId The unnormalized public identifier. * * @return The normalized identifier. */ public static String encodeURN(String publicId) { String urn = PublicId.normalize(publicId); urn = PublicId.stringReplace(urn, "%", "%25"); urn = PublicId.stringReplace(urn, ";", "%3B"); urn = PublicId.stringReplace(urn, "'", "%27"); urn = PublicId.stringReplace(urn, "?", "%3F"); urn = PublicId.stringReplace(urn, "#", "%23"); urn = PublicId.stringReplace(urn, "+", "%2B"); urn = PublicId.stringReplace(urn, " ", "+"); urn = PublicId.stringReplace(urn, "::", ";"); urn = PublicId.stringReplace(urn, ":", "%3A"); urn = PublicId.stringReplace(urn, "//", ":"); urn = PublicId.stringReplace(urn, "/", "%2F"); return "urn:publicid:" + urn; } /** * Decode a "publicid" URN into a public identifier. * *

This method is declared static so that other classes * can use it directly.

* * @param urn The unnormalized public identifier. * * @return The normalized identifier. */ public static String decodeURN(String urn) { String publicId = ""; if (urn.startsWith("urn:publicid:")) { publicId = urn.substring(13); } else { return urn; } publicId = PublicId.stringReplace(publicId, "%2F", "/"); publicId = PublicId.stringReplace(publicId, ":", "//"); publicId = PublicId.stringReplace(publicId, "%3A", ":"); publicId = PublicId.stringReplace(publicId, ";", "::"); publicId = PublicId.stringReplace(publicId, "+", " "); publicId = PublicId.stringReplace(publicId, "%2B", "+"); publicId = PublicId.stringReplace(publicId, "%23", "#"); publicId = PublicId.stringReplace(publicId, "%3F", "?"); publicId = PublicId.stringReplace(publicId, "%27", "'"); publicId = PublicId.stringReplace(publicId, "%3B", ";"); publicId = PublicId.stringReplace(publicId, "%25", "%"); return publicId; } /** * Replace one string with another. * */ private static String stringReplace(String str, String oldStr, String newStr) { String result = ""; int pos = str.indexOf(oldStr); // System.out.println(str + ": " + oldStr + " => " + newStr); while (pos >= 0) { // System.out.println(str + " (" + pos + ")"); result += str.substring(0, pos); result += newStr; str = str.substring(pos+1); pos = str.indexOf(oldStr); } return result + str; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/0000755000175000017500000000000011105642366033013 5ustar twernertwerner././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/p0000644000175000017500000000150110470642610033166 0ustar twernertwerner

XML utilities.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/ExtendedXMLCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/E0000644000175000017500000001702610774222622033130 0ustar twernertwerner// ExtendedXMLCatalogReader.java - Read XML Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.util.Vector; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogEntry; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.Resolver; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Parse Extended OASIS Entity Resolution Technical Committee * XML Catalog files. * * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class ExtendedXMLCatalogReader extends OASISXMLCatalogReader { /** The namespace name of extended catalog elements */ public static final String extendedNamespaceName = "http://nwalsh.com/xcatalog/1.0"; /** * The SAX startElement method recognizes elements * from the plain catalog format and instantiates CatalogEntry * objects for them. * * @param namespaceURI The namespace name of the element. * @param localName The local name of the element. * @param qName The QName of the element. * @param atts The list of attributes on the element. * * @see CatalogEntry */ public void startElement (String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { // Check before calling the super because super will report our // namespace as an extension namespace, but that doesn't count // for this element. boolean inExtension = inExtensionNamespace(); super.startElement(namespaceURI, localName, qName, atts); int entryType = -1; Vector entryArgs = new Vector(); if (namespaceURI != null && extendedNamespaceName.equals(namespaceURI) && !inExtension) { // This is an Extended XML Catalog entry if (atts.getValue("xml:base") != null) { String baseURI = atts.getValue("xml:base"); entryType = Catalog.BASE; entryArgs.add(baseURI); baseURIStack.push(baseURI); debug.message(4, "xml:base", baseURI); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (base)", localName); } } entryType = -1; entryArgs = new Vector(); } else { baseURIStack.push(baseURIStack.peek()); } if (localName.equals("uriSuffix")) { if (checkAttributes(atts, "suffix", "uri")) { entryType = Resolver.URISUFFIX; entryArgs.add(atts.getValue("suffix")); entryArgs.add(atts.getValue("uri")); debug.message(4, "uriSuffix", atts.getValue("suffix"), atts.getValue("uri")); } } else if (localName.equals("systemSuffix")) { if (checkAttributes(atts, "suffix", "uri")) { entryType = Resolver.SYSTEMSUFFIX; entryArgs.add(atts.getValue("suffix")); entryArgs.add(atts.getValue("uri")); debug.message(4, "systemSuffix", atts.getValue("suffix"), atts.getValue("uri")); } } else { // This is equivalent to an invalid catalog entry type debug.message(1, "Invalid catalog entry type", localName); } if (entryType >= 0) { try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry", localName); } } } } } /** The SAX endElement method does nothing. */ public void endElement (String namespaceURI, String localName, String qName) throws SAXException { super.endElement(namespaceURI, localName, qName); // Check after popping the stack so we don't erroneously think we // are our own extension namespace... boolean inExtension = inExtensionNamespace(); int entryType = -1; Vector entryArgs = new Vector(); if (namespaceURI != null && (extendedNamespaceName.equals(namespaceURI)) && !inExtension) { String popURI = (String) baseURIStack.pop(); String baseURI = (String) baseURIStack.peek(); if (!baseURI.equals(popURI)) { entryType = catalog.BASE; entryArgs.add(baseURI); debug.message(4, "(reset) xml:base", baseURI); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (rbase)", localName); } } } } } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/TR9401CatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/T0000644000175000017500000001256010774222622033145 0ustar twernertwerner// TR9401CatalogReader.java - Read OASIS Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.io.InputStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.Vector; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogEntry; import org.jboss.util.xml.catalog.CatalogException; /** * Parses OASIS Open Catalog files. * *

This class reads OASIS Open Catalog files, returning a stream * of tokens.

* *

This code interrogates the following non-standard system properties:

* *
*
xml.catalog.debug
*

Sets the debug level. A value of 0 is assumed if the * property is not set or is not a number.

*
* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class TR9401CatalogReader extends TextCatalogReader { /** * Start parsing an OASIS TR9401 Open Catalog file. The file is * actually read and parsed * as needed by nextEntry. * *

In a TR9401 Catalog the 'DELEGATE' entry delegates public * identifiers. There is no delegate entry for system identifiers * or URIs.

* * @throws MalformedURLException Improper fileUrl * @throws IOException Error reading catalog file */ public void readCatalog(Catalog catalog, InputStream is) throws MalformedURLException, IOException { catfile = is; if (catfile == null) { return; } Vector unknownEntry = null; while (true) { String token = nextToken(); if (token == null) { if (unknownEntry != null) { catalog.unknownEntry(unknownEntry); unknownEntry = null; } catfile.close(); catfile = null; return; } String entryToken = null; if (caseSensitive) { entryToken = token; } else { entryToken = token.toUpperCase(); } if (entryToken.equals("DELEGATE")) { entryToken = "DELEGATE_PUBLIC"; } try { int type = CatalogEntry.getEntryType(entryToken); int numArgs = CatalogEntry.getEntryArgCount(type); Vector args = new Vector(); if (unknownEntry != null) { catalog.unknownEntry(unknownEntry); unknownEntry = null; } for (int count = 0; count < numArgs; count++) { args.addElement(nextToken()); } catalog.addEntry(new CatalogEntry(entryToken, args)); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { if (unknownEntry == null) { unknownEntry = new Vector(); } unknownEntry.addElement(token); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { catalog.getCatalogManager().debug.message(1, "Invalid catalog entry", token); unknownEntry = null; } } } } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/TextCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/T0000644000175000017500000002175510774222622033153 0ustar twernertwerner// TextCatalogReader.java - Read text/plain Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.io.InputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.net.URL; import java.net.URLConnection; import java.net.MalformedURLException; import java.util.Vector; import java.util.Stack; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogEntry; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.readers.CatalogReader; /** * Parses plain text Catalog files. * *

This class reads plain text Open Catalog files.

* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class TextCatalogReader implements CatalogReader { /** The input stream used to read the catalog */ protected InputStream catfile = null; /** * Character lookahead stack. Reading a catalog sometimes requires * up to two characters of lookahead. */ protected int[] stack = new int[3]; /** * Token stack. Recognizing an unexpected catalog entry requires * the ability to "push back" a token. */ protected Stack tokenStack = new Stack(); /** The current position on the lookahead stack */ protected int top = -1; /** Are keywords in the catalog case sensitive? */ protected boolean caseSensitive = false; /** * Construct a CatalogReader object. */ public TextCatalogReader() { } public void setCaseSensitive(boolean isCaseSensitive) { caseSensitive = isCaseSensitive; } public boolean getCaseSensitive() { return caseSensitive; } /** * Start parsing a text catalog file. The file is * actually read and parsed * as needed by nextEntry.

* * @param fileUrl The URL or filename of the catalog file to process * * @throws MalformedURLException Improper fileUrl * @throws IOException Error reading catalog file */ public void readCatalog(Catalog catalog, String fileUrl) throws MalformedURLException, IOException { URL catURL = null; try { catURL = new URL(fileUrl); } catch (MalformedURLException e) { catURL = new URL("file:///" + fileUrl); } URLConnection urlCon = catURL.openConnection(); try { readCatalog(catalog, urlCon.getInputStream()); } catch (FileNotFoundException e) { catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found", catURL.toString()); } } public void readCatalog(Catalog catalog, InputStream is) throws MalformedURLException, IOException { catfile = is; if (catfile == null) { return; } Vector unknownEntry = null; while (true) { String token = nextToken(); if (token == null) { if (unknownEntry != null) { catalog.unknownEntry(unknownEntry); unknownEntry = null; } catfile.close(); catfile = null; return; } String entryToken = null; if (caseSensitive) { entryToken = token; } else { entryToken = token.toUpperCase(); } try { int type = CatalogEntry.getEntryType(entryToken); int numArgs = CatalogEntry.getEntryArgCount(type); Vector args = new Vector(); if (unknownEntry != null) { catalog.unknownEntry(unknownEntry); unknownEntry = null; } for (int count = 0; count < numArgs; count++) { args.addElement(nextToken()); } catalog.addEntry(new CatalogEntry(entryToken, args)); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { if (unknownEntry == null) { unknownEntry = new Vector(); } unknownEntry.addElement(token); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { catalog.getCatalogManager().debug.message(1, "Invalid catalog entry", token); unknownEntry = null; } } } } /** * The destructor. * *

Makes sure the catalog file is closed.

*/ protected void finalize() { if (catfile != null) { try { catfile.close(); } catch (IOException e) { // whatever... } } catfile = null; } // ----------------------------------------------------------------- /** * Return the next token in the catalog file. * * @return The Catalog file token from the input stream. * @throws IOException If an error occurs reading from the stream. */ protected String nextToken() throws IOException { String token = ""; int ch, nextch; if (!tokenStack.empty()) { return (String) tokenStack.pop(); } // Skip over leading whitespace and comments while (true) { // skip leading whitespace ch = catfile.read(); while (ch <= ' ') { // all ctrls are whitespace ch = catfile.read(); if (ch < 0) { return null; } } // now 'ch' is the current char from the file nextch = catfile.read(); if (nextch < 0) { return null; } if (ch == '-' && nextch == '-') { // we've found a comment, skip it... ch = ' '; nextch = nextChar(); while (ch != '-' || nextch != '-') { ch = nextch; nextch = nextChar(); } // Ok, we've found the end of the comment, // loop back to the top and start again... } else { stack[++top] = nextch; stack[++top] = ch; break; } } ch = nextChar(); if (ch == '"' || ch == '\'') { int quote = ch; while ((ch = nextChar()) != quote) { char[] chararr = new char[1]; chararr[0] = (char) ch; String s = new String(chararr); token = token.concat(s); } return token; } else { // return the next whitespace or comment delimited // string while (ch > ' ') { nextch = nextChar(); if (ch == '-' && nextch == '-') { stack[++top] = ch; stack[++top] = nextch; return token; } else { char[] chararr = new char[1]; chararr[0] = (char) ch; String s = new String(chararr); token = token.concat(s); ch = nextch; } } return token; } } /** * Return the next logical character from the input stream. * * @return The next (logical) character from the input stream. The * character may be buffered from a previous lookahead. * * @throws IOException If an error occurs reading from the stream. */ protected int nextChar() throws IOException { if (top < 0) { return catfile.read(); } else { return stack[top--]; } } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/SAXCatalogParser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/S0000644000175000017500000000646410774222622033152 0ustar twernertwerner// SAXCatalogParser.java - An interface for reading catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import org.jboss.util.xml.catalog.Catalog; import org.xml.sax.*; /** * The SAXCatalogParser interface. * *

This interface must be implemented in order for a class to * participate as a parser for the SAXCatalogReader. * * @see Catalog * @see SAXCatalogReader * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("deprecation") public interface SAXCatalogParser extends ContentHandler, DocumentHandler { /** Set the Catalog for which parsing is being performed. * @param catalog */ public void setCatalog(Catalog catalog); } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/XCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/X0000644000175000017500000001726310774222622033156 0ustar twernertwerner// XCatalogReader.java - Read XML Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.util.Vector; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogEntry; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.helpers.PublicId; import org.xml.sax.*; import javax.xml.parsers.*; /** * Parse "xcatalog" XML Catalog files, this is the XML Catalog format * developed by John Cowan and supported by Apache. * * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class XCatalogReader extends SAXCatalogReader implements SAXCatalogParser { /** The catalog object needs to be stored by the object so that * SAX callbacks can use it. */ protected Catalog catalog = null; /** Set the current catalog. */ public void setCatalog (Catalog catalog) { this.catalog = catalog; } /** @return the current catalog. */ public Catalog getCatalog () { return catalog; } /** The constructor * @param parserFactory */ public XCatalogReader(SAXParserFactory parserFactory) { super(parserFactory); } // ---------------------------------------------------------------------- // Implement the SAX DocumentHandler interface /** The SAX setDocumentLocator method does nothing. */ public void setDocumentLocator (Locator locator) { return; } /** The SAX startDocument method does nothing. */ public void startDocument () throws SAXException { return; } /** The SAX endDocument method does nothing. */ public void endDocument () throws SAXException { return; } /** * The SAX startElement method recognizes elements * from the plain catalog format and instantiates CatalogEntry * objects for them. * * @param namespaceURI The namespace name of the element. * @param localName The local name of the element. * @param qName The QName of the element. * @param atts The list of attributes on the element. * * @see CatalogEntry */ public void startElement (String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { int entryType = -1; Vector entryArgs = new Vector(); if (localName.equals("Base")) { entryType = catalog.BASE; entryArgs.add(atts.getValue("HRef")); catalog.getCatalogManager().debug.message(4, "Base", atts.getValue("HRef")); } else if (localName.equals("Delegate")) { entryType = catalog.DELEGATE_PUBLIC; entryArgs.add(atts.getValue("PublicId")); entryArgs.add(atts.getValue("HRef")); catalog.getCatalogManager().debug.message(4, "Delegate", PublicId.normalize(atts.getValue("PublicId")), atts.getValue("HRef")); } else if (localName.equals("Extend")) { entryType = catalog.CATALOG; entryArgs.add(atts.getValue("HRef")); catalog.getCatalogManager().debug.message(4, "Extend", atts.getValue("HRef")); } else if (localName.equals("Map")) { entryType = catalog.PUBLIC; entryArgs.add(atts.getValue("PublicId")); entryArgs.add(atts.getValue("HRef")); catalog.getCatalogManager().debug.message(4, "Map", PublicId.normalize(atts.getValue("PublicId")), atts.getValue("HRef")); } else if (localName.equals("Remap")) { entryType = catalog.SYSTEM; entryArgs.add(atts.getValue("SystemId")); entryArgs.add(atts.getValue("HRef")); catalog.getCatalogManager().debug.message(4, "Remap", atts.getValue("SystemId"), atts.getValue("HRef")); } else if (localName.equals("XMLCatalog")) { // nop, start of catalog } else { // This is equivalent to an invalid catalog entry type catalog.getCatalogManager().debug.message(1, "Invalid catalog entry type", localName); } if (entryType >= 0) { try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { catalog.getCatalogManager().debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { catalog.getCatalogManager().debug.message(1, "Invalid catalog entry", localName); } } } } /** The SAX endElement method does nothing. */ public void endElement (String namespaceURI, String localName, String qName) throws SAXException { return; } /** The SAX characters method does nothing. */ public void characters (char ch[], int start, int length) throws SAXException { return; } /** The SAX ignorableWhitespace method does nothing. */ public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { return; } /** The SAX processingInstruction method does nothing. */ public void processingInstruction (String target, String data) throws SAXException { return; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/SAXParserHandler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/S0000644000175000017500000001260510470642610033140 0ustar twernertwerner// SAXParserHandler.java - An entity-resolving DefaultHandler /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.io.IOException; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * An entity-resolving DefaultHandler. * *

This class provides a SAXParser DefaultHandler that performs * entity resolution. *

* * @author Norman Walsh * Norman.Walsh@Sun.COM * @version 1.0 */ public class SAXParserHandler extends DefaultHandler { private EntityResolver er = null; private ContentHandler ch = null; public SAXParserHandler() { super(); } public void setEntityResolver(EntityResolver er) { this.er = er; } public void setContentHandler(ContentHandler ch) { this.ch = ch; } // Entity Resolver public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (er != null) { try { return er.resolveEntity(publicId, systemId); } catch (IOException e) { System.out.println("resolveEntity threw IOException!"); return null; } } else { return null; } } // Content Handler public void characters(char[] ch, int start, int length) throws SAXException { if (this.ch != null) { this.ch.characters(ch, start, length); } } public void endDocument() throws SAXException { if (ch != null) { ch.endDocument(); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (ch != null) { ch.endElement(namespaceURI, localName, qName); } } public void endPrefixMapping(String prefix) throws SAXException { if (ch != null) { ch.endPrefixMapping(prefix); } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (this.ch != null) { this.ch.ignorableWhitespace(ch, start, length); } } public void processingInstruction(String target, String data) throws SAXException { if (ch != null) { ch.processingInstruction(target, data); } } public void setDocumentLocator(Locator locator) { if (ch != null) { ch.setDocumentLocator(locator); } } public void skippedEntity(String name) throws SAXException { if (ch != null) { ch.skippedEntity(name); } } public void startDocument() throws SAXException { if (ch != null) { ch.startDocument(); } } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (ch != null) { ch.startElement(namespaceURI, localName, qName, atts); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { if (ch != null) { ch.startPrefixMapping(prefix, uri); } } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/DOMCatalogParser.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/D0000644000175000017500000000676110470642610033127 0ustar twernertwerner// DOMCatalogParser.java - An interface for reading catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import org.jboss.util.xml.catalog.Catalog; import org.w3c.dom.Node; /** * The DOMCatalogParser interface. * *

This interface must be implemented in order for a class to * participate as a parser for the DOMCatalogReader. * * @see Catalog * @see DOMCatalogReader * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public interface DOMCatalogParser { /** * Parse a DOM node as a catalog entry. * *

This method is expected to analyze the specified node and * construct appropriate catalog entry(ies) from it.

* * @param catalog The catalog for which this node is being considered. * @param node The DOM Node from the catalog. */ public void parseCatalogEntry(Catalog catalog, Node node); } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/SAXCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/S0000644000175000017500000004151310774222622033144 0ustar twernertwerner// SAXCatalogReader.java - Read XML Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.util.Hashtable; import java.io.IOException; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.MalformedURLException; import java.net.UnknownHostException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import org.xml.sax.AttributeList; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DocumentHandler; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.CatalogManager; import org.jboss.util.xml.catalog.helpers.Debug; import org.jboss.util.xml.catalog.readers.CatalogReader; /** * A SAX-based CatalogReader. * *

This class is used to read XML Catalogs using the SAX. This reader * has an advantage over the DOM-based reader in that it functions on * the stream of SAX events. It has the disadvantage * that it cannot look around in the tree.

* *

Since the choice of CatalogReaders (in the InputStream case) can only * be made on the basis of MIME type, the following problem occurs: only * one CatalogReader can exist for all XML mime types. In order to get * around this problem, the SAXCatalogReader relies on a set of external * CatalogParsers to actually build the catalog.

* *

The selection of CatalogParsers is made on the basis of the QName * of the root element of the document.

* * @see Catalog * @see CatalogReader * @see SAXCatalogReader * @see TextCatalogReader * @see DOMCatalogParser * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings({"unchecked", "deprecation"}) public class SAXCatalogReader implements CatalogReader, ContentHandler, DocumentHandler { /** The SAX Parser Factory */ protected SAXParserFactory parserFactory = null; /** The SAX Parser Class */ protected String parserClass = null; /** * Mapping table from QNames to CatalogParser classes. * *

Each key in this hash table has the form "elementname" * or "{namespaceuri}elementname". The former is used if the * namespace URI is null.

*/ protected Hashtable namespaceMap = new Hashtable(); /** The parser in use for the current catalog. */ private SAXCatalogParser saxParser = null; /** Set if something goes horribly wrong. It allows the class to * ignore the rest of the events that are received. */ private boolean abandonHope = false; /** The Catalog that we're working for. */ private Catalog catalog; /** Set the XML SAX Parser Factory. * @param parserFactory */ public void setParserFactory(SAXParserFactory parserFactory) { this.parserFactory = parserFactory; } /** Set the XML SAX Parser Class * @param parserClass */ public void setParserClass(String parserClass) { this.parserClass = parserClass; } /** @return the parser factory currently in use. */ public SAXParserFactory getParserFactory() { return parserFactory; } /** @return the parser class currently in use. */ public String getParserClass() { return parserClass; } /** The debug class to use for this reader. * * This is a bit of a hack. Anyway, whenever we read for a catalog, * we extract the debug object * from the catalog's manager so that we can use it to print messages. * * In production, we don't really expect any messages so it doesn't * really matter. But it's still a bit of a hack. */ protected Debug debug = CatalogManager.getStaticManager().debug; /** The constructor */ public SAXCatalogReader() { parserFactory = null; parserClass = null; } /** The constructor * @param parserFactory */ public SAXCatalogReader(SAXParserFactory parserFactory) { this.parserFactory = parserFactory; } /** The constructor * @param parserClass */ public SAXCatalogReader(String parserClass) { this.parserClass = parserClass; } /** Set the SAXCatalogParser class for the given namespace/root * element type. * @param namespaceURI * @param rootElement * @param parserClass */ public void setCatalogParser(String namespaceURI, String rootElement, String parserClass) { if (namespaceURI == null) { namespaceMap.put(rootElement, parserClass); } else { namespaceMap.put("{"+namespaceURI+"}"+rootElement, parserClass); } } /** Get the SAXCatalogParser class for the given namespace/root * element type. * @param namespaceURI * @param rootElement * @return the catalog parser */ public String getCatalogParser(String namespaceURI, String rootElement) { if (namespaceURI == null) { return (String) namespaceMap.get(rootElement); } else { return (String) namespaceMap.get("{"+namespaceURI+"}"+rootElement); } } /** * Parse an XML Catalog file. * * @param catalog The catalog to which this catalog file belongs * @param fileUrl The URL or filename of the catalog file to process * * @throws MalformedURLException Improper fileUrl * @throws IOException Error reading catalog file */ public void readCatalog(Catalog catalog, String fileUrl) throws MalformedURLException, IOException, CatalogException { URL url = null; try { url = new URL(fileUrl); } catch (MalformedURLException e) { url = new URL("file:///" + fileUrl); } debug = catalog.getCatalogManager().debug; try { URLConnection urlCon = url.openConnection(); readCatalog(catalog, urlCon.getInputStream()); } catch (FileNotFoundException e) { catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found", url.toString()); } } /** * Parse an XML Catalog stream. * * @param catalog The catalog to which this catalog file belongs * @param is The input stream from which the catalog will be read * * @throws MalformedURLException Improper fileUrl * @throws IOException Error reading catalog file * @throws CatalogException A Catalog exception */ public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException { // Create an instance of the parser if (parserFactory == null && parserClass == null) { debug.message(1, "Cannot read SAX catalog without a parser"); throw new CatalogException(CatalogException.UNPARSEABLE); } debug = catalog.getCatalogManager().debug; EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver(); this.catalog = catalog; try { if (parserFactory != null) { SAXParser parser = parserFactory.newSAXParser(); SAXParserHandler spHandler = new SAXParserHandler(); spHandler.setContentHandler(this); if (bResolver != null) { spHandler.setEntityResolver(bResolver); } parser.parse(new InputSource(is), spHandler); } else { Parser parser = (Parser) Class.forName(parserClass).newInstance(); parser.setDocumentHandler(this); if (bResolver != null) { parser.setEntityResolver(bResolver); } parser.parse(new InputSource(is)); } } catch (ClassNotFoundException cnfe) { throw new CatalogException(CatalogException.UNPARSEABLE); } catch (IllegalAccessException iae) { throw new CatalogException(CatalogException.UNPARSEABLE); } catch (InstantiationException ie) { throw new CatalogException(CatalogException.UNPARSEABLE); } catch (ParserConfigurationException pce) { throw new CatalogException(CatalogException.UNKNOWN_FORMAT); } catch (SAXException se) { Exception e = se.getException(); // FIXME: there must be a better way UnknownHostException uhe = new UnknownHostException(); FileNotFoundException fnfe = new FileNotFoundException(); if (e != null) { if (e.getClass() == uhe.getClass()) { throw new CatalogException(CatalogException.PARSE_FAILED, e.toString()); } else if (e.getClass() == fnfe.getClass()) { throw new CatalogException(CatalogException.PARSE_FAILED, e.toString()); } } throw new CatalogException(se); } } // ---------------------------------------------------------------------- // Implement the SAX ContentHandler interface /** The SAX setDocumentLocator method. Does nothing. */ public void setDocumentLocator (Locator locator) { if (saxParser != null) { saxParser.setDocumentLocator(locator); } } /** The SAX startDocument method. Does nothing. */ public void startDocument () throws SAXException { saxParser = null; abandonHope = false; return; } /** The SAX endDocument method. Does nothing. */ public void endDocument ()throws SAXException { if (saxParser != null) { saxParser.endDocument(); } } /** * The SAX startElement method. * *

The catalog parser is selected based on the namespace of the * first element encountered in the catalog.

*/ public void startElement (String name, AttributeList atts) throws SAXException { if (abandonHope) { return; } if (saxParser == null) { String prefix = ""; if (name.indexOf(':') > 0) { prefix = name.substring(0, name.indexOf(':')); } String localName = name; if (localName.indexOf(':') > 0) { localName = localName.substring(localName.indexOf(':')+1); } String namespaceURI = null; if (prefix.equals("")) { namespaceURI = atts.getValue("xmlns"); } else { namespaceURI = atts.getValue("xmlns:" + prefix); } String saxParserClass = getCatalogParser(namespaceURI, localName); if (saxParserClass == null) { abandonHope = true; if (namespaceURI == null) { debug.message(2, "No Catalog parser for " + name); } else { debug.message(2, "No Catalog parser for " + "{" + namespaceURI + "}" + name); } return; } try { saxParser = (SAXCatalogParser) Class.forName(saxParserClass).newInstance(); saxParser.setCatalog(catalog); saxParser.startDocument(); saxParser.startElement(name, atts); } catch (ClassNotFoundException cnfe) { saxParser = null; abandonHope = true; debug.message(2, cnfe.toString()); } catch (InstantiationException ie) { saxParser = null; abandonHope = true; debug.message(2, ie.toString()); } catch (IllegalAccessException iae) { saxParser = null; abandonHope = true; debug.message(2, iae.toString()); } catch (ClassCastException cce ) { saxParser = null; abandonHope = true; debug.message(2, cce.toString()); } } else { saxParser.startElement(name, atts); } } /** * The SAX2 startElement method. * *

The catalog parser is selected based on the namespace of the * first element encountered in the catalog.

*/ public void startElement (String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (abandonHope) { return; } if (saxParser == null) { String saxParserClass = getCatalogParser(namespaceURI, localName); if (saxParserClass == null) { abandonHope = true; if (namespaceURI == null) { debug.message(2, "No Catalog parser for " + localName); } else { debug.message(2, "No Catalog parser for " + "{" + namespaceURI + "}" + localName); } return; } try { saxParser = (SAXCatalogParser) Class.forName(saxParserClass).newInstance(); saxParser.setCatalog(catalog); saxParser.startDocument(); saxParser.startElement(namespaceURI, localName, qName, atts); } catch (ClassNotFoundException cnfe) { saxParser = null; abandonHope = true; debug.message(2, cnfe.toString()); } catch (InstantiationException ie) { saxParser = null; abandonHope = true; debug.message(2, ie.toString()); } catch (IllegalAccessException iae) { saxParser = null; abandonHope = true; debug.message(2, iae.toString()); } catch (ClassCastException cce ) { saxParser = null; abandonHope = true; debug.message(2, cce.toString()); } } else { saxParser.startElement(namespaceURI, localName, qName, atts); } } /** The SAX endElement method. Does nothing. */ public void endElement (String name) throws SAXException { if (saxParser != null) { saxParser.endElement(name); } } /** The SAX2 endElement method. Does nothing. */ public void endElement (String namespaceURI, String localName, String qName) throws SAXException { if (saxParser != null) { saxParser.endElement(namespaceURI, localName, qName); } } /** The SAX characters method. Does nothing. */ public void characters (char ch[], int start, int length) throws SAXException { if (saxParser != null) { saxParser.characters(ch, start, length); } } /** The SAX ignorableWhitespace method. Does nothing. */ public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { if (saxParser != null) { saxParser.ignorableWhitespace(ch, start, length); } } /** The SAX processingInstruction method. Does nothing. */ public void processingInstruction (String target, String data) throws SAXException { if (saxParser != null) { saxParser.processingInstruction(target, data); } } /** The SAX startPrefixMapping method. Does nothing. */ public void startPrefixMapping (String prefix, String uri) throws SAXException { if (saxParser != null) { saxParser.startPrefixMapping (prefix, uri); } } /** The SAX endPrefixMapping method. Does nothing. */ public void endPrefixMapping (String prefix) throws SAXException { if (saxParser != null) { saxParser.endPrefixMapping (prefix); } } /** The SAX skippedentity method. Does nothing. */ public void skippedEntity (String name) throws SAXException { if (saxParser != null) { saxParser.skippedEntity(name); } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/CatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/C0000644000175000017500000001046510774222622033126 0ustar twernertwerner// CatalogReader.java - An interface for reading catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.io.IOException; import java.net.MalformedURLException; import java.io.InputStream; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogException; /** * The CatalogReader interface. * *

The Catalog class requires that classes implement this interface * in order to be used to read catalogs. Examples of CatalogReaders * include the TextCatalogReader, the SAXCatalogReader, and the * DOMCatalogReader.

* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public interface CatalogReader { /** * Read a catalog from a file. * *

This class reads a catalog from a URL.

* * @param catalog The catalog for which this reader is called. * @param fileUrl The URL of a document to be read. * @throws MalformedURLException if the specified URL cannot be * turned into a URL object. * @throws IOException if the URL cannot be read. * @throws CatalogException for any error */ public void readCatalog(Catalog catalog, String fileUrl) throws MalformedURLException, IOException, CatalogException; /** * Read a catalog from an input stream. * *

This class reads a catalog from an input stream.

* * @param catalog The catalog for which this reader is called. * @param is The input stream that is to be read. * @throws IOException if the URL cannot be read. * @throws CatalogException for any error */ public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException; } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/DOMCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/D0000644000175000017500000002417510774222622033132 0ustar twernertwerner// DOMCatalogReader.java - Read XML Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.util.Hashtable; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.MalformedURLException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.helpers.Namespaces; import org.jboss.util.xml.catalog.readers.CatalogReader; import org.xml.sax.SAXException; import org.w3c.dom.*; /** * A DOM-based CatalogReader. * *

This class is used to read XML Catalogs using the DOM. This reader * has an advantage over the SAX-based reader that it can analyze the * DOM tree rather than simply a series of SAX events. It has the disadvantage * that it requires all of the code necessary to build and walk a DOM * tree.

* *

Since the choice of CatalogReaders (in the InputStream case) can only * be made on the basis of MIME type, the following problem occurs: only * one CatalogReader can exist for all XML mime types. In order to get * around this problem, the DOMCatalogReader relies on a set of external * CatalogParsers to actually build the catalog.

* *

The selection of CatalogParsers is made on the basis of the QName * of the root element of the document.

* *

This class requires the Java API for XML Parsing.

* * @see Catalog * @see CatalogReader * @see SAXCatalogReader * @see TextCatalogReader * @see DOMCatalogParser * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class DOMCatalogReader implements CatalogReader { /** * Mapping table from QNames to CatalogParser classes. * *

Each key in this hash table has the form "elementname" * or "{namespaceuri}elementname". The former is used if the * namespace URI is null.

*/ protected Hashtable namespaceMap = new Hashtable(); /** * Add a new parser to the reader. * *

This method associates the specified parserClass with the * namespaceURI/rootElement names specified.

* * @param namespaceURI The namespace URI. Not the prefix. * @param rootElement The name of the root element. * @param parserClass The name of the parserClass to instantiate * for this kind of catalog. */ public void setCatalogParser(String namespaceURI, String rootElement, String parserClass) { if (namespaceURI == null) { namespaceMap.put(rootElement, parserClass); } else { namespaceMap.put("{"+namespaceURI+"}"+rootElement, parserClass); } } /** * Get the name of the parser class for a given catalog type. * *

This method returns the parserClass associated with the * namespaceURI/rootElement names specified.

* * @param namespaceURI The namespace URI. Not the prefix. * @param rootElement The name of the root element. * @return The parser class. */ public String getCatalogParser(String namespaceURI, String rootElement) { if (namespaceURI == null) { return (String) namespaceMap.get(rootElement); } else { return (String) namespaceMap.get("{"+namespaceURI+"}"+rootElement); } } /** * Null constructor; something for subclasses to call. */ public DOMCatalogReader() { } /** * Read a catalog from an input stream. * *

This class reads a catalog from an input stream:

* *
    *
  • Based on the QName of the root element, it determines which * parser to instantiate for this catalog.
  • *
  • It constructs a DOM Document from the catalog and
  • *
  • For each child of the root node, it calls the parser's * parseCatalogEntry method. This method is expected to make * appropriate calls back into the catalog to add entries for the * entries in the catalog. It is free to do this in whatever manner * is appropriate (perhaps using just the node passed in, perhaps * wandering arbitrarily throughout the tree).
  • *
* * @param catalog The catalog for which this reader is called. * @param is The input stream that is to be read. * @throws IOException if the URL cannot be read. * (For example, if it is supposed to be XML and isn't well-formed or * if the parser class cannot be instantiated.) */ public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException { DocumentBuilderFactory factory = null; DocumentBuilder builder = null; factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new CatalogException(CatalogException.UNPARSEABLE); } Document doc = null; try { doc = builder.parse(is); } catch (SAXException se) { throw new CatalogException(CatalogException.UNKNOWN_FORMAT); } Element root = doc.getDocumentElement(); String namespaceURI = Namespaces.getNamespaceURI(root); String localName = Namespaces.getLocalName(root); String domParserClass = getCatalogParser(namespaceURI, localName); if (domParserClass == null) { if (namespaceURI == null) { catalog.getCatalogManager().debug.message(1, "No Catalog parser for " + localName); } else { catalog.getCatalogManager().debug.message(1, "No Catalog parser for " + "{" + namespaceURI + "}" + localName); } return; } DOMCatalogParser domParser = null; try { domParser = (DOMCatalogParser) Class.forName(domParserClass).newInstance(); } catch (ClassNotFoundException cnfe) { catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass); throw new CatalogException(CatalogException.UNPARSEABLE); } catch (InstantiationException ie) { catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass); throw new CatalogException(CatalogException.UNPARSEABLE); } catch (IllegalAccessException iae) { catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass); throw new CatalogException(CatalogException.UNPARSEABLE); } catch (ClassCastException cce ) { catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass); throw new CatalogException(CatalogException.UNPARSEABLE); } Node node = root.getFirstChild(); while (node != null) { domParser.parseCatalogEntry(catalog, node); node = node.getNextSibling(); } } /** * Read the catalog behind the specified URL. * * @see #readCatalog(Catalog, InputStream) * * @param catalog The catalog for which we are reading. * @param fileUrl The URL of the document that should be read. * * @throws MalformedURLException if the specified URL cannot be * turned into a URL object. * @throws IOException if the URL cannot be read. */ public void readCatalog(Catalog catalog, String fileUrl) throws MalformedURLException, IOException, CatalogException { URL url = new URL(fileUrl); URLConnection urlCon = url.openConnection(); readCatalog(catalog, urlCon.getInputStream()); } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/OASISXMLCatalogReader.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/readers/O0000644000175000017500000004271710774222622033147 0ustar twernertwerner// OASISXMLCatalogReader.java - Read XML Catalog files /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog.readers; import java.util.Enumeration; import java.util.Stack; import java.util.Vector; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.CatalogEntry; import org.jboss.util.xml.catalog.CatalogException; import org.jboss.util.xml.catalog.helpers.PublicId; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * Parse OASIS Entity Resolution Technical Committee * XML Catalog files. * * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class OASISXMLCatalogReader extends SAXCatalogReader implements SAXCatalogParser { /** The catalog object needs to be stored by the object so that * SAX callbacks can use it. */ protected Catalog catalog = null; /** The namespace name of OASIS ERTC catalogs */ public static final String namespaceName = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; /** The namespace name of OASIS ERTC TR9401 catalog extension */ public static final String tr9401NamespaceName = "urn:oasis:names:tc:entity:xmlns:tr9401:catalog"; protected Stack baseURIStack = new Stack(); protected Stack overrideStack = new Stack(); protected Stack namespaceStack = new Stack(); /** Set the current catalog. */ public void setCatalog (Catalog catalog) { this.catalog = catalog; debug = catalog.getCatalogManager().debug; } /** @return the current catalog. */ public Catalog getCatalog () { return catalog; } /** * Are we in an extension namespace? * * @return true if the current stack of open namespaces includes * an extension namespace. */ protected boolean inExtensionNamespace() { boolean inExtension = false; Enumeration elements = namespaceStack.elements(); while (!inExtension && elements.hasMoreElements()) { String ns = (String) elements.nextElement(); if (ns == null) { inExtension = true; } else { inExtension = (!ns.equals(tr9401NamespaceName) && !ns.equals(namespaceName)); } } return inExtension; } // ---------------------------------------------------------------------- // Implement the SAX ContentHandler interface /** The SAX setDocumentLocator method does nothing. */ public void setDocumentLocator (Locator locator) { return; } /** The SAX startDocument method does nothing. */ public void startDocument () throws SAXException { baseURIStack.push(catalog.getCurrentBase()); overrideStack.push(catalog.getDefaultOverride()); return; } /** The SAX endDocument method does nothing. */ public void endDocument () throws SAXException { return; } /** * The SAX startElement method recognizes elements * from the plain catalog format and instantiates CatalogEntry * objects for them. * * @param namespaceURI The namespace name of the element. * @param localName The local name of the element. * @param qName The QName of the element. * @param atts The list of attributes on the element. * * @see CatalogEntry */ public void startElement (String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { int entryType = -1; Vector entryArgs = new Vector(); namespaceStack.push(namespaceURI); boolean inExtension = inExtensionNamespace(); if (namespaceURI != null && namespaceName.equals(namespaceURI) && !inExtension) { // This is an XML Catalog entry if (atts.getValue("xml:base") != null) { String baseURI = atts.getValue("xml:base"); entryType = Catalog.BASE; entryArgs.add(baseURI); baseURIStack.push(baseURI); debug.message(4, "xml:base", baseURI); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (base)", localName); } } entryType = -1; entryArgs = new Vector(); } else { baseURIStack.push(baseURIStack.peek()); } if ((localName.equals("catalog") || localName.equals("group")) && atts.getValue("prefer") != null) { String override = atts.getValue("prefer"); if (override.equals("public")) { override = "yes"; } else if (override.equals("system")) { override = "no"; } else { debug.message(1, "Invalid prefer: must be 'system' or 'public'", localName); override = catalog.getDefaultOverride(); } entryType = Catalog.OVERRIDE; entryArgs.add(override); overrideStack.push(override); debug.message(4, "override", override); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (override)", localName); } } entryType = -1; entryArgs = new Vector(); } else { overrideStack.push(overrideStack.peek()); } if (localName.equals("delegatePublic")) { if (checkAttributes(atts, "publicIdStartString", "catalog")) { entryType = Catalog.DELEGATE_PUBLIC; entryArgs.add(atts.getValue("publicIdStartString")); entryArgs.add(atts.getValue("catalog")); debug.message(4, "delegatePublic", PublicId.normalize(atts.getValue("publicIdStartString")), atts.getValue("catalog")); } } else if (localName.equals("delegateSystem")) { if (checkAttributes(atts, "systemIdStartString", "catalog")) { entryType = Catalog.DELEGATE_SYSTEM; entryArgs.add(atts.getValue("systemIdStartString")); entryArgs.add(atts.getValue("catalog")); debug.message(4, "delegateSystem", atts.getValue("systemIdStartString"), atts.getValue("catalog")); } } else if (localName.equals("delegateURI")) { if (checkAttributes(atts, "uriStartString", "catalog")) { entryType = Catalog.DELEGATE_URI; entryArgs.add(atts.getValue("uriStartString")); entryArgs.add(atts.getValue("catalog")); debug.message(4, "delegateURI", atts.getValue("uriStartString"), atts.getValue("catalog")); } } else if (localName.equals("rewriteSystem")) { if (checkAttributes(atts, "systemIdStartString", "rewritePrefix")) { entryType = Catalog.REWRITE_SYSTEM; entryArgs.add(atts.getValue("systemIdStartString")); entryArgs.add(atts.getValue("rewritePrefix")); debug.message(4, "rewriteSystem", atts.getValue("systemIdStartString"), atts.getValue("rewritePrefix")); } } else if (localName.equals("rewriteURI")) { if (checkAttributes(atts, "uriStartString", "rewritePrefix")) { entryType = Catalog.REWRITE_URI; entryArgs.add(atts.getValue("uriStartString")); entryArgs.add(atts.getValue("rewritePrefix")); debug.message(4, "rewriteURI", atts.getValue("uriStartString"), atts.getValue("rewritePrefix")); } } else if (localName.equals("nextCatalog")) { if (checkAttributes(atts, "catalog")) { entryType = Catalog.CATALOG; entryArgs.add(atts.getValue("catalog")); debug.message(4, "nextCatalog", atts.getValue("catalog")); } } else if (localName.equals("public")) { if (checkAttributes(atts, "publicId", "uri")) { entryType = Catalog.PUBLIC; entryArgs.add(atts.getValue("publicId")); entryArgs.add(atts.getValue("uri")); debug.message(4, "public", PublicId.normalize(atts.getValue("publicId")), atts.getValue("uri")); } } else if (localName.equals("system")) { if (checkAttributes(atts, "systemId", "uri")) { entryType = Catalog.SYSTEM; entryArgs.add(atts.getValue("systemId")); entryArgs.add(atts.getValue("uri")); debug.message(4, "system", atts.getValue("systemId"), atts.getValue("uri")); } } else if (localName.equals("uri")) { if (checkAttributes(atts, "name", "uri")) { entryType = Catalog.URI; entryArgs.add(atts.getValue("name")); entryArgs.add(atts.getValue("uri")); debug.message(4, "uri", atts.getValue("name"), atts.getValue("uri")); } } else if (localName.equals("catalog")) { // nop, start of catalog } else if (localName.equals("group")) { // nop, a group } else { // This is equivalent to an invalid catalog entry type debug.message(1, "Invalid catalog entry type", localName); } if (entryType >= 0) { try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry", localName); } } } } if (namespaceURI != null && tr9401NamespaceName.equals(namespaceURI) && !inExtension) { // This is a TR9401 Catalog entry if (atts.getValue("xml:base") != null) { String baseURI = atts.getValue("xml:base"); entryType = Catalog.BASE; entryArgs.add(baseURI); baseURIStack.push(baseURI); debug.message(4, "xml:base", baseURI); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (base)", localName); } } entryType = -1; entryArgs = new Vector(); } else { baseURIStack.push(baseURIStack.peek()); } if (localName.equals("doctype")) { entryType = catalog.DOCTYPE; entryArgs.add(atts.getValue("name")); entryArgs.add(atts.getValue("uri")); } else if (localName.equals("document")) { entryType = catalog.DOCUMENT; entryArgs.add(atts.getValue("uri")); } else if (localName.equals("dtddecl")) { entryType = catalog.DTDDECL; entryArgs.add(atts.getValue("publicId")); entryArgs.add(atts.getValue("uri")); } else if (localName.equals("entity")) { entryType = Catalog.ENTITY; entryArgs.add(atts.getValue("name")); entryArgs.add(atts.getValue("uri")); } else if (localName.equals("linktype")) { entryType = Catalog.LINKTYPE; entryArgs.add(atts.getValue("name")); entryArgs.add(atts.getValue("uri")); } else if (localName.equals("notation")) { entryType = Catalog.NOTATION; entryArgs.add(atts.getValue("name")); entryArgs.add(atts.getValue("uri")); } else if (localName.equals("sgmldecl")) { entryType = Catalog.SGMLDECL; entryArgs.add(atts.getValue("uri")); } else { // This is equivalent to an invalid catalog entry type debug.message(1, "Invalid catalog entry type", localName); } if (entryType >= 0) { try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry", localName); } } } } } public boolean checkAttributes (Attributes atts, String attName) { if (atts.getValue(attName) == null) { debug.message(1, "Error: required attribute " + attName + " missing."); return false; } else { return true; } } public boolean checkAttributes (Attributes atts, String attName1, String attName2) { return checkAttributes(atts, attName1) && checkAttributes(atts, attName2); } /** The SAX endElement method does nothing. */ public void endElement (String namespaceURI, String localName, String qName) throws SAXException { int entryType = -1; Vector entryArgs = new Vector(); boolean inExtension = inExtensionNamespace(); if (namespaceURI != null && !inExtension && (namespaceName.equals(namespaceURI) || tr9401NamespaceName.equals(namespaceURI))) { String popURI = (String) baseURIStack.pop(); String baseURI = (String) baseURIStack.peek(); if (!baseURI.equals(popURI)) { entryType = catalog.BASE; entryArgs.add(baseURI); debug.message(4, "(reset) xml:base", baseURI); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (rbase)", localName); } } } } if (namespaceURI != null && namespaceName.equals(namespaceURI) && !inExtension) { if (localName.equals("catalog") || localName.equals("group")) { String popOverride = (String) overrideStack.pop(); String override = (String) overrideStack.peek(); if (!override.equals(popOverride)) { entryType = catalog.OVERRIDE; entryArgs.add(override); overrideStack.push(override); debug.message(4, "(reset) override", override); try { CatalogEntry ce = new CatalogEntry(entryType, entryArgs); catalog.addEntry(ce); } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) { debug.message(1, "Invalid catalog entry type", localName); } else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) { debug.message(1, "Invalid catalog entry (roverride)", localName); } } } } } namespaceStack.pop(); return; } /** The SAX characters method does nothing. */ public void characters (char ch[], int start, int length) throws SAXException { return; } /** The SAX ignorableWhitespace method does nothing. */ public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { return; } /** The SAX processingInstruction method does nothing. */ public void processingInstruction (String target, String data) throws SAXException { return; } /** The SAX skippedEntity method does nothing. */ public void skippedEntity (String name) throws SAXException { return; } /** The SAX startPrefixMapping method does nothing. */ public void startPrefixMapping(String prefix, String uri) throws SAXException { return; } /** The SAX endPrefixMapping method does nothing. */ public void endPrefixMapping(String prefix) throws SAXException { return; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Resolver.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Resolver.0000644000175000017500000005712710774222622033204 0ustar twernertwerner// Resolver.java - Represents an extension of OASIS Open Catalog files. /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Vector; import javax.xml.parsers.SAXParserFactory; import org.jboss.util.xml.catalog.readers.ExtendedXMLCatalogReader; import org.jboss.util.xml.catalog.readers.OASISXMLCatalogReader; import org.jboss.util.xml.catalog.readers.SAXCatalogReader; import org.jboss.util.xml.catalog.readers.TR9401CatalogReader; import org.jboss.util.xml.catalog.readers.XCatalogReader; /** * An extension to OASIS Open Catalog files, this class supports * suffix-based matching and an external RFC2483 resolver. * * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class Resolver extends Catalog { /** * The URISUFFIX Catalog Entry type. * *

URI suffix entries match URIs that end in a specified suffix.

*/ public static final int URISUFFIX = CatalogEntry.addEntryType("URISUFFIX", 2); /** * The SYSTEMSUFFIX Catalog Entry type. * *

System suffix entries match system identifiers that end in a * specified suffix.

*/ public static final int SYSTEMSUFFIX = CatalogEntry.addEntryType("SYSTEMSUFFIX", 2); /** * The RESOLVER Catalog Entry type. * *

A hook for providing support for web-based backup resolvers.

*/ public static final int RESOLVER = CatalogEntry.addEntryType("RESOLVER", 1); /** * The SYSTEMREVERSE Catalog Entry type. * *

This is a bit of a hack. There's no actual SYSTEMREVERSE entry, * but this entry type is used to indicate that a reverse lookup is * being performed. (This allows the Resolver to implement * RFC2483 I2N and I2NS.) */ public static final int SYSTEMREVERSE = CatalogEntry.addEntryType("SYSTEMREVERSE", 1); /** * Setup readers. */ @SuppressWarnings("deprecation") public void setupReaders() { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); SAXCatalogReader saxReader = new SAXCatalogReader(spf); saxReader.setCatalogParser(null, "XMLCatalog", XCatalogReader.class.getName()); saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName, "catalog", ExtendedXMLCatalogReader.class.getName()); addReader("application/xml", saxReader); TR9401CatalogReader textReader = new TR9401CatalogReader(); addReader("text/plain", textReader); } /** * Cleanup and process a Catalog entry. * *

This method processes each Catalog entry, changing mapped * relative system identifiers into absolute ones (based on the current * base URI), and maintaining other information about the current * catalog.

* * @param entry The CatalogEntry to process. */ public void addEntry(CatalogEntry entry) { int type = entry.getEntryType(); if (type == URISUFFIX) { String suffix = normalizeURI(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "URISUFFIX", suffix, fsi); } else if (type == SYSTEMSUFFIX) { String suffix = normalizeURI(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "SYSTEMSUFFIX", suffix, fsi); } super.addEntry(entry); } /** * Return the applicable URI. * *

If a URI entry exists in the Catalog * for the URI specified, return the mapped value.

* *

In the Resolver (as opposed to the Catalog) class, if the * URI isn't found by the usual algorithm, URISUFFIX entries are * considered.

* *

URI comparison is case sensitive.

* * @param uri The URI to locate in the catalog. * * @return The resolved URI. * * @throws MalformedURLException The system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveURI(String uri) throws MalformedURLException, IOException { String resolved = super.resolveURI(uri); if (resolved != null) { return resolved; } Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == RESOLVER) { resolved = resolveExternalSystem(uri, e.getEntryArg(0)); if (resolved != null) { return resolved; } } else if (e.getEntryType() == URISUFFIX) { String suffix = e.getEntryArg(0); String result = e.getEntryArg(1); if (suffix.length() <= uri.length() && uri.substring(uri.length()-suffix.length()).equals(suffix)) { return result; } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(Catalog.URI, null, null, uri); } /** * Return the applicable SYSTEM system identifier, resorting * to external RESOLVERs if necessary. * *

If a SYSTEM entry exists in the Catalog * for the system ID specified, return the mapped value.

* *

In the Resolver (as opposed to the Catalog) class, if the * URI isn't found by the usual algorithm, SYSTEMSUFFIX entries are * considered.

* *

On Windows-based operating systems, the comparison between * the system identifier provided and the SYSTEM entries in the * Catalog is case-insensitive.

* * @param systemId The system ID to locate in the catalog. * * @return The system identifier to use for systemId. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveSystem(String systemId) throws MalformedURLException, IOException { String resolved = super.resolveSystem(systemId); if (resolved != null) { return resolved; } Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == RESOLVER) { resolved = resolveExternalSystem(systemId, e.getEntryArg(0)); if (resolved != null) { return resolved; } } else if (e.getEntryType() == SYSTEMSUFFIX) { String suffix = e.getEntryArg(0); String result = e.getEntryArg(1); if (suffix.length() <= systemId.length() && systemId.substring(systemId.length()-suffix.length()).equals(suffix)) { return result; } } } return resolveSubordinateCatalogs(Catalog.SYSTEM, null, null, systemId); } /** * Return the applicable PUBLIC or SYSTEM identifier, resorting * to external resolvers if necessary. * *

This method searches the Catalog and returns the system * identifier specified for the given system or * public identifiers. If * no appropriate PUBLIC or SYSTEM entry is found in the Catalog, * null is returned.

* *

Note that a system or public identifier in the current catalog * (or subordinate catalogs) will be used in preference to an * external resolver. Further, if a systemId is present, the external * resolver(s) will be queried for that before the publicId.

* * @param publicId The public identifier to locate in the catalog. * Public identifiers are normalized before comparison. * @param systemId The nominal system identifier for the entity * in question (as provided in the source document). * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. * * @return The system identifier to use. * Note that the nominal system identifier is not returned if a * match is not found in the catalog, instead null is returned * to indicate that no match was found. */ public String resolvePublic(String publicId, String systemId) throws MalformedURLException, IOException { String resolved = super.resolvePublic(publicId, systemId); if (resolved != null) { return resolved; } Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == RESOLVER) { if (systemId != null) { resolved = resolveExternalSystem(systemId, e.getEntryArg(0)); if (resolved != null) { return resolved; } } resolved = resolveExternalPublic(publicId, e.getEntryArg(0)); if (resolved != null) { return resolved; } } } return resolveSubordinateCatalogs(Catalog.PUBLIC, null, publicId, systemId); } /** * Query an external RFC2483 resolver for a system identifier. * * @param systemId The system ID to locate. * @param resolver The name of the resolver to use. * * @return The system identifier to use for the systemId. * @throws MalformedURLException * @throws IOException */ protected String resolveExternalSystem(String systemId, String resolver) throws MalformedURLException, IOException { Resolver r = queryResolver(resolver, "i2l", systemId, null); if (r != null) { return r.resolveSystem(systemId); } else { return null; } } /** * Query an external RFC2483 resolver for a public identifier. * * @param publicId The system ID to locate. * @param resolver The name of the resolver to use. * * @throws MalformedURLException * @throws IOException * @return The system identifier to use for the systemId. */ protected String resolveExternalPublic(String publicId, String resolver) throws MalformedURLException, IOException { Resolver r = queryResolver(resolver, "fpi2l", publicId, null); if (r != null) { return r.resolvePublic(publicId, null); } else { return null; } } /** * Query an external RFC2483 resolver. * * @param resolver The URL of the RFC2483 resolver. * @param command The command to send the resolver. * @param arg1 The first argument to the resolver. * @param arg2 The second argument to the resolver, usually null. * * @return The Resolver constructed. */ protected Resolver queryResolver(String resolver, String command, String arg1, String arg2) { String RFC2483 = resolver + "?command=" + command + "&format=tr9401&uri=" + arg1 + "&uri2=" + arg2; try { URL url = new URL(RFC2483); URLConnection urlCon = url.openConnection(); urlCon.setUseCaches(false); Resolver r = (Resolver) newCatalog(); String cType = urlCon.getContentType(); // I don't care about the character set or subtype if (cType.indexOf(";") > 0) { cType = cType.substring(0, cType.indexOf(";")); } r.parseCatalog(cType, urlCon.getInputStream()); return r; } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.UNPARSEABLE) { catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483); } else if (cex.getExceptionType() == CatalogException.UNKNOWN_FORMAT) { catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483); } return null; } catch (MalformedURLException mue) { catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483); return null; } catch (IOException ie) { catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483); return null; } } /** * Append two vectors, returning the result. * * @param vec The first vector * @param appvec The vector to be appended * @return The vector vec, with appvec's elements appended to it */ private Vector appendVector(Vector vec, Vector appvec) { if (appvec != null) { for (int count = 0; count < appvec.size(); count++) { vec.addElement(appvec.elementAt(count)); } } return vec; } /** * Find the URNs for a given system identifier in all catalogs. * * @param systemId The system ID to locate. * * @throws MalformedURLException * @throws IOException * @return A vector of URNs that map to the systemId. */ public Vector resolveAllSystemReverse(String systemId) throws MalformedURLException, IOException { Vector resolved = new Vector(); // If there's a SYSTEM entry in this catalog, use it if (systemId != null) { Vector localResolved = resolveLocalSystemReverse(systemId); resolved = appendVector(resolved, localResolved); } // Otherwise, look in the subordinate catalogs Vector subResolved = resolveAllSubordinateCatalogs(SYSTEMREVERSE, null, null, systemId); return appendVector(resolved, subResolved); } /** * Find the URN for a given system identifier. * * @param systemId The system ID to locate. * * @throws MalformedURLException * @throws IOException * @return A (single) URN that maps to the systemId. */ public String resolveSystemReverse(String systemId) throws MalformedURLException, IOException { Vector resolved = resolveAllSystemReverse(systemId); if (resolved != null && resolved.size() > 0) { return (String) resolved.elementAt(0); } else { return null; } } /** * Return the applicable SYSTEM system identifiers. * *

If one or more SYSTEM entries exists in the Catalog * for the system ID specified, return the mapped values.

* *

The caller is responsible for doing any necessary * normalization of the system identifier before calling * this method. For example, a relative system identifier in * a document might be converted to an absolute system identifier * before attempting to resolve it.

* *

Note that this function will force all subordinate catalogs * to be loaded.

* *

On Windows-based operating systems, the comparison between * the system identifier provided and the SYSTEM entries in the * Catalog is case-insensitive.

* * @param systemId The system ID to locate in the catalog. * * @return The system identifier to use for the notation. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public Vector resolveAllSystem(String systemId) throws MalformedURLException, IOException { Vector resolutions = new Vector(); // If there are SYSTEM entries in this catalog, start with them if (systemId != null) { Vector localResolutions = resolveAllLocalSystem(systemId); resolutions = appendVector(resolutions, localResolutions); } // Then look in the subordinate catalogs Vector subResolutions = resolveAllSubordinateCatalogs(SYSTEM, null, null, systemId); resolutions = appendVector(resolutions, subResolutions); if (resolutions.size() > 0) { return resolutions; } else { return null; } } /** * Return all applicable SYSTEM system identifiers in this * catalog. * *

If one or more SYSTEM entries exists in the catalog file * for the system ID specified, return the mapped values.

* * @param systemId The system ID to locate in the catalog * * @return A vector of the mapped system identifiers or null */ private Vector resolveAllLocalSystem(String systemId) { Vector map = new Vector(); String osname = System.getProperty("os.name"); boolean windows = (osname.indexOf("Windows") >= 0); Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == SYSTEM && (e.getEntryArg(0).equals(systemId) || (windows && e.getEntryArg(0).equalsIgnoreCase(systemId)))) { map.addElement(e.getEntryArg(1)); } } if (map.size() == 0) { return null; } else { return map; } } /** * Find the URNs for a given system identifier in the current catalog. * * @param systemId The system ID to locate. * * @return A vector of URNs that map to the systemId. */ private Vector resolveLocalSystemReverse(String systemId) { Vector map = new Vector(); String osname = System.getProperty("os.name"); boolean windows = (osname.indexOf("Windows") >= 0); Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == SYSTEM && (e.getEntryArg(1).equals(systemId) || (windows && e.getEntryArg(1).equalsIgnoreCase(systemId)))) { map.addElement(e.getEntryArg(0)); } } if (map.size() == 0) { return null; } else { return map; } } /** * Search the subordinate catalogs, in order, looking for all * match. * *

This method searches the Catalog and returns all of the system * identifiers specified for the given entity type with the given * name, public, and system identifiers. In some contexts, these * may be null.

* * @param entityType The CatalogEntry type for which this query is * being conducted. This is necessary in order to do the approprate * query on a subordinate catalog. * @param entityName The name of the entity being searched for, if * appropriate. * @param publicId The public identifier of the entity in question * (as provided in the source document). * @param systemId The nominal system identifier for the entity * in question (as provided in the source document). * * @throws MalformedURLException The formal system identifier of a * delegated catalog cannot be turned into a valid URL. * @throws IOException Error reading delegated catalog file. * * @return The system identifier to use. * Note that the nominal system identifier is not returned if a * match is not found in the catalog, instead null is returned * to indicate that no match was found. */ private synchronized Vector resolveAllSubordinateCatalogs(int entityType, String entityName, String publicId, String systemId) throws MalformedURLException, IOException { Vector resolutions = new Vector(); for (int catPos = 0; catPos < catalogs.size(); catPos++) { Resolver c = null; try { c = (Resolver) catalogs.elementAt(catPos); } catch (ClassCastException e) { String catfile = (String) catalogs.elementAt(catPos); c = (Resolver) newCatalog(); try { c.parseCatalog(catfile); } catch (MalformedURLException mue) { catalogManager.debug.message(1, "Malformed Catalog URL", catfile); } catch (FileNotFoundException fnfe) { catalogManager.debug.message(1, "Failed to load catalog, file not found", catfile); } catch (IOException ioe) { catalogManager.debug.message(1, "Failed to load catalog, I/O error", catfile); } catalogs.setElementAt(c, catPos); } String resolved = null; // Ok, now what are we supposed to call here? if (entityType == DOCTYPE) { resolved = c.resolveDoctype(entityName, publicId, systemId); if (resolved != null) { // Only find one DOCTYPE resolution resolutions.addElement(resolved); return resolutions; } } else if (entityType == DOCUMENT) { resolved = c.resolveDocument(); if (resolved != null) { // Only find one DOCUMENT resolution resolutions.addElement(resolved); return resolutions; } } else if (entityType == ENTITY) { resolved = c.resolveEntity(entityName, publicId, systemId); if (resolved != null) { // Only find one ENTITY resolution resolutions.addElement(resolved); return resolutions; } } else if (entityType == NOTATION) { resolved = c.resolveNotation(entityName, publicId, systemId); if (resolved != null) { // Only find one NOTATION resolution resolutions.addElement(resolved); return resolutions; } } else if (entityType == PUBLIC) { resolved = c.resolvePublic(publicId, systemId); if (resolved != null) { // Only find one PUBLIC resolution resolutions.addElement(resolved); return resolutions; } } else if (entityType == SYSTEM) { Vector localResolutions = c.resolveAllSystem(systemId); resolutions = appendVector(resolutions, localResolutions); break; } else if (entityType == SYSTEMREVERSE) { Vector localResolutions = c.resolveAllSystemReverse(systemId); resolutions = appendVector(resolutions, localResolutions); } } if (resolutions != null) { return resolutions; } else { return null; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogManager.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogMa0000644000175000017500000006101110774222622033140 0ustar twernertwerner// CatalogManager.java - Access CatalogManager.properties /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; import java.io.InputStream; import java.net.URL; import java.net.MalformedURLException; import java.util.MissingResourceException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.StringTokenizer; import java.util.Vector; import org.jboss.util.xml.catalog.Catalog; import org.jboss.util.xml.catalog.helpers.BootstrapResolver; import org.jboss.util.xml.catalog.helpers.Debug; /** * CatalogManager provides an interface to the catalog properties. * *

Properties can come from two places: from system properties or * from a CatalogManager.properties file. This class provides a transparent * interface to both, with system properties preferred over property file values.

* *

The following table summarizes the properties:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
System PropertyCatalogManager.properties
Property
Description
xml.catalog.ignoreMissing If true, a missing CatalogManager.properties file or missing properties * within that file will not generate warning messages. See also the * ignoreMissingProperties method.
xml.catalog.filescatalogsThe semicolon-delimited list of catalog files.
 relative-catalogsIf false, relative catalog URIs are made absolute with respect to the base URI of * the CatalogManager.properties file. This setting only applies to catalog * URIs obtained from the catalogs property in the * CatalogManager.properties file
xml.catalog.verbosityverbosityIf non-zero, the Catalog classes will print informative and debugging messages. * The higher the number, the more messages.
xml.catalog.preferpreferWhich identifier is preferred, "public" or "system"?
xml.catalog.staticCatalogstatic-catalogShould a single catalog be constructed for all parsing, or should a different * catalog be created for each parser?
xml.catalog.allowPIallow-oasis-xml-catalog-piIf the source document contains "oasis-xml-catalog" processing instructions, * should they be used?
xml.catalog.classNamecatalog-class-nameIf you're using the convenience classes * org.apache.xml.resolver.tools.*), this setting * allows you to specify an alternate class name to use for the underlying * catalog.
* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class CatalogManager { private static String pFiles = "xml.catalog.files"; private static String pVerbosity = "xml.catalog.verbosity"; private static String pPrefer = "xml.catalog.prefer"; private static String pStatic = "xml.catalog.staticCatalog"; private static String pAllowPI = "xml.catalog.allowPI"; private static String pClassname = "xml.catalog.className"; private static String pIgnoreMissing = "xml.catalog.ignoreMissing"; /** A static CatalogManager instance for sharing */ private static CatalogManager staticManager = new CatalogManager(); /** The bootstrap resolver to use when loading XML Catalogs. */ private BootstrapResolver bResolver = new BootstrapResolver(); /** Flag to ignore missing property files and/or properties */ private boolean ignoreMissingProperties = (System.getProperty(pIgnoreMissing) != null || System.getProperty(pFiles) != null); /** Holds the resources after they are loaded from the file. */ private ResourceBundle resources; /** The name of the CatalogManager properties file. */ private String propertyFile = "CatalogManager.properties"; /** The location of the propertyFile */ private URL propertyFileURI = null; /** Default catalog files list. */ private String defaultCatalogFiles = "./xcatalog"; /** Current catalog files list. */ private String catalogFiles = null; /** Did the catalgoFiles come from the properties file? */ private boolean fromPropertiesFile = false; /** Default verbosity level if there is no property setting for it. */ private int defaultVerbosity = 1; /** Current verbosity level. */ private Integer verbosity = null; /** Default preference setting. */ private boolean defaultPreferPublic = true; /** Current preference setting. */ private Boolean preferPublic = null; /** Default setting of the static catalog flag. */ private boolean defaultUseStaticCatalog = true; /** Current setting of the static catalog flag. */ private Boolean useStaticCatalog = null; /** The static catalog used by this manager. */ private static Catalog staticCatalog = null; /** Default setting of the oasisXMLCatalogPI flag. */ private boolean defaultOasisXMLCatalogPI = true; /** Current setting of the oasisXMLCatalogPI flag. */ private Boolean oasisXMLCatalogPI = null; /** Default setting of the relativeCatalogs flag. */ private boolean defaultRelativeCatalogs = true; /** Current setting of the relativeCatalogs flag. */ private Boolean relativeCatalogs = null; /** Current catalog class name. */ private String catalogClassName = null; /** The manager's debug object. Used for printing debugging messages. * *

This field is public so that objects that have access to this * CatalogManager can use this debug object.

*/ public Debug debug = null; /** Constructor. */ public CatalogManager() { debug = new Debug(); // Note that we don't setDebug() here; we do that lazily. Either the // user will set it explicitly, or we'll do it automagically if they // read from the propertyFile for some other reason. That way, there's // no attempt to read from the file before the caller has had a chance // to avoid it. } /** Constructor that specifies an explicit property file. * @param propertyFile */ public CatalogManager(String propertyFile) { this.propertyFile = propertyFile; debug = new Debug(); // Note that we don't setDebug() here; we do that lazily. Either the // user will set it explicitly, or we'll do it automagically if they // read from the propertyFile for some other reason. That way, there's // no attempt to read from the file before the caller has had a chance // to avoid it. } /** Set the bootstrap resolver. * @param resolver */ public void setBootstrapResolver(BootstrapResolver resolver) { bResolver = resolver; } /** @return the bootstrap resolver.*/ public BootstrapResolver getBootstrapResolver() { return bResolver; } /** * Load the properties from the propertyFile and build the * resources from it. */ private synchronized void readProperties() { try { propertyFileURI = CatalogManager.class.getResource("/"+propertyFile); InputStream in = CatalogManager.class.getResourceAsStream("/"+propertyFile); if (in==null) { if (!ignoreMissingProperties) { System.err.println("Cannot find "+propertyFile); // there's no reason to give this warning more than once ignoreMissingProperties = true; } return; } resources = new PropertyResourceBundle(in); } catch (MissingResourceException mre) { if (!ignoreMissingProperties) { System.err.println("Cannot read "+propertyFile); } } catch (java.io.IOException e) { if (!ignoreMissingProperties) { System.err.println("Failure trying to read "+propertyFile); } } // This is a bit of a hack. After we've successfully read the properties, // use them to set the default debug level, if the user hasn't already set // the default debug level. if (verbosity == null) { try { String verbStr = resources.getString("verbosity"); int verb = Integer.parseInt(verbStr.trim()); debug.setDebug(verb); verbosity = new Integer(verb); } catch (Exception e) { // nop } } } /** * Allow access to the static CatalogManager * @return the catalog manager */ public static CatalogManager getStaticManager() { return staticManager; } /** * How are missing properties handled? * *

If true, missing or unreadable property files will * not be reported. Otherwise, a message will be sent to System.err. *

* @return the value */ public boolean getIgnoreMissingProperties() { return ignoreMissingProperties; } /** * How should missing properties be handled? * *

If ignore is true, missing or unreadable property files will * not be reported. Otherwise, a message will be sent to System.err. *

* @param ignore */ public void setIgnoreMissingProperties(boolean ignore) { ignoreMissingProperties = ignore; } /** * How are missing properties handled? * *

If ignore is true, missing or unreadable property files will * not be reported. Otherwise, a message will be sent to System.err. *

* @param ignore * * @deprecated No longer static; use get/set methods. */ public void ignoreMissingProperties(boolean ignore) { setIgnoreMissingProperties(ignore); } /** * Obtain the verbosity setting from the properties. * * @return The verbosity level from the propertyFile or the * defaultVerbosity. */ private int queryVerbosity () { String verbStr = System.getProperty(pVerbosity); if (verbStr == null) { if (resources==null) readProperties(); if (resources==null) return defaultVerbosity; try { verbStr = resources.getString("verbosity"); } catch (MissingResourceException e) { return defaultVerbosity; } } try { int verb = Integer.parseInt(verbStr.trim()); return verb; } catch (Exception e) { System.err.println("Cannot parse verbosity: \"" + verbStr + "\""); return defaultVerbosity; } } /** * @return the current verbosity? */ public int getVerbosity() { if (verbosity == null) { verbosity = new Integer(queryVerbosity()); } return verbosity.intValue(); } /** * Set the current verbosity. * @param verbosity */ public void setVerbosity (int verbosity) { this.verbosity = new Integer(verbosity); debug.setDebug(verbosity); } /** * @return the current verbosity? * * @deprecated No longer static; use get/set methods. */ public int verbosity () { return getVerbosity(); } /** * Obtain the relativeCatalogs setting from the properties. * * @return The relativeCatalogs setting from the propertyFile or the * defaultRelativeCatalogs. */ private boolean queryRelativeCatalogs () { if (resources==null) readProperties(); if (resources==null) return defaultRelativeCatalogs; try { String allow = resources.getString("relative-catalogs"); return (allow.equalsIgnoreCase("true") || allow.equalsIgnoreCase("yes") || allow.equalsIgnoreCase("1")); } catch (MissingResourceException e) { return defaultRelativeCatalogs; } } /** * Get the relativeCatalogs setting. * *

This property is used when the catalogFiles property is * interrogated. If true, then relative catalog entry file names * are returned. If false, relative catalog entry file names are * made absolute with respect to the properties file before returning * them.

* *

This property only applies when the catalog files * come from a properties file. If they come from a system property or * the default list, they are never considered relative. (What would * they be relative to?)

* *

In the properties, a value of 'yes', 'true', or '1' is considered * true, anything else is false.

* * @return The relativeCatalogs setting from the propertyFile or the * defaultRelativeCatalogs. */ public boolean getRelativeCatalogs () { if (relativeCatalogs == null) { relativeCatalogs = new Boolean(queryRelativeCatalogs()); } return relativeCatalogs.booleanValue(); } /** * Set the relativeCatalogs setting. * @param relative * * @see #getRelativeCatalogs() */ public void setRelativeCatalogs (boolean relative) { relativeCatalogs = new Boolean(relative); } /** * @return the relativeCatalogs setting. * * @deprecated No longer static; use get/set methods. */ public boolean relativeCatalogs () { return getRelativeCatalogs(); } /** * Obtain the list of catalog files from the properties. * * @return A semicolon delimited list of catlog file URIs */ private String queryCatalogFiles () { String catalogList = System.getProperty(pFiles); fromPropertiesFile = false; if (catalogList == null) { if (resources == null) readProperties(); if (resources != null) { try { catalogList = resources.getString("catalogs"); fromPropertiesFile = true; } catch (MissingResourceException e) { System.err.println(propertyFile + ": catalogs not found."); catalogList = null; } } } if (catalogList == null) { catalogList = defaultCatalogFiles; } return catalogList; } /** * Return the current list of catalog files. * * @return A vector of the catalog file names or null if no catalogs * are available in the properties. */ public Vector getCatalogFiles() { if (catalogFiles == null) { catalogFiles = queryCatalogFiles(); } StringTokenizer files = new StringTokenizer(catalogFiles, ";"); Vector catalogs = new Vector(); while (files.hasMoreTokens()) { String catalogFile = files.nextToken(); URL absURI = null; if (fromPropertiesFile && !relativeCatalogs()) { try { absURI = new URL(propertyFileURI, catalogFile); catalogFile = absURI.toString(); } catch (MalformedURLException mue) { absURI = null; } } catalogs.add(catalogFile); } return catalogs; } /** * Set the list of catalog files. * @param fileList */ public void setCatalogFiles(String fileList) { catalogFiles = fileList; fromPropertiesFile = false; } /** * Return the current list of catalog files. * * @return A vector of the catalog file names or null if no catalogs * are available in the properties. * * @deprecated No longer static; use get/set methods. */ public Vector catalogFiles() { return getCatalogFiles(); } /** * Obtain the preferPublic setting from the properties. * *

In the properties, a value of 'public' is true, * anything else is false.

* * @return True if prefer is public or the * defaultPreferSetting. */ private boolean queryPreferPublic () { String prefer = System.getProperty(pPrefer); if (prefer == null) { if (resources==null) readProperties(); if (resources==null) return defaultPreferPublic; try { prefer = resources.getString("prefer"); } catch (MissingResourceException e) { return defaultPreferPublic; } } if (prefer == null) { return defaultPreferPublic; } return (prefer.equalsIgnoreCase("public")); } /** * Return the current prefer public setting. * * @return True if public identifiers are preferred. */ public boolean getPreferPublic () { if (preferPublic == null) { preferPublic = new Boolean(queryPreferPublic()); } return preferPublic.booleanValue(); } /** * Set the prefer public setting. * @param preferPublic */ public void setPreferPublic (boolean preferPublic) { this.preferPublic = new Boolean(preferPublic); } /** * Return the current prefer public setting. * * @return True if public identifiers are preferred. * * @deprecated No longer static; use get/set methods. */ public boolean preferPublic () { return getPreferPublic(); } /** * Obtain the static-catalog setting from the properties. * *

In the properties, a value of 'yes', 'true', or '1' is considered * true, anything else is false.

* * @return The static-catalog setting from the propertyFile or the * defaultUseStaticCatalog. */ private boolean queryUseStaticCatalog () { String staticCatalog = System.getProperty(pStatic); if (useStaticCatalog == null) { if (resources==null) readProperties(); if (resources==null) return defaultUseStaticCatalog; try { staticCatalog = resources.getString("static-catalog"); } catch (MissingResourceException e) { return defaultUseStaticCatalog; } } if (staticCatalog == null) { return defaultUseStaticCatalog; } return (staticCatalog.equalsIgnoreCase("true") || staticCatalog.equalsIgnoreCase("yes") || staticCatalog.equalsIgnoreCase("1")); } /** * @return the current use static catalog setting. */ public boolean getUseStaticCatalog() { if (useStaticCatalog == null) { useStaticCatalog = new Boolean(queryUseStaticCatalog()); } return useStaticCatalog.booleanValue(); } /** * Set the use static catalog setting. * @param useStatic */ public void setUseStaticCatalog(boolean useStatic) { useStaticCatalog = new Boolean(useStatic); } /** * @return the current use static catalog setting. * * @deprecated No longer static; use get/set methods. */ public boolean staticCatalog() { return getUseStaticCatalog(); } /** * @return a new catalog instance. * * This method always returns a new instance of the underlying catalog class. */ public Catalog getPrivateCatalog() { Catalog catalog = staticCatalog; if (useStaticCatalog == null) { useStaticCatalog = new Boolean(getUseStaticCatalog()); } if (catalog == null || !useStaticCatalog.booleanValue()) { try { String catalogClassName = getCatalogClassName(); if (catalogClassName == null) { catalog = new Catalog(); } else { try { catalog = (Catalog) Class.forName(catalogClassName).newInstance(); } catch (ClassNotFoundException cnfe) { debug.message(1,"Catalog class named '" + catalogClassName + "' could not be found. Using default."); catalog = new Catalog(); } catch (ClassCastException cnfe) { debug.message(1,"Class named '" + catalogClassName + "' is not a Catalog. Using default."); catalog = new Catalog(); } } catalog.setCatalogManager(this); catalog.setupReaders(); catalog.loadSystemCatalogs(); } catch (Exception ex) { ex.printStackTrace(); } if (useStaticCatalog.booleanValue()) { staticCatalog = catalog; } } return catalog; } /** * @return a catalog instance. * * If this manager uses static catalogs, the same static catalog will * always be returned. Otherwise a new catalog will be returned. */ public Catalog getCatalog() { Catalog catalog = staticCatalog; if (useStaticCatalog == null) { useStaticCatalog = new Boolean(getUseStaticCatalog()); } if (catalog == null || !useStaticCatalog.booleanValue()) { catalog = getPrivateCatalog(); if (useStaticCatalog.booleanValue()) { staticCatalog = catalog; } } return catalog; } /** *

Obtain the oasisXMLCatalogPI setting from the properties.

* *

In the properties, a value of 'yes', 'true', or '1' is considered * true, anything else is false.

* * @return The oasisXMLCatalogPI setting from the propertyFile or the * defaultOasisXMLCatalogPI. */ public boolean queryAllowOasisXMLCatalogPI () { String allow = System.getProperty(pAllowPI); if (allow == null) { if (resources==null) readProperties(); if (resources==null) return defaultOasisXMLCatalogPI; try { allow = resources.getString("allow-oasis-xml-catalog-pi"); } catch (MissingResourceException e) { return defaultOasisXMLCatalogPI; } } if (allow == null) { return defaultOasisXMLCatalogPI; } return (allow.equalsIgnoreCase("true") || allow.equalsIgnoreCase("yes") || allow.equalsIgnoreCase("1")); } /** * @return the current XML Catalog PI setting. */ public boolean getAllowOasisXMLCatalogPI () { if (oasisXMLCatalogPI == null) { oasisXMLCatalogPI = new Boolean(queryAllowOasisXMLCatalogPI()); } return oasisXMLCatalogPI.booleanValue(); } /** * Set the XML Catalog PI setting * @param allowPI */ public void setAllowOasisXMLCatalogPI(boolean allowPI) { oasisXMLCatalogPI = new Boolean(allowPI); } /** * @return the current XML Catalog PI setting. * * @deprecated No longer static; use get/set methods. */ public boolean allowOasisXMLCatalogPI() { return getAllowOasisXMLCatalogPI(); } /** * Obtain the Catalog class name setting from the properties. * @return the name * */ public String queryCatalogClassName () { String className = System.getProperty(pClassname); if (className == null) { if (resources==null) readProperties(); if (resources==null) return null; try { return resources.getString("catalog-class-name"); } catch (MissingResourceException e) { return null; } } return className; } /** * @return the current Catalog class name. */ public String getCatalogClassName() { if (catalogClassName == null) { catalogClassName = queryCatalogClassName(); } return catalogClassName; } /** * Set the Catalog class name. * @param className */ public void setCatalogClassName(String className) { catalogClassName = className; } /** * @return the current Catalog class name. * * @deprecated No longer static; use get/set methods. */ public String catalogClassName() { return getCatalogClassName(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Version.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Version.j0000644000175000017500000000732110470642610033165 0ustar twernertwerner/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; /** * * Administrative class to keep track of the version number of * xml-commons external sources releases. * See xml-commons/java/resolver.xml for filtering on 1.0, etc. */ public class Version { /** * Get the version string for xml-commons-resolver. * Version String formatted like: * "XmlResolver v.r". * * @return String denoting our current version */ public static String getVersion() { return getProduct()+" "+getVersionNum(); } /** * Get just the product name. * * @return String denoting our product name */ public static String getProduct() { return "XmlResolver"; } /** * Get just the version number v.r. * @return String denoting our current version number */ public static String getVersionNum() { return "1.1"; } /** * Print the release version to the command line. * @param argv command line arguments, unused. */ public static void main(String argv[]) { System.out.println(getVersion()); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Catalog.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/Catalog.j0000644000175000017500000021301610774222622033116 0ustar twernertwerner// Catalog.java - Represents OASIS Open Catalog files. /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; import java.io.DataInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.xml.parsers.SAXParserFactory; import org.jboss.util.xml.catalog.helpers.PublicId; import org.jboss.util.xml.catalog.readers.CatalogReader; import org.jboss.util.xml.catalog.readers.OASISXMLCatalogReader; import org.jboss.util.xml.catalog.readers.SAXCatalogReader; import org.jboss.util.xml.catalog.readers.TR9401CatalogReader; /** * Represents OASIS Open Catalog files. * *

This class implements the semantics of OASIS Open Catalog files * (defined by * OASIS Technical * Resolution 9401:1997 (Amendment 2 to TR 9401)).

* *

The primary purpose of the Catalog is to associate resources in the * document with local system identifiers. Some entities * (document types, XML entities, and notations) have names and all of them * can have either public or system identifiers or both. (In XML, only a * notation can have a public identifier without a system identifier, but * the methods implemented in this class obey the Catalog semantics * from the SGML * days when system identifiers were optional.)

* *

The system identifiers returned by the resolution methods in this * class are valid, i.e. usable by, and in fact constructed by, the * java.net.URL class. Unfortunately, this class seems to behave in * somewhat non-standard ways and the system identifiers returned may * not be directly usable in a browser or filesystem context. * *

This class recognizes all of the Catalog entries defined in * TR9401:1997:

* *
    *
  • BASE * changes the base URI for resolving relative system identifiers. The * initial base URI is the URI of the location of the catalog (which is, * in turn, relative to the location of the current working directory * at startup, as returned by the user.dir system property).
  • *
  • CATALOG * processes other catalog files. An included catalog occurs logically * at the end of the including catalog.
  • *
  • DELEGATE_PUBLIC * specifies alternate catalogs for some public identifiers. The delegated * catalogs are not loaded until they are needed, but they are cached * once loaded.
  • *
  • DELEGATE_SYSTEM * specifies alternate catalogs for some system identifiers. The delegated * catalogs are not loaded until they are needed, but they are cached * once loaded.
  • *
  • DELEGATE_URI * specifies alternate catalogs for some URIs. The delegated * catalogs are not loaded until they are needed, but they are cached * once loaded.
  • *
  • REWRITE_SYSTEM * specifies alternate prefix for a system identifier.
  • *
  • REWRITE_URI * specifies alternate prefix for a URI.
  • *
  • DOCTYPE * associates the names of root elements with URIs. (In other words, an XML * processor might infer the doctype of an XML document that does not include * a doctype declaration by looking for the DOCTYPE entry in the * catalog which matches the name of the root element of the document.)
  • *
  • DOCUMENT * provides a default document.
  • *
  • DTDDECL * recognized and silently ignored. Not relevant for XML.
  • *
  • ENTITY * associates entity names with URIs.
  • *
  • LINKTYPE * recognized and silently ignored. Not relevant for XML.
  • *
  • NOTATION * associates notation names with URIs.
  • *
  • OVERRIDE * changes the override behavior. Initial behavior is set by the * system property xml.catalog.override. The default initial * behavior is 'YES', that is, entries in the catalog override * system identifiers specified in the document.
  • *
  • PUBLIC * maps a public identifier to a system identifier.
  • *
  • SGMLDECL * recognized and silently ignored. Not relevant for XML.
  • *
  • SYSTEM * maps a system identifier to another system identifier.
  • *
  • URI * maps a URI to another URI.
  • *
* *

Note that BASE entries are treated as described by RFC2396. In * particular, this has the counter-intuitive property that after a BASE * entry identifing "http://example.com/a/b/c" as the base URI, * the relative URI "foo" is resolved to the absolute URI * "http://example.com/a/b/foo". You must provide the trailing slash if * you do not want the final component of the path to be discarded as a * filename would in a URI for a resource: "http://example.com/a/b/c/". *

* *

Note that subordinate catalogs (all catalogs except the first, * including CATALOG and DELEGATE* catalogs) are only loaded if and when * they are required.

* *

This class relies on classes which implement the CatalogReader * interface to actually load catalog files. This allows the catalog * semantics to be implemented for TR9401 text-based catalogs, XML * catalogs, or any number of other storage formats.

* *

Additional catalogs may also be loaded with the * {@link #parseCatalog(String)} method.

* * * *

Change Log:

*
*
2.0
*

Rewrite to use CatalogReaders.

*
1.1
*

Allow quoted components in xml.catalog.files * so that URLs containing colons can be used on Unix. * The string passed to xml.catalog.files can now have the form:

*
 * unquoted-path-with-no-sep-chars:"double-quoted path with or without sep chars":'single-quoted path with or without sep chars'
 * 
*

(Where ":" is the separater character in this example.)

*

If an unquoted path contains an embedded double or single quote * character, no special processig is performed on that character. No * path can contain separater characters, double, and single quotes * simultaneously.

*

Fix bug in calculation of BASE entries: if * a catalog contains multiple BASE entries, each is relative to the preceding * base, not the default base URI of the catalog.

*
*
1.0.1
*

Fixed a bug in the calculation of the list of subordinate catalogs. * This bug caused an infinite loop where parsing would alternately process * two catalogs indefinitely.

*
*
* * @see CatalogReader * @see CatalogEntry * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 * *

Derived from public domain code originally published by Arbortext, * Inc.

*/ @SuppressWarnings("unchecked") public class Catalog { /** The BASE Catalog Entry type. */ public static final int BASE = CatalogEntry.addEntryType("BASE", 1); /** The CATALOG Catalog Entry type. */ public static final int CATALOG = CatalogEntry.addEntryType("CATALOG", 1); /** The DOCUMENT Catalog Entry type. */ public static final int DOCUMENT = CatalogEntry.addEntryType("DOCUMENT", 1); /** The OVERRIDE Catalog Entry type. */ public static final int OVERRIDE = CatalogEntry.addEntryType("OVERRIDE", 1); /** The SGMLDECL Catalog Entry type. */ public static final int SGMLDECL = CatalogEntry.addEntryType("SGMLDECL", 1); /** The DELEGATE_PUBLIC Catalog Entry type. */ public static final int DELEGATE_PUBLIC = CatalogEntry.addEntryType("DELEGATE_PUBLIC", 2); /** The DELEGATE_SYSTEM Catalog Entry type. */ public static final int DELEGATE_SYSTEM = CatalogEntry.addEntryType("DELEGATE_SYSTEM", 2); /** The DELEGATE_URI Catalog Entry type. */ public static final int DELEGATE_URI = CatalogEntry.addEntryType("DELEGATE_URI", 2); /** The DOCTYPE Catalog Entry type. */ public static final int DOCTYPE = CatalogEntry.addEntryType("DOCTYPE", 2); /** The DTDDECL Catalog Entry type. */ public static final int DTDDECL = CatalogEntry.addEntryType("DTDDECL", 2); /** The ENTITY Catalog Entry type. */ public static final int ENTITY = CatalogEntry.addEntryType("ENTITY", 2); /** The LINKTYPE Catalog Entry type. */ public static final int LINKTYPE = CatalogEntry.addEntryType("LINKTYPE", 2); /** The NOTATION Catalog Entry type. */ public static final int NOTATION = CatalogEntry.addEntryType("NOTATION", 2); /** The PUBLIC Catalog Entry type. */ public static final int PUBLIC = CatalogEntry.addEntryType("PUBLIC", 2); /** The SYSTEM Catalog Entry type. */ public static final int SYSTEM = CatalogEntry.addEntryType("SYSTEM", 2); /** The URI Catalog Entry type. */ public static final int URI = CatalogEntry.addEntryType("URI", 2); /** The REWRITE_SYSTEM Catalog Entry type. */ public static final int REWRITE_SYSTEM = CatalogEntry.addEntryType("REWRITE_SYSTEM", 2); /** The REWRITE_URI Catalog Entry type. */ public static final int REWRITE_URI = CatalogEntry.addEntryType("REWRITE_URI", 2); /** * The base URI for relative system identifiers in the catalog. * This may be changed by BASE entries in the catalog. */ protected URL base; /** The base URI of the Catalog file currently being parsed. */ protected URL catalogCwd; /** The catalog entries currently known to the system. */ protected Vector catalogEntries = new Vector(); /** The default initial override setting. */ protected boolean default_override = true; /** The catalog manager in use for this instance. */ protected CatalogManager catalogManager = CatalogManager.getStaticManager(); /** * A vector of catalog files to be loaded. * *

This list is initially established by * loadSystemCatalogs when * it parses the system catalog list, but CATALOG entries may * contribute to it during the course of parsing.

* * @see #loadSystemCatalogs * @see #localCatalogFiles */ protected Vector catalogFiles = new Vector(); /** * A vector of catalog files constructed during processing of * CATALOG entries in the current catalog. * *

This two-level system is actually necessary to correctly implement * the semantics of the CATALOG entry. If one catalog file includes * another with a CATALOG entry, the included catalog logically * occurs at the end of the including catalog, and after any * preceding CATALOG entries. In other words, the CATALOG entry * cannot insert anything into the middle of a catalog file.

* *

When processing reaches the end of each catalog files, any * elements on this vector are added to the front of the * catalogFiles vector.

* * @see #catalogFiles */ protected Vector localCatalogFiles = new Vector(); /** * A vector of Catalogs. * *

The semantics of Catalog resolution are such that each * catalog is effectively a list of Catalogs (in other words, * a recursive list of Catalog instances).

* *

Catalogs that are processed as the result of CATALOG or * DELEGATE* entries are subordinate to the catalog that contained * them, but they may in turn have subordinate catalogs.

* *

Catalogs are only loaded when they are needed, so this vector * initially contains a list of Catalog filenames (URLs). If, during * processing, one of these catalogs has to be loaded, the resulting * Catalog object is placed in the vector, effectively caching it * for the next query.

*/ protected Vector catalogs = new Vector(); /** * A vector of DELEGATE* Catalog entries constructed during * processing of the Catalog. * *

This two-level system has two purposes; first, it allows * us to sort the DELEGATE* entries by the length of the partial * public identifier so that a linear search encounters them in * the correct order and second, it puts them all at the end of * the Catalog.

* *

When processing reaches the end of each catalog file, any * elements on this vector are added to the end of the * catalogEntries vector. This assures that matching * PUBLIC keywords are encountered before DELEGATE* entries.

*/ protected Vector localDelegate = new Vector(); /** * A hash of CatalogReaders. * *

This hash maps MIME types to elements in the readerArr * vector. This allows the Catalog to quickly locate the reader * for a particular MIME type.

*/ protected Hashtable readerMap = new Hashtable(); /** * A vector of CatalogReaders. * *

This vector contains all of the readers in the order that they * were added. In the event that a catalog is read from a file, where * the MIME type is unknown, each reader is attempted in turn until * one succeeds.

*/ protected Vector readerArr = new Vector(); /** * Constructs an empty Catalog. * *

The constructor interrogates the relevant system properties * using the default (static) CatalogManager * and initializes the catalog data structures.

*/ public Catalog() { // nop; } /** * Constructs an empty Catalog with a specific CatalogManager. * *

The constructor interrogates the relevant system properties * using the specified Catalog Manager * and initializes the catalog data structures.

* @param manager */ public Catalog(CatalogManager manager) { catalogManager = manager; } /** * @return the CatalogManager used by this catalog. * */ public CatalogManager getCatalogManager() { return catalogManager; } /** * Establish the CatalogManager used by this catalog. * @param manager * */ public void setCatalogManager(CatalogManager manager) { catalogManager = manager; } /** * Setup readers. */ public void setupReaders() { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); SAXCatalogReader saxReader = new SAXCatalogReader(spf); saxReader.setCatalogParser(null, "XMLCatalog", "org.apache.xml.resolver.readers.XCatalogReader"); saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName, "catalog", "org.apache.xml.resolver.readers.OASISXMLCatalogReader"); addReader("application/xml", saxReader); TR9401CatalogReader textReader = new TR9401CatalogReader(); addReader("text/plain", textReader); } /** * Add a new CatalogReader to the Catalog. * *

This method allows you to add a new CatalogReader to the * catalog. The reader will be associated with the specified mimeType. * You can only have one reader per mimeType.

* *

In the absence of a mimeType (e.g., when reading a catalog * directly from a file on the local system), the readers are attempted * in the order that you add them to the Catalog.

* *

Note that subordinate catalogs (created by CATALOG or * DELEGATE* entries) get a copy of the set of readers present in * the primary catalog when they are created. Readers added subsequently * will not be available. For this reason, it is best to add all * of the readers before the first call to parse a catalog.

* * @param mimeType The MIME type associated with this reader. * @param reader The CatalogReader to use. */ public void addReader(String mimeType, CatalogReader reader) { if (readerMap.containsKey(mimeType)) { Integer pos = (Integer) readerMap.get(mimeType); readerArr.set(pos.intValue(), reader); } else { readerArr.add(reader); Integer pos = new Integer(readerArr.size()-1); readerMap.put(mimeType, pos); } } /** * Copies the reader list from the current Catalog to a new Catalog. * *

This method is used internally when constructing a new catalog. * It copies the current reader associations over to the new catalog. *

* * @param newCatalog The new Catalog. */ protected void copyReaders(Catalog newCatalog) { // Have to copy the readers in the right order...convert hash to arr Vector mapArr = new Vector(readerMap.size()); // Pad the mapArr out to the right length for (int count = 0; count < readerMap.size(); count++) { mapArr.add(null); } Enumeration enumt = readerMap.keys(); while (enumt.hasMoreElements()) { String mimeType = (String) enumt.nextElement(); Integer pos = (Integer) readerMap.get(mimeType); mapArr.set(pos.intValue(), mimeType); } for (int count = 0; count < mapArr.size(); count++) { String mimeType = (String) mapArr.get(count); Integer pos = (Integer) readerMap.get(mimeType); newCatalog.addReader(mimeType, (CatalogReader) readerArr.get(pos.intValue())); } } /** * Create a new Catalog object. * *

This method constructs a new instance of the running Catalog * class (which might be a subtype of org.apache.xml.resolver.Catalog). * All new catalogs are managed by the same CatalogManager. *

* *

N.B. All Catalog subtypes should call newCatalog() to construct * a new Catalog. Do not simply use "new Subclass()" since that will * confuse future subclasses.

* * @return the catalog */ protected Catalog newCatalog() { String catalogClass = this.getClass().getName(); try { Catalog c = (Catalog) (Class.forName(catalogClass).newInstance()); c.setCatalogManager(catalogManager); copyReaders(c); return c; } catch (ClassNotFoundException cnfe) { catalogManager.debug.message(1, "Class Not Found Exception: " + catalogClass); } catch (IllegalAccessException iae) { catalogManager.debug.message(1, "Illegal Access Exception: " + catalogClass); } catch (InstantiationException ie) { catalogManager.debug.message(1, "Instantiation Exception: " + catalogClass); } catch (ClassCastException cce) { catalogManager.debug.message(1, "Class Cast Exception: " + catalogClass); } catch (Exception e) { catalogManager.debug.message(1, "Other Exception: " + catalogClass); } Catalog c = new Catalog(); c.setCatalogManager(catalogManager); copyReaders(c); return c; } /** * @return the current base URI. */ public String getCurrentBase() { return base.toString(); } /** * @return the default override setting associated with this * catalog. * *

All catalog files loaded by this catalog will have the * initial override setting specified by this default.

*/ public String getDefaultOverride() { if (default_override) { return "yes"; } else { return "no"; } } /** * Load the system catalog files. * *

The method adds all of the * catalogs specified in the xml.catalog.files property * to the Catalog list.

* * @throws MalformedURLException One of the system catalogs is * identified with a filename that is not a valid URL. * @throws IOException One of the system catalogs cannot be read. */ public void loadSystemCatalogs() throws MalformedURLException, IOException { Vector catalogs = catalogManager.getCatalogFiles(); if (catalogs != null) { for (int count = 0; count < catalogs.size(); count++) { catalogFiles.addElement(catalogs.elementAt(count)); } } if (catalogFiles.size() > 0) { // This is a little odd. The parseCatalog() method expects // a filename, but it adds that name to the end of the // catalogFiles vector, and then processes that vector. // This allows the system to handle CATALOG entries // correctly. // // In this init case, we take the last element off the // catalogFiles vector and pass it to parseCatalog. This // will "do the right thing" in the init case, and allow // parseCatalog() to do the right thing in the non-init // case. Honest. // String catfile = (String) catalogFiles.lastElement(); catalogFiles.removeElement(catfile); parseCatalog(catfile); } } /** * Parse a catalog file, augmenting internal data structures. * * @param fileName The filename of the catalog file to process * * @throws MalformedURLException The fileName cannot be turned into * a valid URL. * @throws IOException Error reading catalog file. */ public synchronized void parseCatalog(String fileName) throws MalformedURLException, IOException { default_override = catalogManager.getPreferPublic(); catalogManager.debug.message(4, "Parse catalog: " + fileName); // Put the file into the list of catalogs to process... // In all cases except the case when initCatalog() is the // caller, this will be the only catalog initially in the list... catalogFiles.addElement(fileName); // Now process all the pending catalogs... parsePendingCatalogs(); } /** * Parse a catalog file, augmenting internal data structures. * *

Catalogs retrieved over the net may have an associated MIME type. * The MIME type can be used to select an appropriate reader.

* * @param mimeType The MIME type of the catalog file. * @param is The InputStream from which the catalog should be read * * @throws CatalogException Failed to load catalog * mimeType. * @throws IOException Error reading catalog file. */ public synchronized void parseCatalog(String mimeType, InputStream is) throws IOException, CatalogException { default_override = catalogManager.getPreferPublic(); catalogManager.debug.message(4, "Parse " + mimeType + " catalog on input stream"); CatalogReader reader = null; if (readerMap.containsKey(mimeType)) { int arrayPos = ((Integer) readerMap.get(mimeType)).intValue(); reader = (CatalogReader) readerArr.get(arrayPos); } if (reader == null) { String msg = "No CatalogReader for MIME type: " + mimeType; catalogManager.debug.message(2, msg); throw new CatalogException(CatalogException.UNPARSEABLE, msg); } reader.readCatalog(this, is); // Now process all the pending catalogs... parsePendingCatalogs(); } /** * Parse a catalog document, augmenting internal data structures. * *

This method supports catalog files stored in jar files: e.g., * jar:file:///path/to/filename.jar!/path/to/catalog.xml". That URI * doesn't survive transmogrification through the URI processing that * the parseCatalog(String) performs and passing it as an input stream * doesn't set the base URI appropriately.

* *

Written by Stefan Wachter (2002-09-26)

* * @param aUrl The URL of the catalog document to process * * @throws IOException Error reading catalog file. */ public synchronized void parseCatalog(URL aUrl) throws IOException { catalogCwd = aUrl; base = aUrl; default_override = catalogManager.getPreferPublic(); catalogManager.debug.message(4, "Parse catalog: " + aUrl.toString()); DataInputStream inStream = null; boolean parsed = false; for (int count = 0; !parsed && count < readerArr.size(); count++) { CatalogReader reader = (CatalogReader) readerArr.get(count); try { inStream = new DataInputStream(aUrl.openStream()); } catch (FileNotFoundException fnfe) { // No catalog; give up! break; } try { reader.readCatalog(this, inStream); parsed=true; } catch (CatalogException ce) { if (ce.getExceptionType() == CatalogException.PARSE_FAILED) { // give up! break; } else { // try again! } } try { inStream.close(); } catch (IOException e) { //nop } } if (parsed) parsePendingCatalogs(); } /** * Parse all of the pending catalogs. * *

Catalogs may refer to other catalogs, this method parses * all of the currently pending catalog files.

* @throws MalformedURLException * @throws IOException */ protected synchronized void parsePendingCatalogs() throws MalformedURLException, IOException { if (!localCatalogFiles.isEmpty()) { // Move all the localCatalogFiles into the front of // the catalogFiles queue Vector newQueue = new Vector(); Enumeration q = localCatalogFiles.elements(); while (q.hasMoreElements()) { newQueue.addElement(q.nextElement()); } // Put the rest of the catalogs on the end of the new list for (int curCat = 0; curCat < catalogFiles.size(); curCat++) { String catfile = (String) catalogFiles.elementAt(curCat); newQueue.addElement(catfile); } catalogFiles = newQueue; localCatalogFiles.clear(); } // Suppose there are no catalog files to process, but the // single catalog already parsed included some delegate // entries? Make sure they don't get lost. if (catalogFiles.isEmpty() && !localDelegate.isEmpty()) { Enumeration e = localDelegate.elements(); while (e.hasMoreElements()) { catalogEntries.addElement(e.nextElement()); } localDelegate.clear(); } // Now process all the files on the catalogFiles vector. This // vector can grow during processing if CATALOG entries are // encountered in the catalog while (!catalogFiles.isEmpty()) { String catfile = (String) catalogFiles.elementAt(0); try { catalogFiles.remove(0); } catch (ArrayIndexOutOfBoundsException e) { // can't happen } if (catalogEntries.size() == 0 && catalogs.size() == 0) { // We haven't parsed any catalogs yet, let this // catalog be the first... try { parseCatalogFile(catfile); } catch (CatalogException ce) { System.out.println("FIXME: " + ce.toString()); } } else { // This is a subordinate catalog. We save its name, // but don't bother to load it unless it's necessary. catalogs.addElement(catfile); } if (!localCatalogFiles.isEmpty()) { // Move all the localCatalogFiles into the front of // the catalogFiles queue Vector newQueue = new Vector(); Enumeration q = localCatalogFiles.elements(); while (q.hasMoreElements()) { newQueue.addElement(q.nextElement()); } // Put the rest of the catalogs on the end of the new list for (int curCat = 0; curCat < catalogFiles.size(); curCat++) { catfile = (String) catalogFiles.elementAt(curCat); newQueue.addElement(catfile); } catalogFiles = newQueue; localCatalogFiles.clear(); } if (!localDelegate.isEmpty()) { Enumeration e = localDelegate.elements(); while (e.hasMoreElements()) { catalogEntries.addElement(e.nextElement()); } localDelegate.clear(); } } // We've parsed them all, reinit the vector... catalogFiles.clear(); } /** * Parse a single catalog file, augmenting internal data structures. * * @param fileName The filename of the catalog file to process * * @throws MalformedURLException The fileName cannot be turned into * a valid URL. * @throws IOException Error reading catalog file. * @throws CatalogException for any error */ protected synchronized void parseCatalogFile(String fileName) throws MalformedURLException, IOException, CatalogException { // The base-base is the cwd. If the catalog file is specified // with a relative path, this assures that it gets resolved // properly... try { // tack on a basename because URLs point to files not dirs String userdir = fixSlashes(System.getProperty("user.dir")); catalogCwd = new URL("file:" + userdir + "/basename"); } catch (MalformedURLException e) { String userdir = fixSlashes(System.getProperty("user.dir")); catalogManager.debug.message(1, "Malformed URL on cwd", userdir); catalogCwd = null; } // The initial base URI is the location of the catalog file try { base = new URL(catalogCwd, fixSlashes(fileName)); } catch (MalformedURLException e) { try { base = new URL("file:" + fixSlashes(fileName)); } catch (MalformedURLException e2) { catalogManager.debug.message(1, "Malformed URL on catalog filename", fixSlashes(fileName)); base = null; } } catalogManager.debug.message(2, "Loading catalog", fileName); catalogManager.debug.message(4, "Default BASE", base.toString()); fileName = base.toString(); DataInputStream inStream = null; boolean parsed = false; boolean notFound = false; for (int count = 0; !parsed && count < readerArr.size(); count++) { CatalogReader reader = (CatalogReader) readerArr.get(count); try { notFound = false; inStream = new DataInputStream(base.openStream()); } catch (FileNotFoundException fnfe) { // No catalog; give up! notFound = true; break; } try { reader.readCatalog(this, inStream); parsed = true; } catch (CatalogException ce) { if (ce.getExceptionType() == CatalogException.PARSE_FAILED) { // give up! break; } else { // try again! } } try { inStream.close(); } catch (IOException e) { //nop } } if (!parsed) { if (notFound) { catalogManager.debug.message(3, "Catalog does not exist", fileName); } else { catalogManager.debug.message(1, "Failed to parse catalog", fileName); } } } /** * Cleanup and process a Catalog entry. * *

This method processes each Catalog entry, changing mapped * relative system identifiers into absolute ones (based on the current * base URI), and maintaining other information about the current * catalog.

* * @param entry The CatalogEntry to process. */ public void addEntry(CatalogEntry entry) { int type = entry.getEntryType(); if (type == BASE) { String value = entry.getEntryArg(0); URL newbase = null; catalogManager.debug.message(5, "BASE CUR", base.toString()); catalogManager.debug.message(4, "BASE STR", value); try { value = fixSlashes(value); newbase = new URL(base, value); } catch (MalformedURLException e) { try { newbase = new URL("file:" + value); } catch (MalformedURLException e2) { catalogManager.debug.message(1, "Malformed URL on base", value); newbase = null; } } if (newbase != null) { base = newbase; } catalogManager.debug.message(5, "BASE NEW", base.toString()); } else if (type == CATALOG) { String fsi = makeAbsolute(entry.getEntryArg(0)); catalogManager.debug.message(4, "CATALOG", fsi); localCatalogFiles.addElement(fsi); } else if (type == PUBLIC) { String publicid = PublicId.normalize(entry.getEntryArg(0)); String systemid = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, publicid); entry.setEntryArg(1, systemid); catalogManager.debug.message(4, "PUBLIC", publicid, systemid); catalogEntries.addElement(entry); } else if (type == SYSTEM) { String systemid = normalizeURI(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "SYSTEM", systemid, fsi); catalogEntries.addElement(entry); } else if (type == URI) { String uri = normalizeURI(entry.getEntryArg(0)); String altURI = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, altURI); catalogManager.debug.message(4, "URI", uri, altURI); catalogEntries.addElement(entry); } else if (type == DOCUMENT) { String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(0))); entry.setEntryArg(0, fsi); catalogManager.debug.message(4, "DOCUMENT", fsi); catalogEntries.addElement(entry); } else if (type == OVERRIDE) { catalogManager.debug.message(4, "OVERRIDE", entry.getEntryArg(0)); catalogEntries.addElement(entry); } else if (type == SGMLDECL) { // meaningless in XML String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(0))); entry.setEntryArg(0, fsi); catalogManager.debug.message(4, "SGMLDECL", fsi); catalogEntries.addElement(entry); } else if (type == DELEGATE_PUBLIC) { String ppi = PublicId.normalize(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, ppi); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "DELEGATE_PUBLIC", ppi, fsi); addDelegate(entry); } else if (type == DELEGATE_SYSTEM) { String psi = normalizeURI(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, psi); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "DELEGATE_SYSTEM", psi, fsi); addDelegate(entry); } else if (type == DELEGATE_URI) { String pui = normalizeURI(entry.getEntryArg(0)); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, pui); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "DELEGATE_URI", pui, fsi); addDelegate(entry); } else if (type == REWRITE_SYSTEM) { String psi = normalizeURI(entry.getEntryArg(0)); String rpx = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, psi); entry.setEntryArg(1, rpx); catalogManager.debug.message(4, "REWRITE_SYSTEM", psi, rpx); catalogEntries.addElement(entry); } else if (type == REWRITE_URI) { String pui = normalizeURI(entry.getEntryArg(0)); String upx = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(0, pui); entry.setEntryArg(1, upx); catalogManager.debug.message(4, "REWRITE_URI", pui, upx); catalogEntries.addElement(entry); } else if (type == DOCTYPE) { String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "DOCTYPE", entry.getEntryArg(0), fsi); catalogEntries.addElement(entry); } else if (type == DTDDECL) { // meaningless in XML String fpi = PublicId.normalize(entry.getEntryArg(0)); entry.setEntryArg(0, fpi); String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "DTDDECL", fpi, fsi); catalogEntries.addElement(entry); } else if (type == ENTITY) { String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "ENTITY", entry.getEntryArg(0), fsi); catalogEntries.addElement(entry); } else if (type == LINKTYPE) { // meaningless in XML String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "LINKTYPE", entry.getEntryArg(0), fsi); catalogEntries.addElement(entry); } else if (type == NOTATION) { String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1))); entry.setEntryArg(1, fsi); catalogManager.debug.message(4, "NOTATION", entry.getEntryArg(0), fsi); catalogEntries.addElement(entry); } else { catalogEntries.addElement(entry); } } /** * Handle unknown CatalogEntry types. * *

This method exists to allow subclasses to deal with unknown * entry types.

* @param strings */ public void unknownEntry(Vector strings) { if (strings != null && strings.size() > 0) { String keyword = (String) strings.elementAt(0); catalogManager.debug.message(2, "Unrecognized token parsing catalog", keyword); } } /** * Parse all subordinate catalogs. * *

This method recursively parses all of the subordinate catalogs. * If this method does not throw an exception, you can be confident that * no subsequent call to any resolve*() method will either, with two * possible exceptions:

* *
    *
  1. Delegated catalogs are re-parsed each time they are needed * (because a variable list of them may be needed in each case, * depending on the length of the matching partial public identifier).

    *

    But they are parsed by this method, so as long as they don't * change or disappear while the program is running, they shouldn't * generate errors later if they don't generate errors now.

    *
  2. If you add new catalogs with parseCatalog, they * won't be loaded until they are needed or until you call * parseAllCatalogs again.

    *
* *

On the other hand, if you don't call this method, you may * successfully parse documents without having to load all possible * catalogs.

* * @throws MalformedURLException The filename (URL) for a * subordinate or delegated catalog is not a valid URL. * @throws IOException Error reading some subordinate or delegated * catalog file. */ public void parseAllCatalogs() throws MalformedURLException, IOException { // Parse all the subordinate catalogs for (int catPos = 0; catPos < catalogs.size(); catPos++) { Catalog c = null; try { c = (Catalog) catalogs.elementAt(catPos); } catch (ClassCastException e) { String catfile = (String) catalogs.elementAt(catPos); c = newCatalog(); c.parseCatalog(catfile); catalogs.setElementAt(c, catPos); c.parseAllCatalogs(); } } // Parse all the DELEGATE catalogs Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == DELEGATE_PUBLIC || e.getEntryType() == DELEGATE_SYSTEM || e.getEntryType() == DELEGATE_URI) { Catalog dcat = newCatalog(); dcat.parseCatalog(e.getEntryArg(1)); } } } /** * Return the applicable DOCTYPE system identifier. * * @param entityName The name of the entity (element) for which * a doctype is required. * @param publicId The nominal public identifier for the doctype * (as provided in the source document). * @param systemId The nominal system identifier for the doctype * (as provided in the source document). * * @return The system identifier to use for the doctype. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveDoctype(String entityName, String publicId, String systemId) throws MalformedURLException, IOException { String resolved = null; catalogManager.debug.message(3, "resolveDoctype(" +entityName+","+publicId+","+systemId+")"); systemId = normalizeURI(systemId); if (publicId != null && publicId.startsWith("urn:publicid:")) { publicId = PublicId.decodeURN(publicId); } if (systemId != null && systemId.startsWith("urn:publicid:")) { systemId = PublicId.decodeURN(systemId); if (publicId != null && !publicId.equals(systemId)) { catalogManager.debug.message(1, "urn:publicid: system identifier differs from public identifier; using public identifier"); systemId = null; } else { publicId = systemId; systemId = null; } } if (systemId != null) { // If there's a SYSTEM entry in this catalog, use it resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } if (publicId != null) { // If there's a PUBLIC entry in this catalog, use it resolved = resolveLocalPublic(DOCTYPE, entityName, publicId, systemId); if (resolved != null) { return resolved; } } // If there's a DOCTYPE entry in this catalog, use it boolean over = default_override; Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == OVERRIDE) { over = e.getEntryArg(0).equalsIgnoreCase("YES"); continue; } if (e.getEntryType() == DOCTYPE && e.getEntryArg(0).equals(entityName)) { if (over || systemId == null) { return e.getEntryArg(1); } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(DOCTYPE, entityName, publicId, systemId); } /** * Return the applicable DOCUMENT entry. * * @return The system identifier to use for the doctype. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveDocument() throws MalformedURLException, IOException { // If there's a DOCUMENT entry, return it catalogManager.debug.message(3, "resolveDocument"); Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == DOCUMENT) { return e.getEntryArg(1); //FIXME check this } } return resolveSubordinateCatalogs(DOCUMENT, null, null, null); } /** * Return the applicable ENTITY system identifier. * * @param entityName The name of the entity for which * a system identifier is required. * @param publicId The nominal public identifier for the entity * (as provided in the source document). * @param systemId The nominal system identifier for the entity * (as provided in the source document). * * @return The system identifier to use for the entity. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveEntity(String entityName, String publicId, String systemId) throws MalformedURLException, IOException { String resolved = null; catalogManager.debug.message(3, "resolveEntity(" +entityName+","+publicId+","+systemId+")"); systemId = normalizeURI(systemId); if (publicId != null && publicId.startsWith("urn:publicid:")) { publicId = PublicId.decodeURN(publicId); } if (systemId != null && systemId.startsWith("urn:publicid:")) { systemId = PublicId.decodeURN(systemId); if (publicId != null && !publicId.equals(systemId)) { catalogManager.debug.message(1, "urn:publicid: system identifier differs from public identifier; using public identifier"); systemId = null; } else { publicId = systemId; systemId = null; } } if (systemId != null) { // If there's a SYSTEM entry in this catalog, use it resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } if (publicId != null) { // If there's a PUBLIC entry in this catalog, use it resolved = resolveLocalPublic(ENTITY, entityName, publicId, systemId); if (resolved != null) { return resolved; } } // If there's a ENTITY entry in this catalog, use it boolean over = default_override; Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == OVERRIDE) { over = e.getEntryArg(0).equalsIgnoreCase("YES"); continue; } if (e.getEntryType() == ENTITY && e.getEntryArg(0).equals(entityName)) { if (over || systemId == null) { return e.getEntryArg(1); } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(ENTITY, entityName, publicId, systemId); } /** * Return the applicable NOTATION system identifier. * * @param notationName The name of the notation for which * a doctype is required. * @param publicId The nominal public identifier for the notation * (as provided in the source document). * @param systemId The nominal system identifier for the notation * (as provided in the source document). * * @return The system identifier to use for the notation. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveNotation(String notationName, String publicId, String systemId) throws MalformedURLException, IOException { String resolved = null; catalogManager.debug.message(3, "resolveNotation(" +notationName+","+publicId+","+systemId+")"); systemId = normalizeURI(systemId); if (publicId != null && publicId.startsWith("urn:publicid:")) { publicId = PublicId.decodeURN(publicId); } if (systemId != null && systemId.startsWith("urn:publicid:")) { systemId = PublicId.decodeURN(systemId); if (publicId != null && !publicId.equals(systemId)) { catalogManager.debug.message(1, "urn:publicid: system identifier differs from public identifier; using public identifier"); systemId = null; } else { publicId = systemId; systemId = null; } } if (systemId != null) { // If there's a SYSTEM entry in this catalog, use it resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } if (publicId != null) { // If there's a PUBLIC entry in this catalog, use it resolved = resolveLocalPublic(NOTATION, notationName, publicId, systemId); if (resolved != null) { return resolved; } } // If there's a NOTATION entry in this catalog, use it boolean over = default_override; Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == OVERRIDE) { over = e.getEntryArg(0).equalsIgnoreCase("YES"); continue; } if (e.getEntryType() == NOTATION && e.getEntryArg(0).equals(notationName)) { if (over || systemId == null) { return e.getEntryArg(1); } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(NOTATION, notationName, publicId, systemId); } /** * Return the applicable PUBLIC or SYSTEM identifier. * *

This method searches the Catalog and returns the system * identifier specified for the given system or * public identifiers. If * no appropriate PUBLIC or SYSTEM entry is found in the Catalog, * null is returned.

* * @param publicId The public identifier to locate in the catalog. * Public identifiers are normalized before comparison. * @param systemId The nominal system identifier for the entity * in question (as provided in the source document). * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. * * @return The system identifier to use. * Note that the nominal system identifier is not returned if a * match is not found in the catalog, instead null is returned * to indicate that no match was found. */ public String resolvePublic(String publicId, String systemId) throws MalformedURLException, IOException { catalogManager.debug.message(3, "resolvePublic("+publicId+","+systemId+")"); systemId = normalizeURI(systemId); if (publicId != null && publicId.startsWith("urn:publicid:")) { publicId = PublicId.decodeURN(publicId); } if (systemId != null && systemId.startsWith("urn:publicid:")) { systemId = PublicId.decodeURN(systemId); if (publicId != null && !publicId.equals(systemId)) { catalogManager.debug.message(1, "urn:publicid: system identifier differs from public identifier; using public identifier"); systemId = null; } else { publicId = systemId; systemId = null; } } // If there's a SYSTEM entry in this catalog, use it if (systemId != null) { String resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } // If there's a PUBLIC entry in this catalog, use it String resolved = resolveLocalPublic(PUBLIC, null, publicId, systemId); if (resolved != null) { return resolved; } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(PUBLIC, null, publicId, systemId); } /** * Return the applicable PUBLIC or SYSTEM identifier. * *

This method searches the Catalog and returns the system * identifier specified for the given system or public identifiers. * If no appropriate PUBLIC or SYSTEM entry is found in the Catalog, * delegated Catalogs are interrogated.

* *

There are four possible cases:

* *
    *
  • If the system identifier provided matches a SYSTEM entry * in the current catalog, the SYSTEM entry is returned. *
  • If the system identifier is not null, the PUBLIC entries * that were encountered when OVERRIDE YES was in effect are * interrogated and the first matching entry is returned.
  • *
  • If the system identifier is null, then all of the PUBLIC * entries are interrogated and the first matching entry * is returned. This may not be the same as the preceding case, if * some PUBLIC entries are encountered when OVERRIDE NO is in effect. In * XML, the only place where a public identifier may occur without * a system identifier is in a notation declaration.
  • *
  • Finally, if the public identifier matches one of the partial * public identifiers specified in a DELEGATE* entry in * the Catalog, the delegated catalog is interrogated. The first * time that the delegated catalog is required, it will be * retrieved and parsed. It is subsequently cached. *
  • *
* * @param entityType The CatalogEntry type for which this query is * being conducted. This is necessary in order to do the approprate * query on a delegated catalog. * @param entityName The name of the entity being searched for, if * appropriate. * @param publicId The public identifier of the entity in question. * @param systemId The nominal system identifier for the entity * in question (as provided in the source document). * * @throws MalformedURLException The formal system identifier of a * delegated catalog cannot be turned into a valid URL. * @throws IOException Error reading delegated catalog file. * * @return The system identifier to use. * Note that the nominal system identifier is not returned if a * match is not found in the catalog, instead null is returned * to indicate that no match was found. */ protected synchronized String resolveLocalPublic(int entityType, String entityName, String publicId, String systemId) throws MalformedURLException, IOException { // Always normalize the public identifier before attempting a match publicId = PublicId.normalize(publicId); // If there's a SYSTEM entry in this catalog, use it if (systemId != null) { String resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } // If there's a PUBLIC entry in this catalog, use it boolean over = default_override; Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == OVERRIDE) { over = e.getEntryArg(0).equalsIgnoreCase("YES"); continue; } if (e.getEntryType() == PUBLIC && e.getEntryArg(0).equals(publicId)) { if (over || systemId == null) { return e.getEntryArg(1); } } } // If there's a DELEGATE_PUBLIC entry in this catalog, use it over = default_override; enumt = catalogEntries.elements(); Vector delCats = new Vector(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == OVERRIDE) { over = e.getEntryArg(0).equalsIgnoreCase("YES"); continue; } if (e.getEntryType() == DELEGATE_PUBLIC && (over || systemId == null)) { String p = e.getEntryArg(0); if (p.length() <= publicId.length() && p.equals(publicId.substring(0, p.length()))) { // delegate this match to the other catalog delCats.addElement(e.getEntryArg(1)); } } } if (delCats.size() > 0) { Enumeration enumCats = delCats.elements(); if (catalogManager.debug.getDebug() > 1) { catalogManager.debug.message(2, "Switching to delegated catalog(s):"); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); catalogManager.debug.message(2, "\t" + delegatedCatalog); } } Catalog dcat = newCatalog(); enumCats = delCats.elements(); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); dcat.parseCatalog(delegatedCatalog); } return dcat.resolvePublic(publicId, null); } // Nada! return null; } /** * Return the applicable SYSTEM system identifier. * *

If a SYSTEM entry exists in the Catalog * for the system ID specified, return the mapped value.

* *

On Windows-based operating systems, the comparison between * the system identifier provided and the SYSTEM entries in the * Catalog is case-insensitive.

* * @param systemId The system ID to locate in the catalog. * * @return The resolved system identifier. * * @throws MalformedURLException The formal system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveSystem(String systemId) throws MalformedURLException, IOException { catalogManager.debug.message(3, "resolveSystem("+systemId+")"); systemId = normalizeURI(systemId); if (systemId != null && systemId.startsWith("urn:publicid:")) { systemId = PublicId.decodeURN(systemId); return resolvePublic(systemId, null); } // If there's a SYSTEM entry in this catalog, use it if (systemId != null) { String resolved = resolveLocalSystem(systemId); if (resolved != null) { return resolved; } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(SYSTEM, null, null, systemId); } /** * Return the applicable SYSTEM system identifier in this * catalog. * *

If a SYSTEM entry exists in the catalog file * for the system ID specified, return the mapped value.

* * @param systemId The system ID to locate in the catalog * * @return The mapped system identifier or null * @throws MalformedURLException * @throws IOException */ protected String resolveLocalSystem(String systemId) throws MalformedURLException, IOException { String osname = System.getProperty("os.name"); boolean windows = (osname.indexOf("Windows") >= 0); Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == SYSTEM && (e.getEntryArg(0).equals(systemId) || (windows && e.getEntryArg(0).equalsIgnoreCase(systemId)))) { return e.getEntryArg(1); } } // If there's a REWRITE_SYSTEM entry in this catalog, use it enumt = catalogEntries.elements(); String startString = null; String prefix = null; while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == REWRITE_SYSTEM) { String p = e.getEntryArg(0); if (p.length() <= systemId.length() && p.equals(systemId.substring(0, p.length()))) { // Is this the longest prefix? if (startString == null || p.length() > startString.length()) { startString = p; prefix = e.getEntryArg(1); } } } if (prefix != null) { // return the systemId with the new prefix return prefix + systemId.substring(startString.length()); } } // If there's a DELEGATE_SYSTEM entry in this catalog, use it enumt = catalogEntries.elements(); Vector delCats = new Vector(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == DELEGATE_SYSTEM) { String p = e.getEntryArg(0); if (p.length() <= systemId.length() && p.equals(systemId.substring(0, p.length()))) { // delegate this match to the other catalog delCats.addElement(e.getEntryArg(1)); } } } if (delCats.size() > 0) { Enumeration enumCats = delCats.elements(); if (catalogManager.debug.getDebug() > 1) { catalogManager.debug.message(2, "Switching to delegated catalog(s):"); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); catalogManager.debug.message(2, "\t" + delegatedCatalog); } } Catalog dcat = newCatalog(); enumCats = delCats.elements(); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); dcat.parseCatalog(delegatedCatalog); } return dcat.resolveSystem(systemId); } return null; } /** * Return the applicable URI. * *

If a URI entry exists in the Catalog * for the URI specified, return the mapped value.

* *

URI comparison is case sensitive.

* * @param uri The URI to locate in the catalog. * * @return The resolved URI. * * @throws MalformedURLException The system identifier of a * subordinate catalog cannot be turned into a valid URL. * @throws IOException Error reading subordinate catalog file. */ public String resolveURI(String uri) throws MalformedURLException, IOException { catalogManager.debug.message(3, "resolveURI("+uri+")"); uri = normalizeURI(uri); if (uri != null && uri.startsWith("urn:publicid:")) { uri = PublicId.decodeURN(uri); return resolvePublic(uri, null); } // If there's a URI entry in this catalog, use it if (uri != null) { String resolved = resolveLocalURI(uri); if (resolved != null) { return resolved; } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs(URI, null, null, uri); } /** * Return the applicable URI in this catalog. * *

If a URI entry exists in the catalog file * for the URI specified, return the mapped value.

* * @param uri The URI to locate in the catalog * * @return The mapped URI or null * @throws MalformedURLException * @throws IOException */ protected String resolveLocalURI(String uri) throws MalformedURLException, IOException { Enumeration enumt = catalogEntries.elements(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == URI && (e.getEntryArg(0).equals(uri))) { return e.getEntryArg(1); } } // If there's a REWRITE_URI entry in this catalog, use it enumt = catalogEntries.elements(); String startString = null; String prefix = null; while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == REWRITE_URI) { String p = e.getEntryArg(0); if (p.length() <= uri.length() && p.equals(uri.substring(0, p.length()))) { // Is this the longest prefix? if (startString == null || p.length() > startString.length()) { startString = p; prefix = e.getEntryArg(1); } } } if (prefix != null) { // return the systemId with the new prefix return prefix + uri.substring(startString.length()); } } // If there's a DELEGATE_URI entry in this catalog, use it enumt = catalogEntries.elements(); Vector delCats = new Vector(); while (enumt.hasMoreElements()) { CatalogEntry e = (CatalogEntry) enumt.nextElement(); if (e.getEntryType() == DELEGATE_URI) { String p = e.getEntryArg(0); if (p.length() <= uri.length() && p.equals(uri.substring(0, p.length()))) { // delegate this match to the other catalog delCats.addElement(e.getEntryArg(1)); } } } if (delCats.size() > 0) { Enumeration enumCats = delCats.elements(); if (catalogManager.debug.getDebug() > 1) { catalogManager.debug.message(2, "Switching to delegated catalog(s):"); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); catalogManager.debug.message(2, "\t" + delegatedCatalog); } } Catalog dcat = newCatalog(); enumCats = delCats.elements(); while (enumCats.hasMoreElements()) { String delegatedCatalog = (String) enumCats.nextElement(); dcat.parseCatalog(delegatedCatalog); } return dcat.resolveURI(uri); } return null; } /** * Search the subordinate catalogs, in order, looking for a match. * *

This method searches the Catalog and returns the system * identifier specified for the given entity type with the given * name, public, and system identifiers. In some contexts, these * may be null.

* * @param entityType The CatalogEntry type for which this query is * being conducted. This is necessary in order to do the approprate * query on a subordinate catalog. * @param entityName The name of the entity being searched for, if * appropriate. * @param publicId The public identifier of the entity in question * (as provided in the source document). * @param systemId The nominal system identifier for the entity * in question (as provided in the source document). This parameter is * overloaded for the URI entry type. * * @throws MalformedURLException The formal system identifier of a * delegated catalog cannot be turned into a valid URL. * @throws IOException Error reading delegated catalog file. * * @return The system identifier to use. * Note that the nominal system identifier is not returned if a * match is not found in the catalog, instead null is returned * to indicate that no match was found. */ protected synchronized String resolveSubordinateCatalogs(int entityType, String entityName, String publicId, String systemId) throws MalformedURLException, IOException { for (int catPos = 0; catPos < catalogs.size(); catPos++) { Catalog c = null; try { c = (Catalog) catalogs.elementAt(catPos); } catch (ClassCastException e) { String catfile = (String) catalogs.elementAt(catPos); c = newCatalog(); try { c.parseCatalog(catfile); } catch (MalformedURLException mue) { catalogManager.debug.message(1, "Malformed Catalog URL", catfile); } catch (FileNotFoundException fnfe) { catalogManager.debug.message(1, "Failed to load catalog, file not found", catfile); } catch (IOException ioe) { catalogManager.debug.message(1, "Failed to load catalog, I/O error", catfile); } catalogs.setElementAt(c, catPos); } String resolved = null; // Ok, now what are we supposed to call here? if (entityType == DOCTYPE) { resolved = c.resolveDoctype(entityName, publicId, systemId); } else if (entityType == DOCUMENT) { resolved = c.resolveDocument(); } else if (entityType == ENTITY) { resolved = c.resolveEntity(entityName, publicId, systemId); } else if (entityType == NOTATION) { resolved = c.resolveNotation(entityName, publicId, systemId); } else if (entityType == PUBLIC) { resolved = c.resolvePublic(publicId, systemId); } else if (entityType == SYSTEM) { resolved = c.resolveSystem(systemId); } else if (entityType == URI) { resolved = c.resolveURI(systemId); } if (resolved != null) { return resolved; } } return null; } // ----------------------------------------------------------------- /** * Replace backslashes with forward slashes. (URLs always use * forward slashes.) * * @param sysid The input system identifier. * @return The same system identifier with backslashes turned into * forward slashes. */ protected String fixSlashes (String sysid) { return sysid.replace('\\', '/'); } /** * Construct an absolute URI from a relative one, using the current * base URI. * * @param sysid The (possibly relative) system identifier * @return The system identifier made absolute with respect to the * current {@link #base}. */ protected String makeAbsolute(String sysid) { URL local = null; sysid = fixSlashes(sysid); try { local = new URL(base, sysid); } catch (MalformedURLException e) { catalogManager.debug.message(1, "Malformed URL on system identifier", sysid); } if (local != null) { return local.toString(); } else { return sysid; } } /** * Perform character normalization on a URI reference. * * @param uriref The URI reference * @return The normalized URI reference. */ protected String normalizeURI(String uriref) { String newRef = ""; byte[] bytes; if (uriref == null) { return null; } try { bytes = uriref.getBytes("UTF-8"); } catch (UnsupportedEncodingException uee) { // this can't happen catalogManager.debug.message(1, "UTF-8 is an unsupported encoding!?"); return uriref; } for (int count = 0; count < bytes.length; count++) { int ch = bytes[count] & 0xFF; if ((ch <= 0x20) // ctrl || (ch > 0x7F) // high ascii || (ch == 0x22) // " || (ch == 0x3C) // < || (ch == 0x3E) // > || (ch == 0x5C) // \ || (ch == 0x5E) // ^ || (ch == 0x60) // ` || (ch == 0x7B) // { || (ch == 0x7C) // | || (ch == 0x7D) // } || (ch == 0x7F)) { newRef += encodedByte(ch); } else { newRef += (char) bytes[count]; } } return newRef; } /** * Perform %-encoding on a single byte. * * @param b The 8-bit integer that represents th byte. (Bytes are signed but encoding needs to look at the bytes unsigned.) * @return The %-encoded string for the byte in question. */ protected String encodedByte (int b) { String hex = Integer.toHexString(b).toUpperCase(); if (hex.length() < 2) { return "%0" + hex; } else { return "%" + hex; } } // ----------------------------------------------------------------- /** * Add to the current list of delegated catalogs. * *

This method always constructs the {@link #localDelegate} * vector so that it is ordered by length of partial * public identifier.

* * @param entry The DELEGATE catalog entry */ protected void addDelegate(CatalogEntry entry) { int pos = 0; String partial = entry.getEntryArg(0); Enumeration local = localDelegate.elements(); while (local.hasMoreElements()) { CatalogEntry dpe = (CatalogEntry) local.nextElement(); String dp = dpe.getEntryArg(0); if (dp.equals(partial)) { // we already have this prefix return; } if (dp.length() > partial.length()) { pos++; } if (dp.length() < partial.length()) { break; } } // now insert partial into the vector at [pos] if (localDelegate.size() == 0) { localDelegate.addElement(entry); } else { localDelegate.insertElementAt(entry, pos); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogEx0000644000175000017500000001426010774222622033163 0ustar twernertwerner// CatalogException.java - Catalog exception /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; /** * Signal Catalog exception. * *

This exception is thrown if an error occurs loading a * catalog file.

* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ public class CatalogException extends Exception { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** A wrapper around another exception */ public static final int WRAPPER = 1; /** An invalid entry */ public static final int INVALID_ENTRY = 2; /** An invalid entry type */ public static final int INVALID_ENTRY_TYPE = 3; /** Could not instantiate an XML parser */ public static final int NO_XML_PARSER = 4; /** Unknown XML format */ public static final int UNKNOWN_FORMAT = 5; /** Unparseable XML catalog (not XML)*/ public static final int UNPARSEABLE = 6; /** XML but parse failed */ public static final int PARSE_FAILED = 7; /** * The embedded exception if tunnelling, or null. */ private Exception exception = null; private int exceptionType = 0; /** * Create a new CatalogException. * * @param type The exception type * @param message The error or warning message. */ public CatalogException (int type, String message) { super(message); this.exceptionType = type; this.exception = null; } /** * Create a new CatalogException. * * @param type The exception type */ public CatalogException (int type) { super("Catalog Exception " + type); this.exceptionType = type; this.exception = null; } /** * Create a new CatalogException wrapping an existing exception. * *

The existing exception will be embedded in the new * one, and its message will become the default message for * the CatalogException.

* * @param e The exception to be wrapped in a CatalogException. */ public CatalogException (Exception e) { super(); this.exceptionType = WRAPPER; this.exception = e; } /** * Create a new CatalogException from an existing exception. * *

The existing exception will be embedded in the new * one, but the new exception will have its own message.

* * @param message The detail message. * @param e The exception to be wrapped in a CatalogException. */ public CatalogException (String message, Exception e) { super(message); this.exceptionType = WRAPPER; this.exception = e; } /** * Return a detail message for this exception. * *

If there is an embedded exception, and if the CatalogException * has no detail message of its own, this method will return * the detail message from the embedded exception.

* * @return The error or warning message. */ public String getMessage () { String message = super.getMessage(); if (message == null && exception != null) { return exception.getMessage(); } else { return message; } } /** * Return the embedded exception, if any. * * @return The embedded exception, or null if there is none. */ public Exception getException () { return exception; } /** * Return the exception type * * @return The exception type */ public int getExceptionType () { return exceptionType; } /** * Override toString to pick up any embedded exception. * * @return A string representation of this exception. */ public String toString () { if (exception != null) { return exception.toString(); } else { return super.toString(); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/package.htmllibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/package.h0000644000175000017500000000150110470642610033123 0ustar twernertwerner

XML utilities.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogEntry.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/catalog/CatalogEn0000644000175000017500000002212610774222622033151 0ustar twernertwerner// CatalogEntry.java - Represents Catalog entries /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml.catalog; import java.util.Hashtable; import java.util.Vector; /** * Represents a Catalog entry. * *

Instances of this class represent individual entries * in a Catalog.

* *

Each catalog entry has a unique name and is associated with * an arbitrary number of arguments (all strings). For example, the * TR9401 catalog entry "PUBLIC" has two arguments, a public identifier * and a system identifier. Each entry has a unique numeric type, * assigned automatically when the entry type is created.

* *

The number and type of catalog entries is maintained * statically. Catalog classes, or their subclasses, can add * new entry types, but all Catalog objects share the same global pool * of types.

* *

Initially there are no valid entries.

* * @see Catalog * * @author Norman Walsh * Norman.Walsh@Sun.COM * * @version 1.0 */ @SuppressWarnings("unchecked") public class CatalogEntry { /** The nextEntry is the ordinal number of the next entry type. */ protected static int nextEntry = 0; /** * The entryTypes vector maps catalog entry names * (e.g., 'BASE' or 'SYSTEM') to their type (1, 2, etc.). * Names are case sensitive. */ protected static Hashtable entryTypes = new Hashtable(); /** The entryTypes vector maps catalog entry types to the number of arguments they're required to have. */ protected static Vector entryArgs = new Vector(); /** * Adds a new catalog entry type. * * @param name The name of the catalog entry type. This must be * unique among all types and is case-sensitive. (Adding a duplicate * name effectively replaces the old type with the new type.) * @param numArgs The number of arguments that this entry type * is required to have. There is no provision for variable numbers * of arguments. * @return The type for the new entry. */ public static int addEntryType(String name, int numArgs) { entryTypes.put(name, new Integer(nextEntry)); entryArgs.add(nextEntry, new Integer(numArgs)); nextEntry++; return nextEntry-1; } /** * Lookup an entry type * * @param name The name of the catalog entry type. * @return The type of the catalog entry with the specified name. * @throws CatalogException for any error */ public static int getEntryType(String name) throws CatalogException { if (!entryTypes.containsKey(name)) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } Integer iType = (Integer) entryTypes.get(name); if (iType == null) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } return iType.intValue(); } /** * Find out how many arguments an entry is required to have. * * @param name The name of the catalog entry type. * @return The number of arguments that entry type is required to have. * @throws CatalogException for any error */ public static int getEntryArgCount(String name) throws CatalogException { return getEntryArgCount(getEntryType(name)); } /** * Find out how many arguments an entry is required to have. * * @param type A valid catalog entry type. * @return The number of arguments that entry type is required to have. * @throws CatalogException for any error */ public static int getEntryArgCount(int type) throws CatalogException { try { Integer iArgs = (Integer) entryArgs.get(type); return iArgs.intValue(); } catch (ArrayIndexOutOfBoundsException e) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } } /** The entry type of this entry */ protected int entryType = 0; /** The arguments associated with this entry */ protected Vector args = null; /** * Null constructor; something for subclasses to call. */ public CatalogEntry() {} /** * Construct a catalog entry of the specified type. * * @param name The name of the entry type * @param args A String Vector of arguments * @throws CatalogException for any error */ public CatalogEntry(String name, Vector args) throws CatalogException { Integer iType = (Integer) entryTypes.get(name); if (iType == null) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } int type = iType.intValue(); try { Integer iArgs = (Integer) entryArgs.get(type); if (iArgs.intValue() != args.size()) { throw new CatalogException(CatalogException.INVALID_ENTRY); } } catch (ArrayIndexOutOfBoundsException e) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } entryType = type; this.args = args; } /** * Construct a catalog entry of the specified type. * * @param type * @param args A String Vector of arguments * @throws CatalogException for any error */ public CatalogEntry(int type, Vector args) throws CatalogException { try { Integer iArgs = (Integer) entryArgs.get(type); if (iArgs.intValue() != args.size()) { throw new CatalogException(CatalogException.INVALID_ENTRY); } } catch (ArrayIndexOutOfBoundsException e) { throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE); } entryType = type; this.args = args; } /** * Get the entry type. * * @return The entry type of the CatalogEntry */ public int getEntryType() { return entryType; } /** * Get an entry argument. * * @param argNum The argument number (arguments are numbered from 0). * @return The specified argument or null if an invalid argNum is * provided. */ public String getEntryArg(int argNum) { try { String arg = (String) args.get(argNum); return arg; } catch (ArrayIndexOutOfBoundsException e) { return null; } } /** * Set an entry argument. * *

Catalogs sometimes need to adjust the catlog entry parameters, * for example to make a relative URI absolute with respect to the * current base URI. But in general, this function should only be * called shortly after object creation to do some sort of cleanup. * Catalog entries should not mutate over time.

* * @param argNum The argument number (arguments are numbered from 0). * @param newspec * @throws ArrayIndexOutOfBoundsException if an invalid argument * number is provided. */ public void setEntryArg(int argNum, String newspec) throws ArrayIndexOutOfBoundsException { args.set(argNum, newspec); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/JBossEntityResolver.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/JBossEntityResolv0000644000175000017500000005702010776055124033316 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.xml; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jboss.logging.Logger; import org.jboss.util.StringPropertyReplacer; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Local entity resolver to handle standard J2EE DTDs and Schemas as well as JBoss * specific DTDs. *

* Function boolean isEntityResolved() is here to avoid validation errors in * descriptors that do not have a DOCTYPE declaration. * * @author Scott.Stark@jboss.org * @author Thomas.Diesler@jboss.org * @author Dimitris.Andreadis@jboss.org * @version $Revision: 2799 $ */ @SuppressWarnings("unchecked") public class JBossEntityResolver implements EntityResolver { private static final Logger log = Logger.getLogger(JBossEntityResolver.class); /** A class wide Map of publicId/systemId to dtd/xsd file */ private static Map entities = new ConcurrentHashMap (); /** A class flag indicating whether an attempt to resolve a systemID as a non-file URL should produce a warning rather than a trace level log msg. */ private static boolean warnOnNonFileURLs; private boolean entityResolved = false; /** Should system property refs in system ids be replaced */ private boolean replaceSystemProperties = true; /** A local entities map that overrides the class level entities */ private Map localEntities; static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { warnOnNonFileURLs = new Boolean(System.getProperty("org.jboss.resolver.warning", "false")).booleanValue(); return null; } }); registerEntity("http://java.sun.com/xml/ns/j2ee/application_1_4.xsd", "application_1_4.xsd"); registerEntity("http://java.sun.com/xml/ns/javaee/application_5.xsd", "application_5.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/application-client_1_4.xsd", "application-client_1_4.xsd"); registerEntity("http://java.sun.com/xml/ns/javaee/application-client_5.xsd", "application-client_5.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd", "connector_1_5.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd", "ejb-jar_2_1.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd", "j2ee_1_4.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", "web-app_2_4.xsd"); registerEntity("http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd", "web-app_2_5.xsd"); registerEntity("http://schemas.xmlsoap.org/soap/encoding/", "soap-encoding_1_1.xsd"); registerEntity("http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd", "j2ee_web_services_client_1_1.xsd"); registerEntity("http://www.ibm.com/webservices/xsd/j2ee_web_services_1_1.xsd", "j2ee_web_services_1_1.xsd"); registerEntity("http://www.ibm.com/webservices/xsd/j2ee_jaxrpc_mapping_1_1.xsd", "j2ee_jaxrpc_mapping_1_1.xsd"); registerEntity("http://www.w3.org/2001/xml.xsd", "xml.xsd"); registerEntity("http://www.w3.org/2005/05/xmlmime", "xml-media-types.xsd"); // ejb related registerEntity("-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN", "ejb-jar.dtd"); registerEntity("-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN", "ejb-jar_2_0.dtd"); // ear stuff registerEntity("-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN", "application_1_2.dtd"); registerEntity("-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN", "application_1_3.dtd"); registerEntity("-//Sun Microsystems, Inc.//DTD J2EE Application Client 1.3//EN", "application-client_1_3.dtd"); // connector descriptors registerEntity("-//Sun Microsystems, Inc.//DTD Connector 1.0//EN", "connector_1_0.dtd"); // war meta-data registerEntity("-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", "web-app_2_2.dtd"); registerEntity("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", "web-app_2_3.dtd"); // jboss-specific registerEntity("-//JBoss//DTD J2EE Application 1.3//EN", "jboss-app_3_0.dtd"); registerEntity("-//JBoss//DTD J2EE Application 1.3V2//EN", "jboss-app_3_2.dtd"); registerEntity("-//JBoss//DTD J2EE Application 1.4//EN", "jboss-app_4_0.dtd"); registerEntity("-//JBoss//DTD J2EE Application 4.2//EN", "jboss-app_4_2.dtd"); registerEntity("-//JBoss//DTD Java EE Application 5.0//EN", "jboss-app_5_0.dtd"); registerEntity("-//JBoss//DTD JAWS//EN", "jaws.dtd"); registerEntity("-//JBoss//DTD JAWS 2.4//EN", "jaws_2_4.dtd"); registerEntity("-//JBoss//DTD JAWS 3.0//EN", "jaws_3_0.dtd"); registerEntity("-//JBoss//DTD JBOSS//EN", "jboss.dtd"); registerEntity("-//JBoss//DTD JBOSS 2.4//EN", "jboss_2_4.dtd"); registerEntity("-//JBoss//DTD JBOSS 3.0//EN", "jboss_3_0.dtd"); registerEntity("-//JBoss//DTD JBOSS 3.2//EN", "jboss_3_2.dtd"); registerEntity("-//JBoss//DTD JBOSS 4.0//EN", "jboss_4_0.dtd"); registerEntity("-//JBoss//DTD JBOSS 4.2//EN", "jboss_4_2.dtd"); registerEntity("-//JBoss//DTD JBOSS 5.0//EN", "jboss_5_0.dtd"); registerEntity("-//JBoss//DTD JBOSSCMP-JDBC 3.0//EN", "jbosscmp-jdbc_3_0.dtd"); registerEntity("-//JBoss//DTD JBOSSCMP-JDBC 3.2//EN", "jbosscmp-jdbc_3_2.dtd"); registerEntity("-//JBoss//DTD JBOSSCMP-JDBC 4.0//EN", "jbosscmp-jdbc_4_0.dtd"); registerEntity("-//JBoss//DTD JBOSSCMP-JDBC 4.2//EN", "jbosscmp-jdbc_4_2.dtd"); registerEntity("-//JBoss//DTD Web Application 2.2//EN", "jboss-web.dtd"); registerEntity("-//JBoss//DTD Web Application 2.3//EN", "jboss-web_3_0.dtd"); registerEntity("-//JBoss//DTD Web Application 2.3V2//EN", "jboss-web_3_2.dtd"); registerEntity("-//JBoss//DTD Web Application 2.4//EN", "jboss-web_4_0.dtd"); registerEntity("-//JBoss//DTD Web Application 4.2//EN", "jboss-web_4_2.dtd"); registerEntity("-//JBoss//DTD Web Application 5.0//EN", "jboss-web_5_0.dtd"); registerEntity("-//JBoss//DTD Application Client 3.2//EN", "jboss-client_3_2.dtd"); registerEntity("-//JBoss//DTD Application Client 4.0//EN", "jboss-client_4_0.dtd"); registerEntity("-//JBoss//DTD Application Client 4.2//EN", "jboss-client_4_2.dtd"); registerEntity("-//JBoss//DTD Application Client 5.0//EN", "jboss-client_5_0.dtd"); registerEntity("-//JBoss//DTD Web Service Reference 4.0//EN", "service-ref_4_0.dtd"); registerEntity("-//JBoss//DTD Web Service Reference 4.2//EN", "service-ref_4_2.dtd"); registerEntity("-//JBoss//DTD Web Service Reference 5.0//EN", "service-ref_5_0.dtd"); registerEntity("-//JBoss//DTD MBean Service 3.2//EN", "jboss-service_3_2.dtd"); registerEntity("-//JBoss//DTD MBean Service 4.0//EN", "jboss-service_4_0.dtd"); registerEntity("-//JBoss//DTD MBean Service 4.2//EN", "jboss-service_4_2.dtd"); registerEntity("-//JBoss//DTD MBean Service 5.0//EN", "jboss-service_5_0.dtd"); registerEntity("-//JBoss//DTD JBOSS XMBEAN 1.0//EN", "jboss_xmbean_1_0.dtd"); registerEntity("-//JBoss//DTD JBOSS XMBEAN 1.1//EN", "jboss_xmbean_1_1.dtd"); registerEntity("-//JBoss//DTD JBOSS XMBEAN 1.2//EN", "jboss_xmbean_1_2.dtd"); registerEntity("-//JBoss//DTD JBOSS Security Config 3.0//EN", "security_config.dtd"); registerEntity("-//JBoss//DTD JBOSS JCA Config 1.0//EN", "jboss-ds_1_0.dtd"); registerEntity("-//JBoss//DTD JBOSS JCA Config 1.5//EN", "jboss-ds_1_5.dtd"); registerEntity("http://www.jboss.org/j2ee/schema/security-config_4_0.xsd", "security-config_4_0.xsd"); registerEntity("urn:jboss:aop-deployer", "aop-deployer_1_1.xsd"); registerEntity("urn:jboss:aop-beans:1.0", "aop-beans_1_0.xsd"); registerEntity("urn:jboss:bean-deployer", "bean-deployer_1_0.xsd"); registerEntity("urn:jboss:bean-deployer:2.0", "bean-deployer_2_0.xsd"); registerEntity("urn:jboss:javabean:1.0", "javabean_1_0.xsd"); registerEntity("urn:jboss:javabean:2.0", "javabean_2_0.xsd"); registerEntity("urn:jboss:spring-beans:2.0", "mc-spring-beans_2_0.xsd"); registerEntity("urn:jboss:policy:1.0", "policy_1_0.xsd"); registerEntity("urn:jboss:osgi-beans:1.0", "osgi-beans_1_0.xsd"); registerEntity("urn:jboss:seam-components:1.0", "seam-components_1_0.xsd"); registerEntity("urn:jboss:security-config:4.1", "security-config_4_1.xsd"); registerEntity("urn:jboss:security-config:5.0", "security-config_5_0.xsd"); registerEntity("urn:jboss:jndi-binding-service:1.0", "jndi-binding-service_1_0.xsd"); registerEntity("urn:jboss:user-roles:1.0", "user-roles_1_0.xsd"); // xml registerEntity("-//W3C//DTD/XMLSCHEMA 200102//EN", "XMLSchema.dtd"); registerEntity("http://www.w3.org/2001/XMLSchema.dtd", "XMLSchema.dtd"); registerEntity("datatypes", "datatypes.dtd"); // This dtd doesn't have a publicId - see XMLSchema.dtd registerEntity("http://www.w3.org/XML/1998/namespace", "xml.xsd"); // ejb3 and javaee5 related registerEntity("http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd", "ejb-jar_3_0.xsd"); registerEntity("http://java.sun.com/xml/ns/javaee/javaee_web_services_client_1_2.xsd", "javaee_web_services_client_1_2.xsd"); registerEntity("http://java.sun.com/xml/ns/javaee/javaee_5.xsd", "javaee_5.xsd"); registerEntity("http://www.jboss.org/j2ee/schema/jboss_5_0.xsd", "jboss_5_0.xsd"); } /** Obtain a read-only view of the current entity map. @return Map of the publicID/systemID to dtd/schema file name */ public static Map getEntityMap() { return Collections.unmodifiableMap(entities); } public static boolean isWarnOnNonFileURLs() { return warnOnNonFileURLs; } public static void setWarnOnNonFileURLs(boolean warnOnNonFileURLs) { JBossEntityResolver.warnOnNonFileURLs = warnOnNonFileURLs; } /** * Register the mapping from the public id/system id to the dtd/xsd file * name. This overwrites any existing mapping. * * @param id the DOCTYPE public id or system id such as * "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN" * @param dtdFileName the simple dtd/xsd file name, "ejb-jar.dtd" */ public static void registerEntity(String id, String dtdFileName) { entities.put(id, dtdFileName); } public boolean isReplaceSystemProperties() { return replaceSystemProperties; } public void setReplaceSystemProperties(boolean replaceSystemProperties) { this.replaceSystemProperties = replaceSystemProperties; } /** * Register the mapping from the public id/system id to the dtd/xsd file * name. This overwrites any existing mapping. * * @param id the DOCTYPE public id or system id such as * "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN" * @param dtdOrSchema the simple dtd/xsd file name, "ejb-jar.dtd" */ public synchronized void registerLocalEntity(String id, String dtdOrSchema) { if( localEntities == null ) localEntities = new ConcurrentHashMap(); localEntities.put(id, dtdOrSchema); } /** Returns DTD/Schema inputSource. The resolution logic is: 1. Check the publicId against the current registered values in the class mapping of entity name to dtd/schema file name. If found, the resulting file name is passed to the loadClasspathResource to locate the file as a classpath resource. 2. Check the systemId against the current registered values in the class mapping of entity name to dtd/schema file name. If found, the resulting file name is passed to the loadClasspathResource to locate the file as a classpath resource. 3. Strip the systemId name down to the simple file name by removing an URL style path elements (myschemas/x.dtd becomes x.dtd), and call loadClasspathResource to locate the simple file name as a classpath resource. 4. Attempt to resolve the systemId as a URL from which the schema can be read. If the URL input stream can be opened this returned as the resolved input. @param publicId - Public ID of DTD, or null if it is a schema @param systemId - the system ID of DTD or Schema @return InputSource of entity */ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { entityResolved = false; // nothing to resolve if( publicId == null && systemId == null ) return null; boolean trace = log.isTraceEnabled(); boolean resolvePublicIdFirst = true; if(publicId != null && systemId != null) { String registeredSystemId = null; if(localEntities != null) registeredSystemId = (String) localEntities.get(publicId); if(registeredSystemId == null) registeredSystemId = (String) entities.get(publicId); if(registeredSystemId != null && !registeredSystemId.equals(systemId)) { resolvePublicIdFirst = false; if(trace) log.trace("systemId argument '" + systemId + "' for publicId '" + publicId + "' is different from the registered systemId '" + registeredSystemId + "', resolution will be based on the argument"); } } InputSource inputSource = null; if(resolvePublicIdFirst) { // Look for a registered publicID inputSource = resolvePublicID(publicId, trace); } if( inputSource == null ) { // Try to resolve the systemID from the registry inputSource = resolveSystemID(systemId, trace); } if( inputSource == null ) { // Try to resolve the systemID as a classpath reference under dtd or schema inputSource = resolveClasspathName(systemId, trace); } if( inputSource == null ) { // Try to resolve the systemID as a absolute URL inputSource = resolveSystemIDasURL(systemId, trace); } entityResolved = (inputSource != null); if (entityResolved == false) log.debug("Cannot resolve [publicID=" + publicId + ",systemID=" + systemId + "]"); return inputSource; } /** * Returns the boolean value to inform id DTD was found in the XML file or not * * @todo this is not thread safe and should be removed? * * @return boolean - true if DTD was found in XML */ public boolean isEntityResolved() { return entityResolved; } /** Load the schema from the class entity to schema file mapping. @see #registerEntity(String, String) @param publicId - the public entity name of the schema @param trace - trace level logging flag @return the InputSource for the schema file found on the classpath, null if the publicId is not registered or found. */ protected InputSource resolvePublicID(String publicId, boolean trace) { if( publicId == null ) return null; if (trace) log.trace("resolvePublicID, publicId=" + publicId); InputSource inputSource = null; String filename = null; if( localEntities != null ) filename = (String) localEntities.get(publicId); if( filename == null ) filename = (String) entities.get(publicId); if( filename != null ) { if (trace) log.trace("Found entity from publicId=" + publicId + " fileName=" + filename); InputStream ins = loadClasspathResource(filename, trace); if( ins != null ) { inputSource = new InputSource(ins); inputSource.setPublicId(publicId); } else { log.trace("Cannot load publicId from classpath resource: " + filename); // Try the file name as a URI inputSource = resolveSystemIDasURL(filename, trace); if (inputSource == null) log.warn("Cannot load publicId from resource: " + filename); } } return inputSource; } /** Attempt to use the systemId as a URL from which the schema can be read. This checks to see whether the systemId is a key to an entry in the class entity map. @param systemId - the systemId @param trace - trace level logging flag @return the URL InputSource if the URL input stream can be opened, null if the systemId is not a URL or could not be opened. */ protected InputSource resolveSystemID(String systemId, boolean trace) { if( systemId == null ) return null; if( trace ) log.trace("resolveSystemID, systemId="+systemId); InputSource inputSource = null; // Try to resolve the systemId as an entity key String filename = null; if( localEntities != null ) filename = (String) localEntities.get(systemId); if( filename == null ) filename = (String) entities.get(systemId); if ( filename != null ) { if( trace ) log.trace("Found entity systemId=" + systemId + " fileName=" + filename); InputStream ins = loadClasspathResource(filename, trace); if( ins != null ) { inputSource = new InputSource(ins); inputSource.setSystemId(systemId); } else { log.warn("Cannot load systemId from resource: " + filename); } } return inputSource; } /** Attempt to use the systemId as a URL from which the schema can be read. This uses the systemID as a URL. @param systemId - the systemId @param trace - trace level logging flag @return the URL InputSource if the URL input stream can be opened, null if the systemId is not a URL or could not be opened. */ protected InputSource resolveSystemIDasURL(String systemId, boolean trace) { if( systemId == null ) return null; if( trace ) log.trace("resolveSystemIDasURL, systemId="+systemId); InputSource inputSource = null; // Try to use the systemId as a URL to the schema try { if (trace) log.trace("Trying to resolve systemId as a URL"); // Replace any system property refs if isReplaceSystemProperties is true if(isReplaceSystemProperties()) systemId = StringPropertyReplacer.replaceProperties(systemId); URL url = new URL(systemId); if (warnOnNonFileURLs && url.getProtocol().equalsIgnoreCase("file") == false) { log.warn("Trying to resolve systemId as a non-file URL: " + systemId); } InputStream ins = url.openStream(); if (ins != null) { inputSource = new InputSource(ins); inputSource.setSystemId(systemId); } else { log.warn("Cannot load systemId as URL: " + systemId); } if (trace) log.trace("Resolved systemId as a URL"); } catch (MalformedURLException ignored) { if (trace) log.trace("SystemId is not a url: " + systemId, ignored); } catch (IOException e) { if (trace) log.trace("Failed to obtain URL.InputStream from systemId: " + systemId, e); } return inputSource; } /** Resolve the systemId as a classpath resource. If not found, the systemId is simply used as a classpath resource name. @param systemId - the system ID of DTD or Schema @param trace - trace level logging flag @return the InputSource for the schema file found on the classpath, null if the systemId is not registered or found. */ protected InputSource resolveClasspathName(String systemId, boolean trace) { if( systemId == null ) return null; if( trace ) log.trace("resolveClasspathName, systemId="+systemId); String filename = systemId; // Parse the systemId as a uri to get the final path component try { URI url = new URI(systemId); String path = url.getPath(); if( path == null ) path = url.getSchemeSpecificPart(); int slash = path.lastIndexOf('/'); if( slash >= 0 ) filename = path.substring(slash + 1); else filename = path; if(path.length() == 0) return null; if (trace) log.trace("Mapped systemId to filename: " + filename); } catch (URISyntaxException e) { if (trace) log.trace("systemId: is not a URI, using systemId as resource", e); } // Resolve the filename as a classpath resource InputStream is = loadClasspathResource(filename, trace); InputSource inputSource = null; if( is != null ) { inputSource = new InputSource(is); inputSource.setSystemId(systemId); } return inputSource; } /** Look for the resource name on the thread context loader resource path. This first simply tries the resource name as is, and if not found, the resource is prepended with either "dtd/" or "schema/" depending on whether the resource ends in ".dtd" or ".xsd". @param resource - the classpath resource name of the schema @param trace - trace level logging flag @return the resource InputStream if found, null if not found. */ protected InputStream loadClasspathResource(String resource, boolean trace) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(resource); if( url == null ) { /* Prefix the simple filename with the schema type patch as this is the naming convention for the jboss bundled schemas. */ if( resource.endsWith(".dtd") ) resource = "dtd/" + resource; else if( resource.endsWith(".xsd") ) resource = "schema/" + resource; url = loader.getResource(resource); } InputStream inputStream = null; if( url != null ) { if( trace ) log.trace(resource+" maps to URL: "+url); try { inputStream = url.openStream(); } catch(IOException e) { log.debug("Failed to open url stream", e); } } return inputStream; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/DOMUtils.java0000644000175000017500000004270210774222622032264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.xml; // $Id: DOMUtils.java 2787 2008-03-31 17:55:30Z adrian@jboss.org $ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jboss.logging.Logger; import org.jboss.util.StringPropertyReplacer; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * DOM2 utilites * * @author Thomas.Diesler@jboss.org * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public final class DOMUtils { private static Logger log = Logger.getLogger(DOMUtils.class); // All elements created by the same thread are created by the same builder and belong to the same doc private static ThreadLocal documentThreadLocal = new ThreadLocal(); private static ThreadLocal builderThreadLocal = new ThreadLocal() { protected Object initialValue() { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new JBossEntityResolver()); return builder; } catch (ParserConfigurationException e) { throw new RuntimeException("Failed to create DocumentBuilder", e); } } }; // Hide the constructor private DOMUtils() { } public static DocumentBuilder getDocumentBuilder() { DocumentBuilder builder = (DocumentBuilder)builderThreadLocal.get(); return builder; } /** Parse the given XML string and return the root Element * @param xmlString * @return the element * @throws IOException */ public static Element parse(String xmlString) throws IOException { try { return parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); } catch (IOException e) { log.error("Cannot parse: " + xmlString); throw e; } } /** Parse the given XML stream and return the root Element * @param xmlStream * @return the element * @throws IOException */ public static Element parse(InputStream xmlStream) throws IOException { try { Document doc = getDocumentBuilder().parse(xmlStream); Element root = doc.getDocumentElement(); return root; } catch (SAXException e) { throw new IOException(e.toString()); } } /** Parse the given input source and return the root Element * @param source * @return the element * @throws IOException */ public static Element parse(InputSource source) throws IOException { try { Document doc = getDocumentBuilder().parse(source); Element root = doc.getDocumentElement(); return root; } catch (SAXException e) { throw new IOException(e.toString()); } } /** Create an Element for a given name * @param localPart * @return the element */ public static Element createElement(String localPart) { Document doc = getOwnerDocument(); log.trace("createElement {}" + localPart); return doc.createElement(localPart); } /** Create an Element for a given name and prefix * @param localPart * @param prefix * @return the element */ public static Element createElement(String localPart, String prefix) { Document doc = getOwnerDocument(); log.trace("createElement {}" + prefix + ":" + localPart); return doc.createElement(prefix + ":" + localPart); } /** Create an Element for a given name, prefix and uri * @param localPart * @param prefix * @param uri * @return the element */ public static Element createElement(String localPart, String prefix, String uri) { Document doc = getOwnerDocument(); if (prefix == null || prefix.length() == 0) { log.trace("createElement {" + uri + "}" + localPart); return doc.createElementNS(uri, localPart); } else { log.trace("createElement {" + uri + "}" + prefix + ":" + localPart); return doc.createElementNS(uri, prefix + ":" + localPart); } } /** Create an Element for a given QName * @param qname * @return the element */ public static Element createElement(QName qname) { return createElement(qname.getLocalPart(), qname.getPrefix(), qname.getNamespaceURI()); } /** Create a org.w3c.dom.Text node * @param value * @return the text node */ public static Text createTextNode(String value) { Document doc = getOwnerDocument(); return doc.createTextNode(value); } /** @return the qname of the given node. * @param el */ public static QName getElementQName(Element el) { String qualifiedName = el.getNodeName(); return resolveQName(el, qualifiedName); } /** Transform the giveen qualified name into a QName * @param el * @param qualifiedName * @return the resolved name */ public static QName resolveQName(Element el, String qualifiedName) { QName qname; String prefix = ""; String namespaceURI = ""; String localPart = qualifiedName; int colIndex = qualifiedName.indexOf(":"); if (colIndex > 0) { prefix = qualifiedName.substring(0, colIndex); localPart = qualifiedName.substring(colIndex + 1); if ("xmlns".equals(prefix)) { namespaceURI = "URI:XML_PREDEFINED_NAMESPACE"; } else { Element nsElement = el; while (namespaceURI.equals("") && nsElement != null) { namespaceURI = nsElement.getAttribute("xmlns:" + prefix); if (namespaceURI.equals("")) nsElement = getParentElement(nsElement); } } if (namespaceURI.equals("")) throw new IllegalArgumentException("Cannot find namespace uri for: " + qualifiedName); } qname = new QName(namespaceURI, localPart, prefix); return qname; } /** Get the value from the given attribute * @param el * @param attrName * * @return null if the attribute value is empty or the attribute is not present */ public static String getAttributeValue(Element el, String attrName) { return getAttributeValue(el, new QName(attrName)); } /** Get the value from the given attribute * @param el * @param attrName * * @return null if the attribute value is empty or the attribute is not present */ public static String getAttributeValue(Element el, QName attrName) { String attr = null; if ("".equals(attrName.getNamespaceURI())) attr = el.getAttribute(attrName.getLocalPart()); else attr = el.getAttributeNS(attrName.getNamespaceURI(), attrName.getLocalPart()); if ("".equals(attr)) attr = null; return attr; } /** @return the qname value from the given attribute * @param el * @param attrName */ public static QName getAttributeValueAsQName(Element el, String attrName) { return getAttributeValueAsQName(el, new QName(attrName)); } /** @return the qname value from the given attribute * @param el * @param attrName */ public static QName getAttributeValueAsQName(Element el, QName attrName) { QName qname = null; String qualifiedName = getAttributeValue(el, attrName); if (qualifiedName != null) { qname = resolveQName(el, qualifiedName); } return qname; } /** @return the boolean value from the given attribute * @param el * @param attrName */ public static boolean getAttributeValueAsBoolean(Element el, String attrName) { return getAttributeValueAsBoolean(el, new QName(attrName)); } /** @return the boolean value from the given attribute * @param el * @param attrName */ public static boolean getAttributeValueAsBoolean(Element el, QName attrName) { String attrVal = getAttributeValue(el, attrName); boolean ret = "true".equalsIgnoreCase(attrVal) || "1".equalsIgnoreCase(attrVal); return ret; } /** @return the integer value from the given attribute * @param el * @param attrName */ public static Integer getAttributeValueAsInteger(Element el, String attrName) { return getAttributeValueAsInteger(el, new QName(attrName)); } /** @param el * @param attrName * @return the integer value from the given attribute */ public static Integer getAttributeValueAsInteger(Element el, QName attrName) { String attrVal = getAttributeValue(el, attrName); return (attrVal != null ? new Integer(attrVal) : null); } /** @param el * @return the attributes as Map */ public static Map getAttributes(Element el) { Map attmap = new HashMap(); NamedNodeMap attribs = el.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { Attr attr = (Attr)attribs.item(i); String name = attr.getName(); QName qname = resolveQName(el, name); String value = attr.getNodeValue(); attmap.put(qname, value); } return attmap; } /** Copy attributes between elements * @param destElement * @param srcElement */ public static void copyAttributes(Element destElement, Element srcElement) { NamedNodeMap attribs = srcElement.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { Attr attr = (Attr)attribs.item(i); String uri = attr.getNamespaceURI(); String qname = attr.getName(); String value = attr.getNodeValue(); // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or // change an object in a way which is incorrect with regard to namespaces. if (uri == null && qname.startsWith("xmlns")) { log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]"); } else { destElement.setAttributeNS(uri, qname, value); } } } /** True if the node has child elements * @param node * @return true when has child elements */ public static boolean hasChildElements(Node node) { NodeList nlist = node.getChildNodes(); for (int i = 0; i < nlist.getLength(); i++) { Node child = nlist.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) return true; } return false; } /** Gets child elements * @param node * @return the iterator */ public static Iterator getChildElements(Node node) { ArrayList list = new ArrayList(); NodeList nlist = node.getChildNodes(); for (int i = 0; i < nlist.getLength(); i++) { Node child = nlist.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) list.add(child); } return list.iterator(); } /** Get the concatenated text content, or null. * @param node * @return getTextContent(node, false). */ public static String getTextContent(Node node) { return getTextContent(node, false); } /** Get the concatenated text content, or null. * @param node node to search for TEXT_NODE conent * @param replaceProps flag indicating if ${x} property refs should be replace * @return the text content */ public static String getTextContent(Node node, boolean replaceProps) { boolean hasTextContent = false; StringBuffer buffer = new StringBuffer(); NodeList nlist = node.getChildNodes(); for (int i = 0; i < nlist.getLength(); i++) { Node child = nlist.item(i); if (child.getNodeType() == Node.TEXT_NODE) { buffer.append(child.getNodeValue()); hasTextContent = true; } } String text = (hasTextContent ? buffer.toString() : null); if ( text != null && replaceProps) text = StringPropertyReplacer.replaceProperties(text); return text; } /** @return the first child element * @param node */ public static Element getFirstChildElement(Node node) { return getFirstChildElementIntern(node, null); } /** @param node * @param nodeName * @return the first child element for a given local name without namespace */ public static Element getFirstChildElement(Node node, String nodeName) { return getFirstChildElementIntern(node, new QName(nodeName)); } /** @param node * @param nodeName * @return the first child element for a given qname */ public static Element getFirstChildElement(Node node, QName nodeName) { return getFirstChildElementIntern(node, nodeName); } private static Element getFirstChildElementIntern(Node node, QName nodeName) { Element childElement = null; Iterator it = getChildElementsIntern(node, nodeName); if (it.hasNext()) { childElement = (Element)it.next(); } return childElement; } /** Gets the child elements for a given local name without namespace * @param node * @param nodeName * @return the iterator */ public static Iterator getChildElements(Node node, String nodeName) { return getChildElementsIntern(node, new QName(nodeName)); } /** Gets the child element for a given qname * @param node * @param nodeName * @return the iterator */ public static Iterator getChildElements(Node node, QName nodeName) { return getChildElementsIntern(node, nodeName); } private static Iterator getChildElementsIntern(Node node, QName nodeName) { ArrayList list = new ArrayList(); NodeList nlist = node.getChildNodes(); for (int i = 0; i < nlist.getLength(); i++) { Node child = nlist.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (nodeName == null) { list.add(child); } else { QName qname; if (nodeName.getNamespaceURI().length() > 0) { qname = new QName(child.getNamespaceURI(), child.getLocalName()); } else { qname = new QName(child.getLocalName()); } if (qname.equals(nodeName)) { list.add(child); } } } } return list.iterator(); } /** Gets parent element or null if there is none * @param node * @return the element */ public static Element getParentElement(Node node) { Node parent = node.getParentNode(); return (parent instanceof Element ? (Element)parent : null); } /** @return the owner document that is associated with the current thread */ public static Document getOwnerDocument() { Document doc = (Document)documentThreadLocal.get(); if (doc == null) { doc = getDocumentBuilder().newDocument(); documentThreadLocal.set(doc); } return doc; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/XmlHelper.java0000644000175000017500000001732710774222622032531 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.xml; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A utility class to cover up the rough bits of xml parsing * * @author Chris Kimpton * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class XmlHelper { public static void write(Writer out, Document dom) throws Exception { new DOMWriter(out).setPrettyprint(true).print(dom); } /** * Returns an iterator over the children of the given element with * the given tag name. * * @param element The parent element * @param tagName The name of the desired child * @return An interator of children or null if element is null. */ public static Iterator getChildrenByTagName(Element element, String tagName) { if (element == null) return null; // getElementsByTagName gives the corresponding elements in the whole // descendance. We want only children NodeList children = element.getChildNodes(); ArrayList goodChildren = new ArrayList(); for (int i=0; icatolog.xml found in the * Thread.currentThread().getContextClassLoader(). * * @author Daniel Wiese * @version $Revision: 2082 $ */ public class CatalogLocation { private static Logger log = Logger.getLogger(CatalogLocation.class); /** * The catalog is assembled by taking into account all accessible resources whose name is * META-INF/jax-ws-catalog.xml. Each resource MUST be a valid entity catalog according to the XML Catalogs */ private static final String[] catalogFilesNames = {"META-INF/jax-ws-catalog.xml", "WEB-INF/jax-ws-catalog.xml", "jax-ws-catalog.xml"}; private final Resolver catologResolver; private final URL location; private boolean isLastEntityResolved = false; static { // If the source document contains "oasis-xml-catalog" processing instructions, // should they be used? System.setProperty("xml.catalog.allowPI", "true"); //Which identifier is preferred, "public" or "system"? System.setProperty("xml.catalog.prefer", "public"); //If non-zero, the Catalog classes will print informative and debugging messages. //The higher the number, the more messages. System.setProperty("xml.catalog.verbosity", "0"); } /** * Create a new CatalogLocation. * @param url - the location of the catalog xml file * @throws IOException if the catalog files cannot be loaded */ public CatalogLocation(URL url) throws IOException { catologResolver = new Resolver(); catologResolver.setCatalogManager(CatalogManager.getStaticManager()); catologResolver.setupReaders(); catologResolver.parseCatalog(url); this.location=url; } /** * Tries to resolve the entity using the thread specific catolog resolvers * * @param publicId - Public ID of DTD, or null if it is a schema * @param systemId - the system ID of DTD or Schema * @return InputSource of entity * @throws MalformedURLException - if the url is wrong * @throws IOException - error reading the local file */ public InputSource resolveEntity(String publicId, String systemId) throws MalformedURLException, IOException { String resolvedURI = catologResolver.resolveSystem(systemId); if (resolvedURI == null) { resolvedURI = catologResolver.resolvePublic(publicId, systemId); } if (resolvedURI != null) { final InputSource is = new InputSource(); is.setPublicId(publicId); is.setSystemId(systemId); is.setByteStream(this.loadResource(resolvedURI)); this.isLastEntityResolved = true; return is; } else { //resource could�t be resloved this.isLastEntityResolved = false; return null; } } /** * Seach the path for oasis catalog files. The classpath of * Thread.currentThread().getContextClassLoader() * is used for the lookup. * @return the url where the jax-ws-catalog.xml is located * @throws IOException if the catalog files cannot be loaded * */ public static URL lookupCatalogFiles() throws IOException { URL url = null; //JAXWS-2.-0 spec, Line 27:the current context class loader MUST be used to //retrieve all the resources with the specified name ClassLoader loader = Thread.currentThread().getContextClassLoader(); for (int i = 0; i < catalogFilesNames.length; i++) { url = loader.getResource(catalogFilesNames[i]); //use the first hit if (url != null) { break; } } return url; } /** * Returns the boolean value to inform id DTD was found in the XML file or not * * * @return boolean - true if DTD was found in XML */ public boolean isEntityResolved() { return this.isLastEntityResolved; } /** * * Loads the resolved resource. * * @param resolvedURI - the full qualified URI of the resoved local ressource * @return - the inputstram represnting this resource * @throws IOException - if the resource cannot be opened */ private InputStream loadResource(String resolvedURI) throws IOException { try { final URI toLoad = new URI(resolvedURI); InputStream inputStream = null; if (toLoad != null) { try { inputStream = new FileInputStream(new File(toLoad)); } catch (IOException e) { log.error("Failed to open url stream", e); throw e; } } return inputStream; } catch (URISyntaxException e) { log.error("The URI (" + resolvedURI + ") is malfomed"); throw new IOException("The URI (" + resolvedURI + ") is malfomed"); } } /** * To catalog locations are qual if the location is equal. * @param other - the catlog location to compare * @return true if equal */ public boolean equals(Object other) { boolean back=false; if (other!=null && other instanceof CatalogLocation){ final CatalogLocation otherC=(CatalogLocation)other; back=this.location.equals(otherC.location); } return back; } /** * Two catalog locations have the same hash code if the location is equal. * @return - the hash code */ public int hashCode() { return this.location.hashCode(); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/XmlLoadable.java0000644000175000017500000000256110774222622033007 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.xml; import org.w3c.dom.Element; /** * * * @author Sebastien Alborini * @version $Revision: 2787 $ */ public interface XmlLoadable { // Public -------------------------------------------------------- public void importXml(Element element); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/JBossErrorHandler.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/JBossErrorHandler0000644000175000017500000000741010470642610033225 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.xml; import javax.xml.transform.ErrorListener; import javax.xml.transform.TransformerException; import org.jboss.logging.Logger; import org.jboss.util.JBossStringBuilder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; public class JBossErrorHandler implements ErrorHandler, ErrorListener { private static final Logger log =Logger.getLogger(JBossErrorHandler.class); // The xml file being parsed private String fileName; private JBossEntityResolver resolver; private boolean error; public JBossErrorHandler(String fileName, JBossEntityResolver resolver) { this.fileName = fileName; this.resolver = resolver; this.error = false; } public void error(SAXParseException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("error", e)); } } public void fatalError(SAXParseException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("fatal", e)); } } public void warning(SAXParseException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("warning", e)); } } public void error(TransformerException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("error", e)); } } public void fatalError(TransformerException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("fatal", e)); } } public void warning(TransformerException e) { if (resolver == null || resolver.isEntityResolved()) { error = true; log.error(formatError("warning", e)); } } protected String formatError(String context, SAXParseException e) { JBossStringBuilder buffer = new JBossStringBuilder(); buffer.append("File ").append(fileName); buffer.append(" process ").append(context); buffer.append(". Line: ").append(e.getLineNumber()); buffer.append(". Error message: ").append(e.getMessage()); return buffer.toString(); } protected String formatError(String context, TransformerException e) { JBossStringBuilder buffer = new JBossStringBuilder(); buffer.append("File ").append(fileName); buffer.append(" process ").append(context); buffer.append(". Location: ").append(e.getLocationAsString()); buffer.append(". Error message: ").append(e.getMessage()); return buffer.toString(); } public boolean hadError() { return error; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/DOMWriter.java0000644000175000017500000004401411044361066032433 0ustar twernertwerner/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.jboss.util.xml; // $Id: DOMWriter.java 2891 2008-07-31 16:03:02Z thomas.diesler@jboss.com $ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Traverse a DOM tree in order to print a document that is parsed. * * @author Andy Clark, IBM * @author Thomas.Diesler@jboss.org */ @SuppressWarnings("unchecked") public class DOMWriter { // Print writer private PrintWriter out; // True, if canonical output private boolean canonical; // True, if pretty printing should be used private boolean prettyprint; // True, if the XML declaration should be written private boolean writeXMLDeclaration; // True, if whitespace should be ignored private boolean ignoreWhitespace; // Explicit character set encoding private String charsetName; // indent for the pretty printer private int prettyIndent; // True, if the XML declaration has been written private boolean wroteXMLDeclaration; // The node that started the write private Node rootNode; // True if we want namespace completion private boolean completeNamespaces = true; // The current default namespace private String currentDefaultNamespace; public DOMWriter(Writer w) { this.out = new PrintWriter(w); } public DOMWriter(Writer w, String charsetName) { this.out = new PrintWriter(w); this.charsetName = charsetName; this.writeXMLDeclaration = true; } public DOMWriter(OutputStream stream) { try { this.out = new PrintWriter(new OutputStreamWriter(stream, "UTF-8")); } catch (UnsupportedEncodingException e) { // ignore, UTF-8 should be available } } public DOMWriter(OutputStream stream, String charsetName) { try { this.out = new PrintWriter(new OutputStreamWriter(stream, charsetName)); this.charsetName = charsetName; this.writeXMLDeclaration = true; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported encoding: " + charsetName); } } /** * Print a node with explicit prettyprinting. * The defaults for all other DOMWriter properties apply. * */ public static String printNode(Node node, boolean prettyprint) { StringWriter strw = new StringWriter(); new DOMWriter(strw).setPrettyprint(prettyprint).print(node); return strw.toString(); } public boolean isCanonical() { return canonical; } /** * Set wheter entities should appear in their canonical form. * The default is false. */ public DOMWriter setCanonical(boolean canonical) { this.canonical = canonical; return this; } public boolean isIgnoreWhitespace() { return ignoreWhitespace; } /** * Set whether whitespace should be ignored. * The default is false. */ public DOMWriter setIgnoreWhitespace(boolean ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; return this; } /** * Set wheter subelements should have their namespaces completed. * Setting this to false may lead to invalid XML fragments. * The default is true. */ public DOMWriter setCompleteNamespaces(boolean complete) { this.completeNamespaces = complete; return this; } public boolean isPrettyprint() { return prettyprint; } /** * Set wheter element should be indented. * The default is false. */ public DOMWriter setPrettyprint(boolean prettyprint) { this.prettyprint = prettyprint; return this; } public boolean isWriteXMLDeclaration() { return writeXMLDeclaration; } /** * Set wheter the XML declaration should be written. * The default is false. */ public DOMWriter setWriteXMLDeclaration(boolean flag) { this.writeXMLDeclaration = flag; return this; } public void print(Node node) { if (prettyprint && ignoreWhitespace) throw new IllegalStateException("Cannot pretty print and ignore whitespace"); rootNode = node; printInternal(node, false); } private void printInternal(Node node, boolean indentEndMarker) { // is there anything to do? if (node == null) { return; } // JBAS-2117 - Don't skip the DOCUMENT_NODE // if (node instanceof Document) node = ((Document)node).getDocumentElement(); if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) { out.print(""); if (prettyprint) out.println(); wroteXMLDeclaration = true; } int type = node.getNodeType(); boolean hasChildNodes = node.getChildNodes().getLength() > 0; String nodeName = node.getNodeName(); switch (type) { // print document case Node.DOCUMENT_NODE: { NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { printInternal(children.item(iChild), false); } out.flush(); break; } // print element with attributes case Node.ELEMENT_NODE: { Element element = (Element)node; if (prettyprint) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } prettyIndent++; } out.print('<'); out.print(nodeName); Map nsMap = new HashMap(); String elPrefix = node.getPrefix(); String elNamespaceURI = node.getNamespaceURI(); if (elPrefix != null) { String nsURI = getNamespaceURI(elPrefix, element, rootNode); nsMap.put(elPrefix, nsURI); } Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; String atPrefix = attr.getPrefix(); String atName = attr.getNodeName(); String atValue = normalize(attr.getNodeValue(), canonical); if (atName.equals("xmlns")) currentDefaultNamespace = atValue; if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) { String nsURI = getNamespaceURI(atPrefix, element, rootNode); nsMap.put(atPrefix, nsURI); // xsi:type='ns1:SubType', xsi:type='xsd:string' if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) { // xsi defined on the envelope if (nsURI == null) nsURI = getNamespaceURI(atPrefix, element, null); if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) { String typePrefix = atValue.substring(0, atValue.indexOf(":")); String typeURI = getNamespaceURI(typePrefix, element, rootNode); nsMap.put(typePrefix, typeURI); } } } out.print(" " + atName + "='" + atValue + "'"); } // Add namespace declaration for prefixes // that are defined further up the tree if (completeNamespaces) { Iterator itPrefix = nsMap.keySet().iterator(); while (itPrefix.hasNext()) { String prefix = (String)itPrefix.next(); String nsURI = (String)nsMap.get(prefix); if (nsURI == null) { nsURI = getNamespaceURI(prefix, element, null); out.print(" xmlns:" + prefix + "='" + nsURI + "'"); } } } // The SAX ContentHandler will by default not add the namespace declaration // World if (elPrefix == null && elNamespaceURI != null) { String defaultNamespace = element.getAttribute("xmlns"); if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) { out.print(" xmlns='" + elNamespaceURI + "'"); currentDefaultNamespace = elNamespaceURI; } } if (hasChildNodes) { out.print('>'); } // Find out if the end marker is indented indentEndMarker = isEndMarkerIndented(node); if (indentEndMarker) { out.print('\n'); } NodeList childNodes = node.getChildNodes(); int len = childNodes.getLength(); for (int i = 0; i < len; i++) { Node childNode = childNodes.item(i); printInternal(childNode, false); } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { if (canonical) { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { printInternal(children.item(i), false); } } } else { out.print('&'); out.print(nodeName); out.print(';'); } break; } // print cdata sections case Node.CDATA_SECTION_NODE: { if (canonical) { out.print(normalize(node.getNodeValue(), canonical)); } else { out.print(""); } break; } // print text case Node.TEXT_NODE: { String text = normalize(node.getNodeValue(), canonical); if (text.trim().length() > 0) { out.print(text); } else if (prettyprint == false && ignoreWhitespace == false) { out.print(text); } break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { out.print(" 0) { out.print(' '); out.print(data); } out.print("?>"); break; } // print comment case Node.COMMENT_NODE: { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } out.print(""); if (prettyprint) { out.print('\n'); } break; } } if (type == Node.ELEMENT_NODE) { if (prettyprint) prettyIndent--; if (hasChildNodes == false) { out.print("/>"); } else { if (indentEndMarker) { for (int i = 0; i < prettyIndent; i++) { out.print(' '); } } out.print("'); } if (prettyIndent > 0) { out.print('\n'); } } out.flush(); } private String getNamespaceURI(String prefix, Element element, Node stopNode) { Node parent = element.getParentNode(); String nsURI = element.getAttribute("xmlns:" + prefix); if (nsURI.length() == 0 && element != stopNode && parent instanceof Element) return getNamespaceURI(prefix, (Element)parent, stopNode); return (nsURI.length() > 0 ? nsURI : null); } private boolean isEndMarkerIndented(Node node) { if (prettyprint) { NodeList childNodes = node.getChildNodes(); int len = childNodes.getLength(); for (int i = 0; i < len; i++) { Node children = childNodes.item(i); if (children.getNodeType() == Node.ELEMENT_NODE) { return true; } } } return false; } /** Returns a sorted list of attributes. */ private Attr[] sortAttributes(NamedNodeMap attrs) { int len = (attrs != null) ? attrs.getLength() : 0; Attr array[] = new Attr[len]; for (int i = 0; i < len; i++) { array[i] = (Attr)attrs.item(i); } for (int i = 0; i < len - 1; i++) { String name = array[i].getNodeName(); int index = i; for (int j = i + 1; j < len; j++) { String curName = array[j].getNodeName(); if (curName.compareTo(name) < 0) { name = curName; index = j; } } if (index != i) { Attr temp = array[i]; array[i] = array[index]; array[index] = temp; } } return (array); } /** Normalizes the given string. */ public static String normalize(String s, boolean canonical) { StringBuffer str = new StringBuffer(); int len = (s != null) ? s.length() : 0; for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '<': { str.append("<"); break; } case '>': { str.append(">"); break; } case '&': { str.append("&"); break; } case '"': { str.append("""); break; } case '\'': { str.append("'"); break; } case '\r': case '\n': { if (canonical) { str.append("&#"); str.append(Integer.toString(ch)); str.append(';'); break; } // else, default append char } default: { str.append(ch); } } } return (str.toString()); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/xml/package.html0000644000175000017500000000150110470642610032226 0ustar twernertwerner

XML utilities.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/0000755000175000017500000000000011105642366031315 5ustar twernertwerner././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicTaskWrapper.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicTaskW0000644000175000017500000002407010470642610033232 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import org.jboss.logging.Logger; /** * A wrapper for the task. * * @author Adrian Brock * @version $Revision: 1958 $ */ public class BasicTaskWrapper implements TaskWrapper { /** The log */ private static final Logger log = Logger.getLogger(BasicTaskWrapper.class); /** The task has not been accepted */ public static final int TASK_NOT_ACCEPTED = 0; /** The task has been accepted */ public static final int TASK_ACCEPTED = 1; /** The task has been started */ public static final int TASK_STARTED = 2; /** The task has completed */ public static final int TASK_COMPLETED = 3; /** The task was rejected */ public static final int TASK_REJECTED = -1; /** The task has been stopped */ public static final int TASK_STOPPED = -2; /** The state of the task */ private int state = TASK_NOT_ACCEPTED; /** The state lock */ private Object stateLock = new Object(); /** The task */ private Task task; /** The task as a string */ private String taskString; /** The start time */ private long startTime; /** The start timeout */ private long startTimeout; /** The completion timeout */ private long completionTimeout; /** The priority */ private int priority; /** The wait type */ private int waitType; /** The thread */ private Thread runThread; /** * Create a task wrapper without a task */ protected BasicTaskWrapper() { } /** * Create a new task wrapper * * @param task the task * @throws IllegalArgumentException for a null task */ public BasicTaskWrapper(Task task) { setTask(task); } public int getTaskWaitType() { return waitType; } public int getTaskPriority() { return priority; } public long getTaskStartTimeout() { return startTimeout; } public long getTaskCompletionTimeout() { return completionTimeout; } public void acceptTask() { synchronized (stateLock) { // Not in a valid state if (state != TASK_NOT_ACCEPTED) return; } // Accept the task if (taskAccepted()) state = TASK_ACCEPTED; else state = TASK_REJECTED; // Notify the waiting task synchronized (stateLock) { stateLock.notifyAll(); } } public void rejectTask(RuntimeException e) { synchronized (stateLock) { state = TASK_REJECTED; stateLock.notifyAll(); } taskRejected(e); } public boolean isComplete() { return state == TASK_COMPLETED; } public void stopTask() { boolean started; synchronized (stateLock) { started = (state == TASK_STARTED); state = TASK_STOPPED; } if (started) { // Interrupt the run thread if its not null if( runThread != null ) { runThread.interrupt(); } taskStop(); } else if( runThread != null && runThread.isInterrupted() ) { /* If the thread has not been returned after being interrupted, then use the deprecated stop method to try to force the thread abort. */ runThread.stop(); } } public void waitForTask() { switch (waitType) { case Task.WAIT_FOR_START: { boolean interrupted = false; synchronized (stateLock) { while (state == TASK_NOT_ACCEPTED || state == TASK_ACCEPTED) { try { stateLock.wait(); } catch (InterruptedException e) { interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); return; } } default: { return; } } } /** * Called by the thread pool executor */ public void run() { // Get the execution thread this.runThread = Thread.currentThread(); // Check for a start timeout long runTime = getElapsedTime(); if (startTimeout > 0l && runTime >= startTimeout) { taskRejected(new StartTimeoutException("Start Timeout exceeded for task " + taskString)); return; } // We are about to start, check for a stop boolean stopped = false; synchronized (stateLock) { if (state == TASK_STOPPED) { stopped = true; } else { state = TASK_STARTED; taskStarted(); if (waitType == Task.WAIT_FOR_START) stateLock.notifyAll(); } } if (stopped) { taskRejected(new TaskStoppedException("Task stopped for task " + taskString)); return; } // Run the task Throwable throwable = null; try { task.execute(); } catch (Throwable t) { throwable = t; } // It is complete taskCompleted(throwable); // We are completed synchronized (stateLock) { state = TASK_COMPLETED; if (waitType == Task.WAIT_FOR_COMPLETE) stateLock.notifyAll(); } } /** * Set thetask for this wrapper * * @param task the task */ protected void setTask(Task task) { if (task == null) throw new IllegalArgumentException("Null task"); this.task = task; this.taskString = task.toString(); this.startTime = System.currentTimeMillis(); this.waitType = task.getWaitType(); this.priority = task.getPriority(); this.startTimeout = task.getStartTimeout(); this.completionTimeout = task.getCompletionTimeout(); } /** * Notify the task it has been accepted * * @return true when the notification succeeds, false otherwise */ protected boolean taskAccepted() { try { task.accepted(getElapsedTime()); return true; } catch (Throwable t) { log.warn("Unexpected error during 'accepted' for task: " + taskString, t); return false; } } /** * Notify the task it has been rejected * * @param e any error associated with the rejection * @return true when the notification succeeds, false otherwise */ protected boolean taskRejected(RuntimeException e) { try { task.rejected(getElapsedTime(), e); return true; } catch (Throwable t) { log.warn("Unexpected error during 'rejected' for task: " + taskString, t); if (e != null) log.warn("Original reason for rejection of task: " + taskString, e); return false; } } /** * Notify the task it has started * * @return true when the notification succeeds, false otherwise */ protected boolean taskStarted() { try { task.started(getElapsedTime()); return true; } catch (Throwable t) { log.warn("Unexpected error during 'started' for task: " + taskString, t); return false; } } /** * Notify the task it has completed * * @param throwable any throwable associated with the completion * @return true when the notification succeeds, false otherwise */ protected boolean taskCompleted(Throwable throwable) { try { task.completed(getElapsedTime(), throwable); return true; } catch (Throwable t) { log.warn("Unexpected error during 'completed' for task: " + taskString, t); if (throwable != null) log.warn("Original error during 'run' for task: " + taskString, throwable); return false; } } /** * Stop the task * * @return true when the notification succeeds, false otherwise */ protected boolean taskStop() { try { task.stop(); return true; } catch (Throwable t) { log.warn("Unexpected error during 'stop' for task: " + taskString, t); return false; } } /** * Calculate the elapsed time since the task was started * * @return the elapsed time in millis */ protected long getElapsedTime() { return System.currentTimeMillis() - startTime; } /** * Get the state as a string * * @return the state string */ protected String getStateString() { switch (state) { case TASK_NOT_ACCEPTED: return "NOT_ACCEPTED"; case TASK_REJECTED: return "REJECTED"; case TASK_ACCEPTED: return "ACCEPTED"; case TASK_STARTED: return "STARTED"; case TASK_STOPPED: return "STOPPED"; case TASK_COMPLETED: return "COMPLETED"; default: return "???"; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicThreadPool.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicThrea0000644000175000017500000005171711045571710033255 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import java.security.AccessController; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.PriorityQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.logging.Logger; import org.jboss.util.collection.WeakValueHashMap; import org.jboss.util.loading.ClassLoaderSource; import org.jboss.util.loading.ContextClassLoaderSwitcher; /** * A basic thread pool. * TODO: this port to jdk concurrent still needs to be tested. * * @author Adrian Brock * @author Scott.Stark@jboss.org * @version $Revision: 2892 $ */ @SuppressWarnings("unchecked") public class BasicThreadPool implements ThreadPool, BasicThreadPoolMBean { // Constants ----------------------------------------------------- /** The jboss thread group */ private static final ThreadGroup JBOSS_THREAD_GROUP = new ThreadGroup("JBoss Pooled Threads"); /** The thread groups */ private static final Map threadGroups = Collections.synchronizedMap(new WeakValueHashMap()); /** The internal pool number */ private static final AtomicInteger lastPoolNumber = new AtomicInteger(0); private static Logger log = Logger.getLogger(BasicThreadPool.class); // Attributes ---------------------------------------------------- /** The thread pool name */ private String name; /** The internal pool number */ private int poolNumber; /** The blocking mode */ private BlockingMode blockingMode = BlockingMode.ABORT; /** The pooled executor */ private ThreadPoolExecutor executor; /** The queue */ private LinkedBlockingQueue queue; /** The thread group */ private ThreadGroup threadGroup; /** Source for the thread contrext classloader to assign to threads */ private ClassLoaderSource classLoaderSource; private ContextClassLoaderSwitcher classLoaderSwitcher; /** The last thread number */ private AtomicInteger lastThreadNumber = new AtomicInteger(0); /** Has the pool been stopped? */ private AtomicBoolean stopped = new AtomicBoolean(false); /** The Heap of tasks ordered by their completion timeout */ private PriorityQueue tasksWithTimeouts = new PriorityQueue(13); /** The task completion timeout monitor runnable */ private TimeoutMonitor timeoutTask; /** The trace level logging flag */ private boolean trace; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new thread pool */ public BasicThreadPool() { this("ThreadPool"); } /** * Create a new thread pool with a default queue size of 1024, max pool * size of 100, min pool size of 4, and a keep alive of 60 seconds. * * @param name the pool name */ public BasicThreadPool(String name) { this(name, JBOSS_THREAD_GROUP); } /** * Create a new thread pool with a default queue size of 1024, max pool * size of 100, min pool size of 4, and a keep alive of 60 seconds. * * @param name the pool name * @param threadGroup threadGroup */ public BasicThreadPool(String name, ThreadGroup threadGroup) { trace = log.isTraceEnabled(); ThreadFactory factory = new ThreadPoolThreadFactory(); queue = new LinkedBlockingQueue(1024); executor = new RestoreTCCLThreadPoolExecutor(4, 4, 60, TimeUnit.SECONDS, queue); executor.setThreadFactory(factory); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); poolNumber = lastPoolNumber.incrementAndGet(); setName(name); this.threadGroup = threadGroup; } // Public -------------------------------------------------------- // ThreadPool ---------------------------------------------------- public void stop(boolean immediate) { log.debug("stop, immediate="+immediate); stopped.set(true); if (immediate) executor.shutdownNow(); else executor.shutdown(); } public void waitForTasks() throws InterruptedException { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } public void waitForTasks(long maxWaitTime) throws InterruptedException { executor.awaitTermination(maxWaitTime, TimeUnit.MILLISECONDS); } public void runTaskWrapper(TaskWrapper wrapper) { if( trace ) log.trace("runTaskWrapper, wrapper="+wrapper); if (stopped.get()) { wrapper.rejectTask(new ThreadPoolStoppedException("Thread pool has been stopped")); return; } wrapper.acceptTask(); long completionTimeout = wrapper.getTaskCompletionTimeout(); TimeoutInfo info; if(completionTimeout > 0) { checkTimeoutMonitor(); // Install the task in the info = new TimeoutInfo(wrapper, completionTimeout); tasksWithTimeouts.add(info); } int waitType = wrapper.getTaskWaitType(); switch (waitType) { case Task.WAIT_FOR_COMPLETE: { executeOnThread(wrapper); break; } default: { execute(wrapper); } } waitForTask(wrapper); } public void runTask(Task task) { BasicTaskWrapper wrapper = new BasicTaskWrapper(task); runTaskWrapper(wrapper); } public void run(Runnable runnable) { run(runnable, 0, 0); } public void run(Runnable runnable, long startTimeout, long completeTimeout) { RunnableTaskWrapper wrapper = new RunnableTaskWrapper(runnable, startTimeout, completeTimeout); runTaskWrapper(wrapper); } public ThreadGroup getThreadGroup() { return threadGroup; } // ThreadPoolMBean implementation -------------------------------- public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPoolNumber() { return poolNumber; } public String getThreadGroupName() { return threadGroup.getName(); } public void setThreadGroupName(String threadGroupName) { ThreadGroup group; synchronized(threadGroups) { group = (ThreadGroup) threadGroups.get(threadGroupName); if (group == null) { group = new ThreadGroup(JBOSS_THREAD_GROUP, threadGroupName); threadGroups.put(threadGroupName, group); } } threadGroup = group; } public int getQueueSize() { return queue.size(); } public int getMaximumQueueSize() { return queue.remainingCapacity() + queue.size(); } /** * This resets the work queue capacity. This requires recreating the * work queue and ThreadPoolExecutor, so this needs to be called * before doing any work with the pool. * * @param size new work queue capacity */ public void setMaximumQueueSize(int size) { // Reset the executor work queue ArrayList tmp = new ArrayList(); queue.drainTo(tmp); queue = new LinkedBlockingQueue(size); queue.addAll(tmp); ThreadFactory tf = executor.getThreadFactory(); RejectedExecutionHandler handler = executor.getRejectedExecutionHandler(); long keepAlive = executor.getKeepAliveTime(TimeUnit.SECONDS); int cs = executor.getCorePoolSize(); int mcs = executor.getMaximumPoolSize(); executor = new ThreadPoolExecutor(cs, mcs, keepAlive, TimeUnit.SECONDS, queue); executor.setThreadFactory(tf); executor.setRejectedExecutionHandler(handler); } public int getPoolSize() { return executor.getPoolSize(); } public int getMinimumPoolSize() { return executor.getCorePoolSize(); } public void setMinimumPoolSize(int size) { synchronized (executor) { // Don't let the min size > max size if (executor.getMaximumPoolSize() < size) { executor.setCorePoolSize(size); executor.setMaximumPoolSize(size); } } } public int getMaximumPoolSize() { return executor.getMaximumPoolSize(); } public void setMaximumPoolSize(int size) { synchronized (executor) { executor.setCorePoolSize(size); executor.setMaximumPoolSize(size); } } public long getKeepAliveTime() { return executor.getKeepAliveTime(TimeUnit.MILLISECONDS); } public void setKeepAliveTime(long time) { executor.setKeepAliveTime(time, TimeUnit.MILLISECONDS); } public BlockingMode getBlockingMode() { return blockingMode; } public void setBlockingMode(BlockingMode mode) { blockingMode = mode; if( blockingMode == BlockingMode.RUN ) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); } else if( blockingMode == BlockingMode.WAIT ) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); } else if( blockingMode == BlockingMode.DISCARD ) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); } else if( blockingMode == BlockingMode.DISCARD_OLDEST ) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); } else if( blockingMode == BlockingMode.ABORT ) { executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); } else { throw new IllegalArgumentException("Failed to recognize mode: "+mode); } } /** * For backward compatibility with the previous string based mode * @param name - the string form of the mode enum */ public void setBlockingMode(String name) { blockingMode = BlockingMode.toBlockingMode(name); if( blockingMode == null ) blockingMode = BlockingMode.ABORT; } /** * For backward compatibility with the previous string based mode * This is needed for microcontainer as it gets confused with overloaded * setters. * @param name - the string form of the mode enum */ public void setBlockingModeString(String name) { blockingMode = BlockingMode.toBlockingMode(name); if( blockingMode == null ) blockingMode = BlockingMode.ABORT; } public ClassLoaderSource getClassLoaderSource() { return classLoaderSource; } public void setClassLoaderSource(ClassLoaderSource classLoaderSource) { if (classLoaderSource == null) { this.classLoaderSource = null; this.classLoaderSwitcher = null; } else if (classLoaderSwitcher == null) { try { this.classLoaderSwitcher = (ContextClassLoaderSwitcher) AccessController.doPrivileged(ContextClassLoaderSwitcher.INSTANTIATOR); this.classLoaderSource = classLoaderSource; } catch (SecurityException e) { log.error("Cannot manage context classloader for pool threads; " + "Do not have setContextClassLoader permission"); } } else { this.classLoaderSource = classLoaderSource; } } public ThreadPool getInstance() { return this; } public void stop() { stop(false); } // Object overrides ---------------------------------------------- public String toString() { return name + '(' + poolNumber + ')'; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- /** * Execute a task on the same thread * * @param wrapper the task wrapper */ protected void executeOnThread(TaskWrapper wrapper) { if( trace ) log.trace("executeOnThread, wrapper="+wrapper); wrapper.run(); } /** * Execute a task * * @param wrapper the task wrapper */ protected void execute(TaskWrapper wrapper) { if( trace ) log.trace("execute, wrapper="+wrapper); try { executor.execute(wrapper); } catch (Throwable t) { wrapper.rejectTask(new ThreadPoolFullException("Error scheduling work: " + wrapper, t)); } } /** * Wait for a task * * @param wrapper the task wrapper */ protected void waitForTask(TaskWrapper wrapper) { wrapper.waitForTask(); } /** * Used to lazily create the task completion timeout thread and monitor */ protected synchronized void checkTimeoutMonitor() { if( timeoutTask == null ) timeoutTask = new TimeoutMonitor(name, log); } protected TimeoutInfo getNextTimeout() { TimeoutInfo info = null; if(this.tasksWithTimeouts.isEmpty() == false) { info = this.tasksWithTimeouts.remove(); } return info; } protected void setDefaultThreadContextClassLoader(Thread thread) { if (classLoaderSwitcher != null) { ClassLoader cl = classLoaderSource == null ? null : classLoaderSource.getClassLoader(); classLoaderSwitcher.setContextClassLoader(thread, cl); } } // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- /** * A factory for threads */ private class ThreadPoolThreadFactory implements ThreadFactory { public Thread newThread(Runnable runnable) { String threadName = BasicThreadPool.this.toString() + "-" + lastThreadNumber.incrementAndGet(); Thread thread = new Thread(threadGroup, runnable, threadName); thread.setDaemon(true); BasicThreadPool.this.setDefaultThreadContextClassLoader(thread); return thread; } } private class RestoreTCCLThreadPoolExecutor extends ThreadPoolExecutor { public RestoreTCCLThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override protected void afterExecute(Runnable r, Throwable t) { try { super.afterExecute(r, t); } finally { BasicThreadPool.this.setDefaultThreadContextClassLoader(Thread.currentThread()); } } } /** An encapsulation of a task and its completion timeout */ private static class TimeoutInfo implements Comparable { long start; long timeoutMS; TaskWrapper wrapper; boolean firstStop; TimeoutInfo(TaskWrapper wrapper, long timeout) { this.start = System.currentTimeMillis(); this.timeoutMS = start + timeout; this.wrapper = wrapper; } public void setTimeout(long timeout) { this.start = System.currentTimeMillis(); this.timeoutMS = start + timeout; } /** Order TimeoutInfo based on the timestamp at which the task needs to * be completed by. * @param o a TimeoutInfo * @return the diff between this timeoutMS and the argument timeoutMS */ public int compareTo(Object o) { TimeoutInfo ti = (TimeoutInfo) o; long to0 = timeoutMS; long to1 = ti.timeoutMS; return (int) (to0 - to1); } TaskWrapper getTaskWrapper() { return wrapper; } public long getTaskCompletionTimeout() { return wrapper.getTaskCompletionTimeout(); } /** Get the time remaining to the complete timeout timestamp in MS. * @param now - the current System.currentTimeMillis value * @return the time remaining to the complete timeout timestamp in MS. */ public long getTaskCompletionTimeout(long now) { return timeoutMS - now; } /** Invoke stopTask on the wrapper and indicate whether this was the first * time the task has been notified to stop. * @return true if this is the first stopTask, false on the second. */ public boolean stopTask() { wrapper.stopTask(); boolean wasFirstStop = firstStop == false; firstStop = true; return wasFirstStop; } } /** * The monitor runnable which validates that threads are completing within * the task completion timeout limits. */ private class TimeoutMonitor implements Runnable { @SuppressWarnings("hiding") final Logger log; TimeoutMonitor(String name, Logger log) { this.log = log; Thread t = new Thread(this, name+" TimeoutMonitor"); t.setDaemon(true); t.start(); } /** The monitor thread loops until the pool is shutdown. It waits for * tasks with completion timeouts and sleeps until the next completion * timeout and then interrupts the associated task thread, and invokes * stopTask on the TaskWrapper. A new timeout check is then inserted with * a 1 second timeout to validate that the TaskWrapper has exited the * run method. If it has not, then the associated task thread is stopped * using the deprecated Thread.stop method since this is the only way to * abort a thread that is in spin loop for example. * * @todo this is not responsive to new tasks with timeouts smaller than * the current shortest completion expiration. We probably should interrupt * the thread on each insertion into the timeout heap to ensure better * responsiveness. */ public void run() { boolean isStopped = stopped.get(); while( isStopped == false ) { boolean trace = log.isTraceEnabled(); try { TimeoutInfo info = getNextTimeout(); if( info != null ) { long now = System.currentTimeMillis(); long timeToTimeout = info.getTaskCompletionTimeout(now); if( timeToTimeout > 0 ) { if( trace ) { log.trace("Will check wrapper="+info.getTaskWrapper() +" after "+timeToTimeout); } Thread.sleep(timeToTimeout); } // Check the status of the task TaskWrapper wrapper = info.getTaskWrapper(); if( wrapper.isComplete() == false ) { if( trace ) log.trace("Failed completion check for wrapper="+wrapper); if( info.stopTask() == true ) { // Requeue the TimeoutInfo to see that the task exits run info.setTimeout(1000); tasksWithTimeouts.add(info); if( trace ) log.trace("Rescheduled completion check for wrapper="+wrapper); } } } else { Thread.sleep(1000); } } catch(InterruptedException e) { log.debug("Timeout monitor has been interrupted", e); } catch(Throwable e) { log.debug("Timeout monitor saw unexpected error", e); } isStopped = stopped.get(); } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPool.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPool0000644000175000017500000000525311045571710033303 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * A thread pool. * * @author Adrian Brock * @version $Revision: 2892 $ */ public interface ThreadPool { /** * Stop the pool * * @param immediate whether to shutdown immediately */ public void stop(boolean immediate); /** * Wait on the queued tasks to complete. * This can only be called after stop. * * @throws InterruptedException for any iterruption error */ public void waitForTasks() throws InterruptedException; /** * Wait on the queued tasks to complete upto maxWaitTime milliseconds. * This can only be called after stop. * * @param maxWaitTime the max wait time * @throws InterruptedException for any interruption error */ public void waitForTasks(long maxWaitTime) throws InterruptedException; /** * Run a task wrapper * * @param wrapper the task wrapper */ public void runTaskWrapper(TaskWrapper wrapper); /** * Run a task * * @param task the task * @throws IllegalArgumentException for a null task */ public void runTask(Task task); /** * Run a runnable * * @param runnable the runnable * @throws IllegalArgumentException for a null runnable */ public void run(Runnable runnable); /** * Run runnable with start and complete time out set explicitely. * * @param runnable the runnable * @param startTimeout the start timeout * @param completeTimeout the complete timeout * @throws IllegalArgumentException for a null runnable */ public void run(Runnable runnable, long startTimeout, long completeTimeout); } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPoolStoppedException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPool0000644000175000017500000000442410776226110033303 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * The thread pool was stopped. * * @author Adrian Brock * @version $Revision: 2800 $ */ public class ThreadPoolStoppedException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = 8732248855455909385L; // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new ThreadPoolStoppedException */ public ThreadPoolStoppedException() { super(); } /** * Create a new ThreadPoolStoppedException * * @param message the message */ public ThreadPoolStoppedException(String message) { super(message); } // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/TaskStoppedException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/TaskStoppe0000644000175000017500000000436010776226110033336 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * The task was stopped. * * @author Adrian Brock * @version $Revision: 2800 $ */ public class TaskStoppedException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = -5166095239829218680L; // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new TaskStoppedException */ public TaskStoppedException() { super(); } /** * Create a new TaskStoppedException * * @param message the message */ public TaskStoppedException(String message) { super(message); } // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/Task.java0000644000175000017500000000566510774222622033076 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * A task for a thread pool. * * @author Adrian Brock * @version $Revision: 2787 $ */ public interface Task { // Constants ----------------------------------------------------- /** Don't wait for task */ static final int WAIT_NONE = 0; /** Synchronized start, wait for task to start */ static final int WAIT_FOR_START = 1; /** Synchronized task, wait for task to complete */ static final int WAIT_FOR_COMPLETE = 2; // Public -------------------------------------------------------- /** * Get the type of wait * * @return the wait type */ int getWaitType(); /** * The priority of the task * * @return the task priority */ int getPriority(); /** * The time before the task must be accepted * * @return the start timeout */ long getStartTimeout(); /** * The time before the task must be completed * * @return the completion timeout */ long getCompletionTimeout(); /** * Execute the task */ void execute(); /** * Invoked by the threadpool when it wants to stop the task */ void stop(); /** * The task has been accepted * * @param time the time taken to accept the task */ void accepted(long time); /** * The task has been rejected * * @param time the time taken to reject the task * @param t any error associated with the rejection */ void rejected(long time, Throwable t); /** * The task has been started * * @param time the time taken to start the task */ void started(long time); /** * The task has been completed * * @param time the time taken to reject the task * @param t any error associated with the completion */ void completed(long time, Throwable t); // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPoolMBean.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPool0000644000175000017500000000457610774222622033315 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * Management interface for the thread pool. * * @author Adrian Brock * @version $Revision: 2787 $ */ public interface ThreadPoolMBean { // Constants ----------------------------------------------------- // Public -------------------------------------------------------- /** * Get the thread pool name * * @return the thread pool name */ String getName(); /** * Set the thread pool name * * @param name the name */ void setName(String name); /** * Get the internal pool number * * @return the internal pool number */ int getPoolNumber(); /** * Get the minimum pool size * * @return the minimum pool size */ int getMinimumPoolSize(); /** * Set the minimum pool size * * @param size the minimum pool size */ void setMinimumPoolSize(int size); /** * Get the maximum pool size * * @return the maximum pool size */ int getMaximumPoolSize(); /** * Set the maximum pool size * * @param size the maximum pool size */ void setMaximumPoolSize(int size); /** * @return the instance */ ThreadPool getInstance(); /** * Stop the thread pool */ void stop(); // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/TaskWrapper.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/TaskWrappe0000644000175000017500000000433011045571710033316 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * A task wrapper for a thread pool. * * @author Adrian Brock * @version $Revision: 2892 $ */ public interface TaskWrapper extends Runnable { /** * Get the type of wait * * @return the wait type */ int getTaskWaitType(); /** * The priority of the task * * @return the task priority */ int getTaskPriority(); /** * The time before the task must be accepted * * @return the start timeout */ long getTaskStartTimeout(); /** * The time before the task must be completed * * @return the completion timeout */ long getTaskCompletionTimeout(); /** * Wait according the wait type */ void waitForTask(); /** * Invoked by the threadpool when it wants to stop the task */ void stopTask(); /** * The task has been accepted * */ void acceptTask(); /** * The task has been rejected * * @param e any error associated with the rejection */ void rejectTask(RuntimeException e); /** * Is the task complete. * * @return true if compelet, false otherwise */ boolean isComplete(); } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/StartTimeoutException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/StartTimeo0000644000175000017500000000437610776226110033343 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * The start timeout was exceeded. * * @author Adrian Brock * @version $Revision: 2800 $ */ public class StartTimeoutException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = 2287779538710535096L; // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new StartTimeoutException */ public StartTimeoutException() { super(); } /** * Create a new StartTimeoutException * * @param message the message */ public StartTimeoutException(String message) { super(message); } // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPoolFullException.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/ThreadPool0000644000175000017500000000355010776226110033302 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; /** * The thread pool is full. * * @author Adrian Brock * @version $Revision: 2800 $ */ public class ThreadPoolFullException extends RuntimeException { /** The serialVersionUID */ private static final long serialVersionUID = -1044683480627340299L; /** * Create a new ThreadPoolFullException */ public ThreadPoolFullException() { super(); } /** * Create a new ThreadPoolFullException * * @param message the message */ public ThreadPoolFullException(String message) { super(message); } /** * Create a new ThreadPoolFullException. * * @param message the message * @param t the throwable */ public ThreadPoolFullException(String message, Throwable t) { super(message, t); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/MinPooledExecutor.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/MinPooledE0000644000175000017500000000730310774222622033236 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** A pooled executor where the minimum pool size threads are kept alive. This is needed in order for the waitWhenBlocked option to work because of a race condition inside the Executor. The race condition goes something like: RT - Requesting Thread wanting to use the pool LT - Last Thread in the pool RT: Check there are enough free threads to process, yes LT is there, so no need to create a new thread. LT: Times out on the keep alive, LT is destroyed. RT: Try to execute, blocks because there are no available threads. In fact, the pool is now empty which the executor mistakenly inteprets as all of them being in use. Doug Lea says he isn't going to fix. In fact, the version in j2se 1.5 doesn't have this option. In order for this to work, the min pool size must be > 0. @author Scott.Stark@jboss.org @author adrian@jboss.org @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class MinPooledExecutor extends ThreadPoolExecutor { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- /** The number of threads to keep alive threads */ protected int keepAliveSize; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Construct a new executor * * @param poolSize the maximum pool size */ public MinPooledExecutor(int poolSize) { super(poolSize, 2*poolSize, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(1024)); } /** * Construct a new executor * * @param queue the queue for any requests * @param poolSize the maximum pool size */ public MinPooledExecutor(BlockingQueue queue, int poolSize) { super(poolSize, 2*poolSize, 60, TimeUnit.SECONDS, queue); } // Public -------------------------------------------------------- /** * @return the number of threads to keep alive */ public int getKeepAliveSize() { return keepAliveSize; } /** * @param keepAliveSize the number of threads to keep alive */ public void setKeepAliveSize(int keepAliveSize) { this.keepAliveSize = keepAliveSize; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicThreadPoolMBean.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BasicThrea0000644000175000017500000001063710772776222033264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import org.jboss.util.loading.ClassLoaderSource; /** * Management interface for the thread pool. * * @author Adrian Brock * @version $Revision: 2761 $ */ public interface BasicThreadPoolMBean extends ThreadPoolMBean { // Constants ----------------------------------------------------- // Public -------------------------------------------------------- /** * Get the current queue size * * @return the queue size */ int getQueueSize(); /** * Get the maximum queue size * * @return the maximum queue size */ int getMaximumQueueSize(); /** * Set the maximum queue size * * @param size the new maximum queue size */ void setMaximumQueueSize(int size); /** * @return the blocking mode */ BlockingMode getBlockingMode(); /** Set the behavior of the pool when a task is added and the queue is full. * The mode string indicates one of the following modes: * abort - a RuntimeException is thrown * run - the calling thread executes the task * wait - the calling thread blocks until the queue has room * discard - the task is silently discarded without being run * discardOldest - check to see if a task is about to complete and enque * the new task if possible, else run the task in the calling thread * * @param mode one of run, wait, discard, discardOldest or abort without * regard to case. */ void setBlockingMode(BlockingMode mode); /** * Retrieve the thread group name * * @return the thread group name */ String getThreadGroupName(); /** * Set the thread group name * * @param threadGroupName - the thread group name */ void setThreadGroupName(String threadGroupName); /** * Get the keep alive time * * @return the keep alive time */ long getKeepAliveTime(); /** * Set the keep alive time * * @param time the keep alive time */ void setKeepAliveTime(long time); /** * Gets the source of the classloader that will be set as the * {@link Thread#getContextClassLoader() thread context classloader} * for pool threads. * * @return the {@link ClassLoaderSource}. May return null. */ ClassLoaderSource getClassLoaderSource(); /** * Sets the source of the classloader that will be set as the * {@link Thread#getContextClassLoader() thread context classloader} * for pool threads. If set, whenever any new pool thread is created, it's * context classloader will be set to the loader provided by this source. * Further, when any thread is returned to the pool, its context classloader * will be reset to the loader provided by this source. *

* If set to null (the default), the pool will not attempt to * manage the context classloader for pool threads; instead a newly created * pool thread will inherit its context classloader from whatever thread * triggered the addition to the pool. A thread returned to the pool will * not have its context classloader changed from whatever it was. *

* * @param classLoaderSource the {@link ClassLoaderSource}. May be null. */ void setClassLoaderSource(ClassLoaderSource classLoaderSource); // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/RunnableTaskWrapper.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/RunnableTa0000644000175000017500000001037611045571710033277 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import org.jboss.logging.Logger; /** * Makes a runnable a task. * * @author Adrian Brock * @version $Revision: 2892 $ */ public class RunnableTaskWrapper implements TaskWrapper { // Constants ----------------------------------------------------- /** The log */ private static final Logger log = Logger.getLogger(RunnableTaskWrapper.class); // Attributes ---------------------------------------------------- /** The runnable */ private Runnable runnable; private boolean started; private Thread runThread; /** The start timeout */ private long startTimeout; /** The completion timeout */ private long completionTimeout; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new RunnableTaskWrapper * * @param runnable the runnable * @throws IllegalArgumentException for a null runnable */ public RunnableTaskWrapper(Runnable runnable) { this(runnable, 0, 0); } public RunnableTaskWrapper(Runnable runnable, long startTimeout, long completeTimeout) { if (runnable == null) throw new IllegalArgumentException("Null runnable"); this.runnable = runnable; this.startTimeout = startTimeout; this.completionTimeout = completeTimeout; } // Public -------------------------------------------------------- // TaskWrapper implementation --------------------------------------- public int getTaskWaitType() { return Task.WAIT_NONE; } public int getTaskPriority() { return Thread.NORM_PRIORITY; } public long getTaskStartTimeout() { return startTimeout; } public long getTaskCompletionTimeout() { return completionTimeout; } public void acceptTask() { // Nothing to do } public void rejectTask(RuntimeException t) { throw t; } public void stopTask() { boolean trace = log.isTraceEnabled(); // Interrupt the run thread if its not null if( runThread != null && runThread.isInterrupted() == false ) { runThread.interrupt(); if( trace ) log.trace("stopTask, interrupted thread="+runThread); } else if( runThread != null ) { /* If the thread has not been returned after being interrupted, then use the deprecated stop method to try to force the thread abort. */ runThread.stop(); if( trace ) log.trace("stopTask, stopped thread="+runThread); } } public void waitForTask() { // Nothing to do } public boolean isComplete() { return started == true && runThread == null; } public void run() { boolean trace = log.isTraceEnabled(); try { if( trace ) log.trace("Begin run, wrapper="+this); runThread = Thread.currentThread(); started = true; runnable.run(); runThread = null; if( trace ) log.trace("End run, wrapper="+this); } catch (Throwable t) { log.warn("Unhandled throwable for runnable: " + runnable, t); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BlockingMode.javalibjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/threadpool/BlockingMo0000644000175000017500000001121710470642610033262 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util.threadpool; import java.io.Serializable; import java.io.ObjectStreamException; /** A type-safe enum for the BasicThreadPool blocking mode. * * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class BlockingMode implements Serializable { /** @since 1.0 */ private static final long serialVersionUID = -9102277941374138830L; public static final int RUN_TYPE = 0; public static final int WAIT_TYPE = 1; public static final int DISCARD_TYPE = 2; public static final int DISCARD_OLDEST_TYPE = 3; public static final int ABORT_TYPE = 4; /** Set the policy for blocked execution to be that the current thread executes the command if there are no available threads in the pool. */ public static final BlockingMode RUN = new BlockingMode("run", RUN_TYPE); /** Set the policy for blocked execution to be to wait until a thread * is available, unless the pool has been shut down, in which case * the action is discarded. */ public static final BlockingMode WAIT = new BlockingMode("wait", WAIT_TYPE); /** Set the policy for blocked execution to be to return without * executing the request. */ public static final BlockingMode DISCARD = new BlockingMode("discard", DISCARD_TYPE); /** Set the policy for blocked execution to be to discard the oldest * unhandled request */ public static final BlockingMode DISCARD_OLDEST = new BlockingMode("discardOldest", DISCARD_OLDEST_TYPE); /** Set the policy for blocked execution to be to throw an AbortWhenBlocked * (a subclass of RuntimeException). */ public static final BlockingMode ABORT = new BlockingMode("abort", ABORT_TYPE); /** The string form of the enum */ private final transient String name; /** The enum manifest constant */ private final int type; /** A utility method to convert a string name to a BlockingMode * @param name * @return The associated BlockingMode constant if name is valid, null otherwise */ public static final BlockingMode toBlockingMode(String name) { BlockingMode mode = null; if( name == null ) { mode = null; } else if( name.equalsIgnoreCase("run") ) { mode = RUN; } else if( name.equalsIgnoreCase("wait") ) { mode = WAIT; } else if( name.equalsIgnoreCase("discard") ) { mode = DISCARD; } else if( name.equalsIgnoreCase("discardOldest") ) { mode = DISCARD_OLDEST; } else if( name.equalsIgnoreCase("abort") ) { mode = ABORT; } return mode; } private BlockingMode(String name, int type) { this.name = name; this.type = type; } public String toString() { return name; } /** * Overriden to return the indentity instance of BlockingMode based on the * stream type int value. This ensures that BlockingMode enums can be * compared using ==. * * @return The BlockingMode instance for the XXX_TYPE int. * @throws ObjectStreamException */ Object readResolve() throws ObjectStreamException { // Replace the marshalled instance type with the local instance BlockingMode mode = ABORT; switch( type ) { case RUN_TYPE: mode = RUN; break; case WAIT_TYPE: mode = RUN; break; case DISCARD_TYPE: mode = RUN; break; case DISCARD_OLDEST_TYPE: mode = RUN; break; case ABORT_TYPE: mode = RUN; break; } return mode; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/WorkerQueue.java0000644000175000017500000001730010774222622032276 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Class that queues {@link Executable} jobs that are executed sequentially * by a single thread. * * @see Executable * * @author Simone Bordet * @version $Revision: 2787 $ */ public class WorkerQueue { /** The thread that runs the Executable jobs */ protected Thread m_queueThread; /** The job that will be executed by the worker thread */ private JobItem m_currentJob; /** * Creates a new worker queue with default thread name of "Worker Thread" */ public WorkerQueue() { this("Worker Thread"); } /** * Creates a new worker queue with the specified thread name * @param threadName */ public WorkerQueue(String threadName) { m_queueThread = new Thread(createQueueLoop(), threadName); } /** * Creates a new worker queue with the specified thread name * and daemon mode flag * @param threadName * @param isDaemon */ public WorkerQueue(String threadName, boolean isDaemon) { m_queueThread = new Thread(createQueueLoop(), threadName); m_queueThread.setDaemon(isDaemon); } /** * Starts the worker queue. * @see #stop */ public void start() { if (m_queueThread != null) {m_queueThread.start();} } /** * Stops nicely the worker queue.
* After this call trying to put a new job will result in a * InterruptedException to be thrown. The jobs queued before and not * yet processed are processed until the queue is empty, then this * worker queue is cleared. * @see #clear * @see #start * @see #isInterrupted */ public synchronized void stop() { if (m_queueThread != null) {m_queueThread.interrupt();} } /** * Called by a thread that is not the WorkerQueue thread, this method * queues the job and, if necessary, wakes up this worker queue that is * waiting in {@link #getJob}. * @param job */ public synchronized void putJob(Executable job) { // Preconditions if (m_queueThread == null || !m_queueThread.isAlive()) { throw new IllegalStateException("Can't put job, thread is not alive or not present"); } if (isInterrupted()) { throw new IllegalStateException("Can't put job, thread was interrupted"); } putJobImpl(job); } /** * @return whether the worker thread has been interrupted.
* When this method returns true, it is not possible to put new jobs in the * queue and the already present jobs are executed and removed from the * queue, then the thread exits. * * @see #stop */ protected boolean isInterrupted() { return m_queueThread.isInterrupted(); } /** * Called by this class, this method checks if the queue is empty; * if it is, then waits, else returns the current job. * * @see #putJob * @return the executable * @throws InterruptedException */ protected synchronized Executable getJob() throws InterruptedException { // Preconditions if (m_queueThread == null || !m_queueThread.isAlive()) { throw new IllegalStateException(); } return getJobImpl(); } /** * Never call this method, only override in subclasses to perform * job getting in a specific way, normally tied to the data structure * holding the jobs. * @return the exectuable * @throws InterruptedException */ protected Executable getJobImpl() throws InterruptedException { // While the queue is empty, wait(); // when notified take an event from the queue and return it. while (m_currentJob == null) {wait();} // This one is the job to return JobItem item = m_currentJob; // Go on to the next object for the next call. m_currentJob = m_currentJob.m_next; return item.m_job; } /** * Never call this method, only override in subclasses to perform * job adding in a specific way, normally tied to the data structure * holding the jobs. * @param job */ protected void putJobImpl(Executable job) { JobItem posted = new JobItem(job); if (m_currentJob == null) { // The queue is empty, set the current job to process and // wake up the thread waiting in method getJob m_currentJob = posted; notifyAll(); } else { JobItem item = m_currentJob; // The queue is not empty, find the end of the queue ad add the // posted job at the end while (item.m_next != null) {item = item.m_next;} item.m_next = posted; } } /** * Clears the running thread after the queue has been stopped.
* After this call, this worker queue is unusable and can be garbaged. */ protected void clear() { m_queueThread = null; m_currentJob = null; } /** * Creates the loop that will get the next job and process it.
* Override in subclasses to create a custom loop. * @return the runnable */ protected Runnable createQueueLoop() { return new QueueLoop(); } /** * Class that loops getting the next job to be executed and then * executing it, in the worker thread. */ protected class QueueLoop implements Runnable { public void run() { try { while (true) { try { if (isInterrupted()) { flush(); break; } else { getJob().execute(); } } catch (InterruptedException e) { try { flush(); } catch (Exception ignored) {} break; } catch (Exception e) { ThrowableHandler.add(ThrowableHandler.Type.ERROR, e); } } } finally { clear(); } } protected void flush() throws Exception { // Empty the queue of the posted jobs and exit while (m_currentJob != null) { m_currentJob.m_job.execute(); m_currentJob = m_currentJob.m_next; } } } /** * Simple linked cell, that has only a reference to the next job. */ private class JobItem { private Executable m_job; private JobItem m_next; private JobItem(Executable job) {m_job = job;} } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/HashCode.java0000644000175000017500000002233710776226110031502 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; /** * A hash-code generator and a collection of static hash-code generation * methods. * * @version $Revision: 2800 $ * @author Jason Dillon */ @SuppressWarnings("unchecked") public final class HashCode implements Serializable, Cloneable, Comparable { /** The serialVersionUID */ private static final long serialVersionUID = 2391396931740264021L; /** Hashcode for a 'null' value. */ private static final int NULL_HASHCODE = 0; /** Hashcode for a 'true' boolean */ private static final int TRUE_HASHCODE = 1231; // completely arbitrary /** Hashcode for a 'false' boolean */ private static final int FALSE_HASHCODE = 1237; // completely arbitrary /** The hash-code value. */ private int value; /** * Construct a new HashCode using the given int as the * base value. * * @param value int to use as the base value. */ public HashCode(final int value) { this.value = value; } /** * Construct a new HashCode. */ public HashCode() { this(0); } /** * Add the hash-code of the given value. * * @param b Value to get hash-code from. * @return This HashCode. */ public HashCode add(final boolean b) { value ^= generate(b); return this; } /** * Add the hash-code of the given value. * * @param n Value to get hash-code from. * @return This HashCode. */ public HashCode add(final byte n) { value ^= n; return this; } /** * Add the hash-code of the given value. * * @param n Value to get hash-code from. * @return This HashCode. */ public HashCode add(final char n) { value ^= n; return this; } /** * Add the hash-code of the given value. * * @param n Value to get hash-code from. * @return This HashCode. */ public HashCode add(final short n) { value ^= n; return this; } /** * Add the hash-code of the given value. * * @param n Value to get hash-code from. * @return This HashCode. */ public HashCode add(final int n) { value ^= n; return this; } /** * Add the hash-code of the given value. * * @param n Value to get hash-code from. * @return This HashCode. */ public HashCode add(final long n) { value ^= generate(n); return this; } /** * Add the hash-code of the given value. * * @param f Value to get hash-code from. * @return This HashCode. */ public HashCode add(final float f) { value ^= generate(f); return this; } /** * Add the hash-code of the given value. * * @param f Value to get hash-code from. * @return This HashCode. */ public HashCode add(final double f) { value ^= generate(f); return this; } /** * Add the hash-code of the given object. * * @param obj Value to get hash-code from. * @return This HashCode. */ public HashCode add(final Object obj) { value ^= generate(obj); return this; } /** * Get the hash-code. * * @return Hash-code. */ public int hashCode() { return value; } /** * Compares this object with the specified int for order. * * @param other Value to compare with. * @return A negative integer, zero, or a positive integer as * this object is less than, equal to, or greater than * the specified object. */ public int compareTo(final int other) { return (value < other) ? -1 : (value == other) ? 0 : 1; } /** * Compares this object with the specified object for order. * * @param obj Value to compare with. * @return A negative integer, zero, or a positive integer as * this object is less than, equal to, or greater than * the specified object. * * @throws ClassCastException Object is not a HashCode. */ public int compareTo(final Object obj) throws ClassCastException { HashCode hashCode = (HashCode)obj; return compareTo(hashCode.value); } /** * Test the equality of this HashCode and another object. * * @param obj Object to test equality with. * @return True if object is equal. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { return value == ((HashCode)obj).value; } return false; } /** * Return a string representation of this HashCode. * * @return A string representation of this HashCode. */ public String toString() { return String.valueOf(value); } /** * Return a cloned copy of this HashCode. * * @return Cloned HashCode. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ///////////////////////////////////////////////////////////////////////// // Generation Methods // ///////////////////////////////////////////////////////////////////////// /** * Generate a hash code for a boolean value. * * @param value Boolean value to generate hash code from. * @return Hash code. */ public static int generate(final boolean value) { return value ? TRUE_HASHCODE : FALSE_HASHCODE; } /** * Generate a hash code for a long value. * * @param value Long value to generate hash code from. * @return Hash code. */ public static int generate(final long value) { return (int)(value ^ (value >> 32)); } /** * Generate a hash code for a double value. * * @param value Double value to generate hash code from. * @return Hash code. */ public static int generate(final double value) { return generate(Double.doubleToLongBits(value)); } /** * Generate a hash code for a float value. * * @param value Float value to generate hash code from. * @return Hash code. */ public static int generate(final float value) { return Float.floatToIntBits(value); } /** * Generate a hash code for a byte array. * * @param bytes An array of bytes to generate a hash code from. * @return Hash code. */ public static int generate(final byte[] bytes) { int hashcode = 0; for (int i=0; iDoes not handle nested primitive array elements. * * @param array Array to generate hashcode for. * @param deep True to traverse elements which are arrays to * determine the elements hash code. * @return Hash code. */ public static int generate(final Object array[], final boolean deep) { int hashcode = 0; for (int i=0; iAles Justin */ public interface CharacterChecker { public CharacterChecker WHITESPACE = new WhitespaceChecker(); /** * Is character legal. * * @param character the char parameter * @return true if legal, false otherwise */ boolean isCharacterLegal(char character); class WhitespaceChecker implements CharacterChecker { public boolean isCharacterLegal(char character) { return Character.isWhitespace(character); } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/PrettyString.java0000644000175000017500000000402110470642610032466 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * A simple interface for objects that can return pretty (ie. * prefixed) string representations of themselves. * * @version $Revision: 1958 $ * @author Jason Dillon */ public interface PrettyString { /** * Returns a pretty representation of the object. * * @param prefix The string which all lines of the output must be prefixed with. * @return A pretty representation of the object. */ String toPrettyString(String prefix); /** * Interface for appending the objects pretty string onto a buffer. */ interface Appendable { /** * Appends a pretty representation of the object to the given buffer. * * @param buff The buffer to use while making pretty. * @param prefix The string which all lines of the output must be prefixed with. * @return The buffer. */ StringBuffer appendPrettyString(StringBuffer buff, String prefix); } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Counter.java0000644000175000017500000001535410776226110031444 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.Serializable; /** * An integer counter class. * * @version $Revision: 2800 $ * @author Jason Dillon */ public class Counter implements Serializable, Cloneable { /** The serialVersionUID */ private static final long serialVersionUID = 7736259185393081556L; /** The current count */ private int count; /** * Construct a Counter with a starting value. * * @param count Starting value for counter. */ public Counter(final int count) { this.count = count; } /** * Construct a Counter. */ public Counter() {} /** * Increment the counter. (Optional operation) * * @return The incremented value of the counter. */ public int increment() { return ++count; } /** * Decrement the counter. (Optional operation) * * @return The decremented value of the counter. */ public int decrement() { return --count; } /** * Return the current value of the counter. * * @return The current value of the counter. */ public int getCount() { return count; } /** * Reset the counter to zero. (Optional operation) */ public void reset() { this.count = 0; } /** * Check if the given object is equal to this. * * @param obj Object to test equality with. * @return True if object is equal to this. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { return ((Counter)obj).count == count; } return false; } /** * Return a string representation of this. * * @return A string representation of this. */ public String toString() { return String.valueOf(count); } /** * Return a cloned copy of this object. * * @return A cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ///////////////////////////////////////////////////////////////////////// // Wrappers // ///////////////////////////////////////////////////////////////////////// /** * Base wrapper class for other wrappers. */ private static class Wrapper extends Counter { /** The serialVersionUID */ private static final long serialVersionUID = -1803971437884946242L; /** The wrapped counter */ protected final Counter counter; public Wrapper(final Counter counter) { this.counter = counter; } public int increment() { return counter.increment(); } public int decrement() { return counter.decrement(); } public int getCount() { return counter.getCount(); } public void reset() { counter.reset(); } public boolean equals(final Object obj) { return counter.equals(obj); } public String toString() { return counter.toString(); } public Object clone() { return counter.clone(); } } /** * Return a synchronized counter. * * @param counter Counter to synchronize. * @return Synchronized counter. */ public static Counter makeSynchronized(final Counter counter) { return new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -6024309396861726945L; public synchronized int increment() { return this.counter.increment(); } public synchronized int decrement() { return this.counter.decrement(); } public synchronized int getCount() { return this.counter.getCount(); } public synchronized void reset() { this.counter.reset(); } public synchronized int hashCode() { return this.counter.hashCode(); } public synchronized boolean equals(final Object obj) { return this.counter.equals(obj); } public synchronized String toString() { return this.counter.toString(); } public synchronized Object clone() { return this.counter.clone(); } }; } /** * Returns a directional counter. * * @param counter Counter to make directional. * @param increasing True to create an increasing only * or false to create a decreasing only. * @return A directional counter. */ public static Counter makeDirectional(final Counter counter, final boolean increasing) { Counter temp; if (increasing) { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 2161377898611431781L; public int decrement() { throw new UnsupportedOperationException(); } public void reset() { throw new UnsupportedOperationException(); } }; } else { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -4683457706354663230L; public int increment() { throw new UnsupportedOperationException(); } }; } return temp; } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/TimerQueue.java0000644000175000017500000001466110774222622032114 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * This class runs in a single thread {@link TimerTask}s that have been * scheduled.

* A similar class is present in java.util package of jdk version >= 1.3; * for compatibility with jdk 1.2 it is reimplemented here. * * @see TimerTask * @author Simone Bordet * @version $Revision: 2787 $ */ public class TimerQueue extends WorkerQueue { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- /* This member is accessed only from putJob and getJob, that will then guarantee necessary synchronization on it */ private Heap m_heap; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Creates a new timer queue with default thread name of "TimerTask Thread" */ public TimerQueue() { this("TimerTask Thread"); } /** * Creates a new timer queue with the specified thread name * @param threadName */ public TimerQueue(String threadName) { super(threadName); m_heap = new Heap(); } // Public -------------------------------------------------------- /** * Schedules the given TimerTask for immediate execution. * @param t */ public void schedule(TimerTask t) { schedule(t, 0); } /** * Schedule the given TimerTask to be executed after delay * milliseconds. * @param t * @param delay */ public void schedule(TimerTask t, long delay) { if (t == null) throw new IllegalArgumentException("Can't schedule a null TimerTask"); if (delay < 0) delay = 0; t.setNextExecutionTime(System.currentTimeMillis() + delay); putJob(t); } // Z implementation ---------------------------------------------- // WorkerQueue overrides --------------------------------------------------- protected void putJobImpl(Executable task) { m_heap.insert(task); ((TimerTask)task).setState(TimerTask.SCHEDULED); notifyAll(); } protected Executable getJobImpl() throws InterruptedException { while (m_heap.peek() == null) { wait(); } TimerTask task = (TimerTask)m_heap.extract(); switch (task.getState()) { case TimerTask.CANCELLED: case TimerTask.EXECUTED: //don't hold onto last dead task if we wait. task = null; return getJobImpl(); case TimerTask.NEW: case TimerTask.SCHEDULED: return task; default: throw new IllegalStateException("TimerTask has an illegal state"); } } protected Runnable createQueueLoop() { return new TimerTaskLoop(); } protected void clear() { super.clear(); synchronized (this) { m_heap.clear(); } } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- /** * Class that loops getting the next job to be executed and then * executing it, in the timer task thread. */ protected class TimerTaskLoop implements Runnable { public void run() { try { while (true) { try { // Wait for the first job TimerTask task = (TimerTask)getJob(); long now = System.currentTimeMillis(); long executionTime = task.getNextExecutionTime(); long timeToWait = executionTime - now; boolean runTask = timeToWait <= 0; if (!runTask) { // Entering here when a new job is scheduled but // it's not yet time to run the first one; // the job was extracted from the heap, reschedule putJob(task); Object mutex = TimerQueue.this; synchronized (mutex) { // timeToWait is always strictly > 0, so I don't wait forever mutex.wait(timeToWait); } } else { if (task.isPeriodic()) { // Reschedule with the new time task.setNextExecutionTime(executionTime + task.getPeriod()); putJob(task); } else { // The one-shot task is already removed from // the heap, mark it as executed task.setState(TimerTask.EXECUTED); } // Run it ! task.execute(); } } catch (InterruptedException x) { // Exit the thread break; } catch (Exception e) { ThrowableHandler.add(ThrowableHandler.Type.ERROR, e); } } } finally {clear();} } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Semaphore.java0000644000175000017500000001561110774222622031746 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.io.StringWriter; import java.io.PrintWriter; /** * Semaphore that can allow a specified number of threads to enter, blocking the * others. If the specified number of threads is 1, it acts as an exclusive semaphore * and can be used instead of synchronized blocks * * @author Simone Bordet * @version $Revision: 2787 $ */ @SuppressWarnings("unchecked") public class Semaphore implements Sync { // Constants ----------------------------------------------------- private static final long DEADLOCK_TIMEOUT = 5*60*1000; // Attributes ---------------------------------------------------- private final static boolean m_debug = false; private int m_users; private int m_allowed; private Map m_logMap; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public Semaphore(int allowed) { if (allowed < 1) throw new IllegalArgumentException(); m_users = 0; m_allowed = allowed; m_logMap = new HashMap(); } // Public -------------------------------------------------------- public int getUsers() { synchronized (this) { return m_users; } } // Sync implementation ---------------------------------------------- public void acquire() throws InterruptedException { synchronized (this) { logAcquire(); // One user more called acquire, increase users ++m_users; boolean waitSuccessful = false; while (m_allowed <= 0) { waitSuccessful = waitImpl(this); if (!waitSuccessful) { // Dealock was detected, restore status, 'cause it's like a release() // that will probably be never called --m_users; ++m_allowed; } } --m_allowed; } } public void release() { synchronized (this) { logRelease(); --m_users; ++m_allowed; notify(); } } // Object overrides --------------------------------------------------- public String toString() { return super.toString() + " - " + m_users; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- protected boolean waitImpl(Object lock) throws InterruptedException { // Wait (forever) until notified. To discover deadlocks, // turn on debugging of this class long start = System.currentTimeMillis(); lock.wait(DEADLOCK_TIMEOUT); long end = System.currentTimeMillis(); if ((end - start) > (DEADLOCK_TIMEOUT - 1000)) { logDeadlock(); return false; } return true; } protected void logAcquire() { if (m_debug) { // Check if thread is already mapped Thread thread = Thread.currentThread(); // Create stack trace StringWriter sw = new StringWriter(); new Exception().printStackTrace(new PrintWriter(sw)); String trace = sw.toString(); LinkedList list = (LinkedList)m_logMap.get(thread); if (list != null) { // Thread is mapped // Add info Info prevInfo = (Info)list.getLast(); Info info = new Info(thread, m_users, trace); list.add(info); } else { // Thread is not mapped, create list and add counter list = new LinkedList(); Info info = new Info(thread, m_users, trace); list.add(info); // Map thread m_logMap.put(thread, list); } } } protected void logDeadlock() { System.err.println(); System.err.println("DEADLOCK ON SEMAPHORE " + this); if (m_debug) { for (Iterator i = m_logMap.values().iterator(); i.hasNext();) { LinkedList list = (LinkedList)i.next(); for (Iterator iter = list.iterator(); iter.hasNext();) { System.err.println(iter.next()); } } } System.err.println(); } protected void logRelease() { if (m_debug) { // Find a matching thread and remove info for it Thread thread = Thread.currentThread(); LinkedList list = (LinkedList)m_logMap.get(thread); if (list != null) { Info info = new Info(thread, 0, ""); if (!list.remove(info)) { System.err.println("LOG INFO SIZE: " + list); new IllegalStateException("BUG: semaphore log list does not contain required info").printStackTrace(); } // If no info left, remove the mapping int size = list.size(); if (size < 1) { m_logMap.remove(thread); } } else { throw new IllegalStateException("Semaphore log failed: release called without acquire"); } } } // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- private class Info { private Info(Thread t, int i, String s) { m_thread = t; m_counter = i; m_trace = s; } private Thread m_thread; private int m_counter; private String m_trace; public boolean equals(Object o) { Info other = (Info)o; return m_thread == other.m_thread; } public String toString() { return m_thread + " - " + m_counter + "\n" + m_trace; } } } libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Base64.java0000644000175000017500000014060110774222622031045 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; import java.io.IOException; import org.jboss.logging.Logger; /** * Encodes and decodes to and from Base64 notation. * *

* Change Log: *

*
    *
  • v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.
  • *
  • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).
  • *
  • v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.
  • *
  • v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (ints that you "OR" together).
  • *
  • v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using decode( String s, boolean gzipCompressed ). * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).
  • *
  • v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.
  • *
  • v1.4 - Added helper methods to read/write files.
  • *
  • v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
  • *
  • v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.
  • *
  • v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.
  • *
  • v1.3.3 - Fixed I/O streams which were totally messed up.
  • *
* *

* I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit http://iharder.net/base64 * periodically to check for updates or to contribute improvements. *

* * @author Robert Harder * @author rob@iharder.net * @version 2.1 */ public class Base64 { // provide logging private static final Logger log = Logger.getLogger(Base64.class); /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array threeBytes * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by numSigBytes. * The array threeBytes needs only be as big as * numSigBytes. * Code can reuse a byte array by passing a four-byte array as b4. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes) { encode3to4(threeBytes, 0, numSigBytes, b4, 0); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array source * and writes the resulting four Base64 bytes to destination. * The source and destination arrays can be manipulated * anywhere along their length by specifying * srcOffset and destOffset. * This method does not check to make sure your arrays * are large enough to accomodate srcOffset + 3 for * the source array or destOffset + 4 for * the destination array. * The actual number of significant bytes in your array is * given by numSigBytes. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the destination array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return null. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject(java.io.Serializable serializableObject) { return encodeObject(serializableObject, NO_OPTIONS); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return null. *

* Valid options:

    *   GZIP: gzip-compresses object before encoding it.
    *   DONT_BREAK_LINES: don't break lines at 76 characters
    *     Note: Technically, this makes your encoding non-compliant.
    * 
*

* Example: encodeObject( myObj, Base64.GZIP ) or *

* Example: encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES ) * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject(java.io.Serializable serializableObject, int options) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines); // GZip? if (gzip == GZIP) { gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream(gzos); } // end if: gzip else oos = new java.io.ObjectOutputStream(b64os); oos.writeObject(serializableObject); } // end try catch (java.io.IOException e) { e.printStackTrace(); return null; } // end catch finally { try { oos.close(); } catch (Exception e) { } try { gzos.close(); } catch (Exception e) { } try { b64os.close(); } catch (Exception e) { } try { baos.close(); } catch (Exception e) { } } // end finally // Return value according to relevant encoding. try { return new String(baos.toByteArray(), PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String(baos.toByteArray()); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return the encode bytes * @since 1.4 */ public static String encodeBytes(byte[] source) { return encodeBytes(source, 0, source.length, NO_OPTIONS); } // end encodeBytes /** * Encodes a byte array into Base64 notation. *

* Valid options:

    *   GZIP: gzip-compresses object before encoding it.
    *   DONT_BREAK_LINES: don't break lines at 76 characters
    *     Note: Technically, this makes your encoding non-compliant.
    * 
*

* Example: encodeBytes( myData, Base64.GZIP ) or *

* Example: encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) * * * @param source The data to convert * @param options Specified options * @return the encoded bytes * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes(byte[] source, int options) { return encodeBytes(source, 0, source.length, options); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return the text node * @since 1.4 */ public static String encodeBytes(byte[] source, int off, int len) { return encodeBytes(source, off, len, NO_OPTIONS); } // end encodeBytes /** * Encodes a byte array into Base64 notation. *

* Valid options:

    *   GZIP: gzip-compresses object before encoding it.
    *   DONT_BREAK_LINES: don't break lines at 76 characters
    *     Note: Technically, this makes your encoding non-compliant.
    * 
*

* Example: encodeBytes( myData, Base64.GZIP ) or *

* Example: encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @return the text node * @since 2.0 */ public static String encodeBytes(byte[] source, int off, int len, int options) { // Isolate options int dontBreakLines = (options & DONT_BREAK_LINES); int gzip = (options & GZIP); // Compress? if (gzip == GZIP) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines); gzos = new java.util.zip.GZIPOutputStream(b64os); gzos.write(source, off, len); gzos.close(); } // end try catch (java.io.IOException e) { e.printStackTrace(); return null; } // end catch finally { try { gzos.close(); } catch (Exception e) { } try { b64os.close(); } catch (Exception e) { } try { baos.close(); } catch (Exception e) { } } // end finally // Return value according to relevant encoding. try { return new String(baos.toByteArray(), PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String(baos.toByteArray()); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[(len43) // Main 4:3 + ((len % 3) > 0 ? 4 : 0) // Account for padding + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { encode3to4(source, d + off, 3, outBuff, e); lineLength += 4; if (breakLines && lineLength == MAX_LINE_LENGTH) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String(outBuff, 0, e, PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String(outBuff, 0, e); } // end catch } // end else: don't compress } // end encodeBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array source * and writes the resulting bytes (up to three of them) * to destination. * The source and destination arrays can be manipulated * anywhere along their length by specifying * srcOffset and destOffset. * This method does not check to make sure your arrays * are large enough to accomodate srcOffset + 4 for * the source array or destOffset + 3 for * the destination array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); destination[destOffset] = (byte)(outBuff >>> 16); return 1; } // Example: DkL= else if (source[srcOffset + 3] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); destination[destOffset] = (byte)(outBuff >>> 16); destination[destOffset + 1] = (byte)(outBuff >>> 8); return 2; } // Example: DkLE else { try { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF)); destination[destOffset] = (byte)(outBuff >> 16); destination[destOffset + 1] = (byte)(outBuff >> 8); destination[destOffset + 2] = (byte)(outBuff); return 3; } catch (Exception e) { log.error("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]])); log.error("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]])); log.error("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]])); log.error("" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]])); return -1; } //end catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode(byte[] source, int off, int len) { int len34 = len * 3 / 4; byte[] outBuff = new byte[len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = off; i < off + len; i++) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better { if (sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn++] = sbiCrop; if (b4Posn > 3) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if (sbiCrop == EQUALS_SIGN) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { throw new IllegalStateException("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); } // end else: } // each input character byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) { byte[] bytes; try { bytes = s.getBytes(PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uee) { bytes = s.getBytes(); } // end catch // // Decode bytes = decode(bytes, 0, bytes.length); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if (bytes != null && bytes.length >= 4) { int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch (java.io.IOException e) { // Just return originally-decoded bytes } // end catch finally { try { baos.close(); } catch (Exception e) { } try { gzis.close(); } catch (Exception e) { } try { bais.close(); } catch (Exception e) { } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns null if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject(String encodedObject) { // Decode and gunzip if necessary byte[] objBytes = decode(encodedObject); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream(objBytes); ois = new java.io.ObjectInputStream(bais); obj = ois.readObject(); } // end try catch (java.io.IOException e) { e.printStackTrace(); obj = null; } // end catch catch (java.lang.ClassNotFoundException e) { e.printStackTrace(); obj = null; } // end catch finally { try { bais.close(); } catch (Exception e) { } try { ois.close(); } catch (Exception e) { } } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return true if successful, false otherwise * * @since 2.1 */ public static boolean encodeToFile(byte[] dataToEncode, String filename) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); success = true; } // end try catch (java.io.IOException e) { success = false; } // end catch: IOException finally { try { bos.close(); } catch (Exception e) { } } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return true if successful, false otherwise * * @since 2.1 */ public static boolean decodeToFile(String dataToDecode, String filename) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.DECODE); bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); success = true; } // end try catch (java.io.IOException e) { success = false; } // end catch: IOException finally { try { bos.close(); } catch (Exception e) { } } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * * @since 2.1 */ public static byte[] decodeFromFile(String filename) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File(filename); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if (file.length() > Integer.MAX_VALUE) { throw new IllegalStateException("File is too big for this convenience method (" + file.length() + " bytes)."); } // end if: file too big for int index buffer = new byte[(int)file.length()]; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) length += numBytes; // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch (java.io.IOException e) { throw new IllegalStateException("Error decoding from file " + filename); } // end catch: IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * * @since 2.1 */ public static String encodeFromFile(String filename) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File(filename); byte[] buffer = new byte[(int)(file.length() * 1.4)]; int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.ENCODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) length += numBytes; // Save in a variable to return encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); } // end try catch (java.io.IOException e) { throw new IllegalStateException("Error encoding from file " + filename); } // end catch: IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return encodedData; } // end encodeFromFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * java.io.InputStream, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the java.io.InputStream from which to read data. * @since 1.3 */ public InputStream(java.io.InputStream in) { this(in, DECODE); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. *

* Valid options:

       *   ENCODE or DECODE: Encode or Decode as data is read.
       *   DONT_BREAK_LINES: don't break lines at 76 characters
       *     (only meaningful when encoding)
       *     Note: Technically, this makes your encoding non-compliant.
       * 
*

* Example: new Base64.InputStream( in, Base64.DECODE ) * * * @param in the java.io.InputStream from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream(java.io.InputStream in, int options) { super(in); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[bufferLength]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if (position < 0) { if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for (int i = 0; i < 3; i++) { try { int b = in.read(); // If end of stream, b is -1. if (b >= 0) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch (java.io.IOException e) { // Only a problem if we got no data at all. if (i == 0) throw e; } // end catch } // end for: each needed input byte if (numBinaryBytes > 0) { encode3to4(b3, 0, numBinaryBytes, buffer, 0); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; do { b = in.read(); } while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC); if (b < 0) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if (i == 4) { numSigBytes = decode4to3(b4, 0, buffer, 0); position = 0; } // end if: got four characters else if (i == 0) { return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException("Improperly padded Base64 input."); } // end } // end else: decode } // end else: get data // Got data? if (position >= 0) { // End of relevant data? if (/*!encode &&*/position >= numSigBytes) return -1; if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; if (position >= bufferLength) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException("Error in Base64 code reading stream."); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or len bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; for (i = 0; i < len; i++) { b = read(); //if( b < 0 && i == 0 ) // return -1; if (b >= 0) dest[off + i] = (byte)b; else if (i == 0) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * java.io.OutputStream, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the java.io.OutputStream to which data will be written. * @since 1.3 */ public OutputStream(java.io.OutputStream out) { this(out, ENCODE); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. *

* Valid options:

       *   ENCODE or DECODE: Encode or Decode as data is read.
       *   DONT_BREAK_LINES: don't break lines at 76 characters
       *     (only meaningful when encoding)
       *     Note: Technically, this makes your encoding non-compliant.
       * 
*

* Example: new Base64.OutputStream( out, Base64.ENCODE ) * * @param out the java.io.OutputStream to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream(java.io.OutputStream out, int options) { super(out); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[bufferLength]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theByte); return; } // end if: supsended // Encode? if (encode) { buffer[position++] = (byte)theByte; if (position >= bufferLength) // Enough to encode. { out.write(encode3to4(b4, buffer, bufferLength)); lineLength += 4; if (breakLines && lineLength >= MAX_LINE_LENGTH) { out.write(NEW_LINE); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) { buffer[position++] = (byte)theByte; if (position >= bufferLength) // Enough to output. { int len = Base64.decode4to3(buffer, 0, b4, 0); out.write(b4, 0, len); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) { throw new java.io.IOException("Invalid character in Base64 data."); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until len * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write(byte[] theBytes, int off, int len) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theBytes, off, len); return; } // end if: supsended for (int i = 0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws IOException */ public void flushBase64() throws java.io.IOException { if (position > 0) { if (encode) { out.write(encode3to4(b4, buffer, position)); position = 0; } // end if: encoding else { throw new java.io.IOException("Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 * @throws IOException */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 libjboss-common-java-0.0+svn2938.orig/common-core/src/main/java/org/jboss/util/Primitives.java0000644000175000017500000000754010470642610032154 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.util; /** * Primitive utilities. * * @version $Revision: 1958 $ * @author Jason Dillon */ public final class Primitives { /** * Get a Boolean from a boolean, equivalent to the java 1.4 method Boolean.valueOf(boolean) * * @param value the boolean * @return the Boolean equivalent */ public static Boolean valueOf(boolean value) { if (value) return Boolean.TRUE; else return Boolean.FALSE; } /** * Test the equality of two doubles by converting their values into * IEEE 754 floating-point "double format" long values. * * @param a Double to check equality with. * @param b Double to check equality with. * @return True if a equals b. */ public static boolean equals(final double a, final double b) { return Double.doubleToLongBits(a) == Double.doubleToLongBits(b); } /** * Test the equality of two doubles by converting their values into * IEEE 754 floating-point "single precision" bit layouts. * * @param a Float to check equality with. * @param b Float to check equality with. * @return True if a equals b. */ public static boolean equals(final float a, final float b) { return Float.floatToIntBits(a) == Float.floatToIntBits(b); } /** * Test the equality of a given sub-section of two byte arrays. * * @param a The first byte array. * @param abegin The begining index of the first byte array. * @param b The second byte array. * @param bbegin The begining index of the second byte array. * @param length The length of the sub-section. * @return True if sub-sections are equal. */ public static boolean equals(final byte a[], final int abegin, final byte b[], final int bbegin, final int length) { try { int i=length; while (--i >= 0) { if (a[abegin + i] != b[bbegin + i]) { return false; } } } catch (ArrayIndexOutOfBoundsException e) { return false; } return true; } /** * Test the equality of two byte arrays. * * @param a The first byte array. * @param b The second byte array. * @return True if the byte arrays are equal. */ public static boolean equals(final byte a[], final byte b[]) { if (a == b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; try { for (int i=0; iJason Dillon * @author Scott Stark * @author Claudio Vesco * @author Adrian Brock * @author Dimitris Andreadis * @version $Revision: 2898 $ */ public final class StringPropertyReplacer { /** New line string constant */ public static final String NEWLINE = SysPropertyActions.getProperty("line.separator", "\n"); /** File separator value */ private static final String FILE_SEPARATOR = File.separator; /** Path separator value */ private static final String PATH_SEPARATOR = File.pathSeparator; /** File separator alias */ private static final String FILE_SEPARATOR_ALIAS = "/"; /** Path separator alias */ private static final String PATH_SEPARATOR_ALIAS = ":"; // States used in property parsing private static final int NORMAL = 0; private static final int SEEN_DOLLAR = 1; private static final int IN_BRACKET = 2; /** * Go through the input string and replace any occurance of ${p} with * the System.getProperty(p) value. If there is no such property p defined, * then the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such property p, * then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then * the primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with System.getProperty("path.separator"). * * @param string - the string with possible ${} references * @return the input string with all property references replaced if any. * If there are no valid references the input string will be returned. */ public static String replaceProperties(final String string) { return replaceProperties(string, null); } /** * Go through the input string and replace any occurance of ${p} with * the props.getProperty(p) value. If there is no such property p defined, * then the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such property p, * then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then * the primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with System.getProperty("path.separator"). * * @param string - the string with possible ${} references * @param props - the source for ${x} property ref values, null means use System.getProperty() * @return the input string with all property references replaced if any. * If there are no valid references the input string will be returned. */ public static String replaceProperties(final String string, final Properties props) { final char[] chars = string.toCharArray(); StringBuffer buffer = new StringBuffer(); boolean properties = false; int state = NORMAL; int start = 0; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; // Dollar sign outside brackets if (c == '$' && state != IN_BRACKET) state = SEEN_DOLLAR; // Open bracket immediatley after dollar else if (c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state = IN_BRACKET; start = i - 1; } // No open bracket after dollar else if (state == SEEN_DOLLAR) state = NORMAL; // Closed bracket after open bracket else if (c == '}' && state == IN_BRACKET) { // No content if (start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else // Collect the system property { String value = null; String key = string.substring(start + 2, i); // check for alias if (FILE_SEPARATOR_ALIAS.equals(key)) { value = FILE_SEPARATOR; } else if (PATH_SEPARATOR_ALIAS.equals(key)) { value = PATH_SEPARATOR; } else { // check from the properties if (props != null) value = props.getProperty(key); else value = System.getProperty(key); if (value == null) { // Check for a default value ${key:default} int colon = key.indexOf(':'); if (colon > 0) { String realKey = key.substring(0, colon); if (props != null) value = props.getProperty(realKey); else value = System.getProperty(realKey); if (value == null) { // Check for a composite key, "key1,key2" value = resolveCompositeKey(realKey, props); // Not a composite key either, use the specified default if (value == null) value = key.substring(colon+1); } } else { // No default, check for a composite key, "key1,key2" value = resolveCompositeKey(key, props); } } } if (value != null) { properties = true; buffer.append(value); } else { buffer.append("${"); buffer.append(key); buffer.append('}'); } } start = i + 1; state = NORMAL; } } // No properties if (properties == false) return string; // Collect the trailing characters if (start != chars.length) buffer.append(string.substring(start, chars.length)); // Done return buffer.toString(); } /** * Try to resolve a "key" from the provided properties by * checking if it is actually a "key1,key2", in which case * try first "key1", then "key2". If all fails, return null. * * It also accepts "key1," and ",key2". * * @param key the key to resolve * @param props the properties to use * @return the resolved key or null */ private static String resolveCompositeKey(String key, Properties props) { String value = null; // Look for the comma int comma = key.indexOf(','); if (comma > -1) { // If we have a first part, try resolve it if (comma > 0) { // Check the first part String key1 = key.substring(0, comma); if (props != null) value = props.getProperty(key1); else value = System.getProperty(key1); } // Check the second part, if there is one and first lookup failed if (value == null && comma < key.length() - 1) { String key2 = key.substring(comma + 1); if (props != null) value = props.getProperty(key2); else value = System.getProperty(key2); } } // Return whatever we've found or null return value; } }libjboss-common-java-0.0+svn2938.orig/common-core/.classpath0000644000175000017500000000171211041662656023623 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-core/.project0000644000175000017500000000052610774161402023304 0ustar twernertwerner jboss-common-core JBoss Common Core Utility classes org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature libjboss-common-java-0.0+svn2938.orig/common-core/.settings/0000755000175000017500000000000011105642366023552 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-core/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000031410774162613030535 0ustar twernertwerner#Mon Mar 31 14:38:35 CEST 2008 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 libjboss-common-java-0.0+svn2938.orig/common-core/projectSet.psf0000644000175000017500000000035710475104443024473 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-core/pom.xml0000644000175000017500000000607611103573251023154 0ustar twernertwerner 4.0.0 org.jboss jboss-parent 4.0.CR1 org.jboss jboss-common-core jar 2.2.10-SNAPSHOT JBoss Common Classes http://www.jboss.org JBoss Common Core Utility classes scm:svn:http://anonsvn.jboss.org/repos/common/common-core/trunk/ scm:svn:https://svn.jboss.org/repos/common/common-core/trunk/ org.apache.maven.plugins maven-surefire-plugin 2.4.3 true false true **/*TestCase.java eclipse org.apache.maven.plugins maven-eclipse-plugin true target/eclipse-classes apache-httpclient commons-httpclient 2.0.2 compile true apache-slide webdavlib 2.0 compile true org.jboss.logging jboss-logging-spi 2.0.5.GA compile junit junit 4.4 test libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/0000755000175000017500000000000011105642371023074 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/0000755000175000017500000000000011105642371023663 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/0000755000175000017500000000000011105642370024606 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/0000755000175000017500000000000011105642370025527 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/0000755000175000017500000000000011105642370026316 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/0000755000175000017500000000000011105642370027436 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/0000755000175000017500000000000011105642371031065 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/0000755000175000017500000000000011105642371031635 5ustar twernertwerner././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handlers/libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handler0000755000175000017500000000000011105642371033173 5ustar twernertwerner././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handlers/HandlerSkeleton.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handler0000644000175000017500000000104510470642610033175 0ustar twernertwerner/* * Copyright (c) 2005 Your Corporation. All Rights Reserved. */ package org.jboss.logging.jdk.handlers; import java.util.logging.Handler; /** * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public abstract class HandlerSkeleton extends Handler { protected String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void activateOptions() { } protected void debug(String msg) { System.out.println(msg); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handlers/WriterHandler.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handler0000644000175000017500000001630310774202215033200 0ustar twernertwernerpackage org.jboss.logging.jdk.handlers; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.logging.ErrorManager; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * A base handler that outputs log messages to a Writer * * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class WriterHandler extends HandlerSkeleton { /** * Immediate flush means that the underlying writer or output stream * will be flushed at the end of each append operation. Immediate * flush is slower but ensures that each append request is actually * written. If immediateFlush is set to * false, then there is a good chance that the last few * logs events are not actually written to persistent media if and * when the application crashes. *

*

The immediateFlush variable is set to * true by default. */ protected boolean immediateFlush = true; /** * Do we do bufferedIO? */ protected boolean bufferedIO = false; /** * Determines the size of IO buffer be. Default is 8K. */ protected int bufferSize = 8 * 1024; private OutputStream msgOutput; private Writer msgWriter; /** * Has the */ private boolean wroteHeader; public WriterHandler() { super(); } public WriterHandler(OutputStream output, Formatter formatter) { setFormatter(formatter); setOutputStream(output); } /** * If the ImmediateFlush option is set to * true, the appender will flush at the end of each * write. This is the default behavior. If the option is set to * false, then the underlying stream can defer writing * to physical medium to a later time. *

*

Avoiding the flush operation at the end of each append results in * a performance gain of 10 to 20 percent. However, there is safety * tradeoff involved in skipping flushing. Indeed, when flushing is * skipped, then it is likely that the last few log events will not * be recorded on disk when the application exits. This is a high * price to pay even for a 20% performance gain. * @param value */ public void setImmediateFlush(boolean value) { immediateFlush = value; } /** * @return value of the ImmediateFlush option. */ public boolean getImmediateFlush() { return immediateFlush; } public boolean isBufferedIO() { return bufferedIO; } /** * The BufferedIO option takes a boolean value. It is set to * false by default. If true, then File * will be opened and the resulting {@link java.io.Writer} wrapped * around a {@link java.io.BufferedWriter}. *

* BufferedIO will significatnly increase performance on heavily * loaded systems. * @param bufferedIO */ public void setBufferedIO(boolean bufferedIO) { this.bufferedIO = bufferedIO; if (bufferedIO) { immediateFlush = false; } } public int getBufferSize() { return bufferSize; } /** * Set the size of the IO buffer. * @param bufferSize */ public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { super.setEncoding(encoding); if (msgOutput == null) { return; } // Replace the current writer with a writer for the new encoding. flush(); if (encoding == null) { msgWriter = new OutputStreamWriter(msgOutput); } else { msgWriter = new OutputStreamWriter(msgOutput, encoding); } } public synchronized void flush() { if (msgWriter != null) { try { msgWriter.flush(); } catch (IOException e) { reportError("Failed to flush writer", e, ErrorManager.FLUSH_FAILURE); } } } public synchronized void close() { if (msgWriter != null) { try { if (!wroteHeader) { msgWriter.write(getFormatter().getHead(this)); wroteHeader = true; } msgWriter.write(getFormatter().getTail(this)); msgWriter.flush(); msgWriter.close(); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.CLOSE_FAILURE); } msgWriter = null; msgOutput = null; } } public void publish(LogRecord record) { if(checkEntryConditions(record) == false) { return; } subPublish(record); } protected boolean checkEntryConditions(LogRecord record) { boolean canWrite = super.isLoggable(record); if( canWrite ) { canWrite = msgWriter != null; } return canWrite; } /** * Actual writing occurs here. * Most subclasses of WriterHandler will need to * override this method. * @param record */ protected void subPublish(LogRecord record) { Formatter fmt = getFormatter(); String msg = fmt.format(record); synchronized (this) { try { msgWriter.write(msg); } catch (IOException e) { reportError("Failed to publish recored", e, ErrorManager.WRITE_FAILURE); } if (this.immediateFlush) { flush(); } } } /** * Change the output stream. *

* If there is a current output stream then the Formatter's * tail string is written and the stream is flushed and closed. * Then the output stream is replaced with the new output stream. * * @param out New output stream. May not be null. * @throws SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ protected synchronized void setOutputStream(OutputStream out) { if (out == null) { throw new NullPointerException("The out argument cannot be null"); } close(); msgOutput = out; wroteHeader = false; String encoding = getEncoding(); if (encoding == null) { msgWriter = new OutputStreamWriter(msgOutput); } else { try { msgWriter = new OutputStreamWriter(msgOutput, encoding); } catch (UnsupportedEncodingException ex) { // This shouldn't happen. The setEncoding method // should have validated that the encoding is OK. throw new Error("Unexpected exception " + ex); } } if (bufferedIO) { msgWriter = new BufferedWriter(msgWriter, bufferSize); } } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handlers/DailyRollingFileHandler.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handler0000644000175000017500000003615410774202215033206 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.handlers; import java.util.Date; import java.util.TimeZone; import java.util.Locale; import java.util.GregorianCalendar; import java.util.Calendar; import java.util.logging.Formatter; import java.util.logging.ErrorManager; import java.util.logging.LogRecord; import java.text.SimpleDateFormat; import java.io.IOException; import java.io.File; /** DailyRollingFileAppender extends {@link FileHandler} so that the underlying file is rolled over at a user chosen frequency.

The rolling schedule is specified by the DatePattern option. This pattern should follow the {@link SimpleDateFormat} conventions. In particular, you must escape literal text within a pair of single quotes. A formatted version of the date pattern is used as the suffix for the rolled file name.

For example, if the File option is set to /foo/bar.log and the DatePattern set to '.'yyyy-MM-dd, on 2001-02-16 at midnight, the logging file /foo/bar.log will be copied to /foo/bar.log.2001-02-16 and logging for 2001-02-17 will continue in /foo/bar.log until it rolls over the next day.

Is is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules.

DatePattern Rollover schedule Example
'.'yyyy-MM Rollover at the beginning of each month At midnight of May 31st, 2002 /foo/bar.log will be copied to /foo/bar.log.2002-05. Logging for the month of June will be output to /foo/bar.log until it is also rolled over the next month.
'.'yyyy-ww Rollover at the first day of each week. The first day of the week depends on the locale. Assuming the first day of the week is Sunday, on Saturday midnight, June 9th 2002, the file /foo/bar.log will be copied to /foo/bar.log.2002-23. Logging for the 24th week of 2002 will be output to /foo/bar.log until it is rolled over the next week.
'.'yyyy-MM-dd Rollover at midnight each day. At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.
'.'yyyy-MM-dd-a Rollover at midnight and midday of each day. At noon, on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-AM. Logging for the afternoon of the 9th will be output to /foo/bar.log until it is rolled over at midnight.
'.'yyyy-MM-dd-HH Rollover at the top of every hour. At approximately 11:00.000 o'clock on March 9th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-09-10. Logging for the 11th hour of the 9th of March will be output to /foo/bar.log until it is rolled over at the beginning of the next hour.
'.'yyyy-MM-dd-HH-mm Rollover at the beginning of every minute. At approximately 11:23,000, on March 9th, 2001, /foo/bar.log will be copied to /foo/bar.log.2001-03-09-10-22. Logging for the minute of 11:23 (9th of March) will be output to /foo/bar.log until it is rolled over the next minute.

Do not use the colon ":" character in anywhere in the DatePattern option. The text before the colon is interpeted as the protocol specificaion of a URL which is probably not what you want. @author Eirik Lygre @author Ceki Gülcü @author Scott.Stark@jboss.org @version $Revision: 2786 $ */ public class DailyRollingFileHandler extends FileHandler { // The code assumes that the following constants are in a increasing // sequence. static final int TOP_OF_TROUBLE = -1; static final int TOP_OF_MINUTE = 0; static final int TOP_OF_HOUR = 1; static final int HALF_DAY = 2; static final int TOP_OF_DAY = 3; static final int TOP_OF_WEEK = 4; static final int TOP_OF_MONTH = 5; /** * The date pattern. By default, the pattern is set to * "'.'yyyy-MM-dd" meaning daily rollover. */ private String datePattern = "'.'yyyy-MM-dd"; /** * The log file will be renamed to the value of the * scheduledFilename variable when the next interval is entered. For * example, if the rollover period is one hour, the log file will be * renamed to the value of "scheduledFilename" at the beginning of * the next hour. *

* The precise time when a rollover occurs depends on logging * activity. */ private String scheduledFilename; /** * The next time we estimate a rollover should occur. */ private long nextCheck = System.currentTimeMillis() - 1; Date now = new Date(); SimpleDateFormat sdf; RollingCalendar rc = new RollingCalendar(); int checkPeriod = TOP_OF_TROUBLE; // The gmtTimeZone is used only in computeCheckPeriod() method. static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); /** * The default constructor does nothing. */ public DailyRollingFileHandler() { } /** * Instantiate a DailyRollingFileAppender and open the * file designated by filename. The opened filename will * become the ouput destination for this appender. * @param layout * @param filename * @param datePattern * @throws IOException */ public DailyRollingFileHandler(Formatter layout, String filename, String datePattern) throws IOException { super(layout, filename, true); this.datePattern = datePattern; activateOptions(); } /** * The DatePattern takes a string in the same format as * expected by {@link SimpleDateFormat}. This options determines the * rollover schedule. * @param pattern */ public void setDatePattern(String pattern) { datePattern = pattern; } /** * Returns the value of the DatePattern option. * @return the date pattern */ public String getDatePattern() { return datePattern; } public void activateOptions() { super.activateOptions(); if (datePattern != null && fileName != null) { now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); int type = computeCheckPeriod(); printPeriodicity(type); rc.setType(type); File file = new File(fileName); scheduledFilename = fileName + sdf.format(new Date(file.lastModified())); } else { reportError("Either File or DatePattern options are not set for appender [" + name + "].", null, ErrorManager.OPEN_FAILURE); } } void printPeriodicity(int type) { switch (type) { case TOP_OF_MINUTE: debug("Appender [" + name + "] to be rolled every minute."); break; case TOP_OF_HOUR: debug("Appender [" + name + "] to be rolled on top of every hour."); break; case HALF_DAY: debug("Appender [" + name + "] to be rolled at midday and midnight."); break; case TOP_OF_DAY: debug("Appender [" + name + "] to be rolled at midnight."); break; case TOP_OF_WEEK: debug("Appender [" + name + "] to be rolled at start of week."); break; case TOP_OF_MONTH: debug("Appender [" + name + "] to be rolled at start of every month."); break; default: reportError("Unknown periodicity for appender [" + name + "].", null, ErrorManager.FORMAT_FAILURE); } } // This method computes the roll over period by looping over the // periods, starting with the shortest, and stopping when the r0 is // different from from r1, where r0 is the epoch formatted according // the datePattern (supplied by the user) and r1 is the // epoch+nextMillis(i) formatted according to datePattern. All date // formatting is done in GMT and not local format because the test // logic is based on comparisons relative to 1970-01-01 00:00:00 // GMT (the epoch). int computeCheckPeriod() { RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH); // set sate to 1970-01-01 00:00:00 GMT Date epoch = new Date(0); if (datePattern != null) { for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); simpleDateFormat.setTimeZone(gmtTimeZone); // do all date formatting in GMT String r0 = simpleDateFormat.format(epoch); rollingCalendar.setType(i); Date next = new Date(rollingCalendar.getNextCheckMillis(epoch)); String r1 = simpleDateFormat.format(next); //System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1); if (r0 != null && r1 != null && !r0.equals(r1)) { return i; } } } return TOP_OF_TROUBLE; // Deliberately head for trouble... } /** * Rollover the current file to a new file. */ void rollOver() throws IOException { /* Compute filename, but only if datePattern is specified */ if (datePattern == null) { reportError("Missing DatePattern option in rollOver().", null, ErrorManager.OPEN_FAILURE); return; } String datedFilename = fileName + sdf.format(now); // It is too early to roll over because we are still within the // bounds of the current interval. Rollover will occur once the // next interval is reached. if (scheduledFilename.equals(datedFilename)) { return; } // close current file, and rename it to datedFilename this.close(); File target = new File(scheduledFilename); if (target.exists()) { target.delete(); } File file = new File(fileName); boolean result = file.renameTo(target); if (result) { debug(fileName + " -> " + scheduledFilename); } else { reportError("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].", null, ErrorManager.OPEN_FAILURE); } try { // This will also close the file. This is OK since multiple // close operations are safe. this.setFile(fileName, false, this.bufferedIO, this.bufferSize); } catch (IOException e) { reportError("setFile(" + fileName + ", false) call failed.", null, ErrorManager.OPEN_FAILURE); } scheduledFilename = datedFilename; } /** * This method differentiates DailyRollingFileAppender from its * super class. *

*

Before actually logging, this method will check whether it is * time to do a rollover. If it is, it will schedule the next * rollover time and then rollover. */ protected void subPublish(LogRecord event) { long n = System.currentTimeMillis(); if (n >= nextCheck) { now.setTime(n); nextCheck = rc.getNextCheckMillis(now); try { rollOver(); } catch (IOException ioe) { reportError("rollOver() failed.", ioe, ErrorManager.OPEN_FAILURE); } } super.subPublish(event); } } /** * RollingCalendar is a helper class to DailyRollingFileAppender. * Given a periodicity type and the current time, it computes the * start of the next interval. * */ class RollingCalendar extends GregorianCalendar { /** The serialVersionUID */ private static final long serialVersionUID = 1L; int type = DailyRollingFileHandler.TOP_OF_TROUBLE; RollingCalendar() { super(); } RollingCalendar(TimeZone tz, Locale locale) { super(tz, locale); } void setType(int type) { this.type = type; } public long getNextCheckMillis(Date now) { return getNextCheckDate(now).getTime(); } public Date getNextCheckDate(Date now) { this.setTime(now); switch (type) { case DailyRollingFileHandler.TOP_OF_MINUTE: this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.MINUTE, 1); break; case DailyRollingFileHandler.TOP_OF_HOUR: this.set(Calendar.MINUTE, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.HOUR_OF_DAY, 1); break; case DailyRollingFileHandler.HALF_DAY: this.set(Calendar.MINUTE, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); int hour = get(Calendar.HOUR_OF_DAY); if (hour < 12) { this.set(Calendar.HOUR_OF_DAY, 12); } else { this.set(Calendar.HOUR_OF_DAY, 0); this.add(Calendar.DAY_OF_MONTH, 1); } break; case DailyRollingFileHandler.TOP_OF_DAY: this.set(Calendar.HOUR_OF_DAY, 0); this.set(Calendar.MINUTE, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.DATE, 1); break; case DailyRollingFileHandler.TOP_OF_WEEK: this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); this.set(Calendar.HOUR_OF_DAY, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.WEEK_OF_YEAR, 1); break; case DailyRollingFileHandler.TOP_OF_MONTH: this.set(Calendar.DATE, 1); this.set(Calendar.HOUR_OF_DAY, 0); this.set(Calendar.SECOND, 0); this.set(Calendar.MILLISECOND, 0); this.add(Calendar.MONTH, 1); break; default: throw new IllegalStateException("Unknown periodicity type."); } return getTime(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handlers/FileHandler.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/handler0000644000175000017500000001703710774202215033205 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.handlers; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.ErrorManager; import java.util.logging.Formatter; /** * FileAppender appends log events to a file. * * @author Ceki Gülcü * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class FileHandler extends WriterHandler { /** * Controls file truncatation. The default value for this variable * is true, meaning that by default a * FileAppender will append to an existing file and not * truncate it. *

*

This option is meaningful only if the FileAppender opens the * file. */ protected boolean fileAppend = true; /** * The name of the log file. */ protected String fileName = null; /** * The default constructor does not do anything. */ public FileHandler() { } /** * Instantiate a FileHandler and open the file * designated by filename. The opened filename will * become the output destination for this appender. *

*

If the append parameter is true, the file will be * appended to. Otherwise, the file designated by * filename will be truncated before being opened. *

*

If the bufferedIO parameter is true, * then buffered IO will be used to write to the output file. * @param layout * @param filename * @param append * @param bufferedIO * @param bufferSize * @throws IOException */ public FileHandler(Formatter layout, String filename, boolean append, boolean bufferedIO, int bufferSize) throws IOException { super.setFormatter(layout); this.setFile(filename, append, bufferedIO, bufferSize); } /** * Instantiate a FileHandler and open the file designated by * filename. The opened filename will become the output * destination for this appender. *

*

If the append parameter is true, the file will be * appended to. Otherwise, the file designated by * filename will be truncated before being opened. * @param layout * @param filename * @param append * @throws IOException */ public FileHandler(Formatter layout, String filename, boolean append) throws IOException { this(layout, filename, append, true, 2048); } /** * Instantiate a FileHandler and open the file designated by * filename. The opened filename will become the output * destination for this appender. *

*

The file will be appended to. * @param layout * @param filename * @throws IOException */ public FileHandler(Formatter layout, String filename) throws IOException { this(layout, filename, true); } /** * The File property takes a string value which should be the * name of the file to append to. *

*

Note: Actual opening of the file is made when {@link * #activateOptions} is called, not when the options are set. * @param file */ public void setFile(String file) { // Trim spaces from both ends. The users probably does not want // trailing spaces in file names. String val = file.trim(); fileName = val; } /** * Returns the value of the Append option. * @return whether to append to the file */ public boolean getAppend() { return fileAppend; } /** * Returns the value of the File option. * @return the file name */ public String getFile() { return fileName; } /** * If the value of File is not null, then {@link * #setFile(String)} is called with the values of File and * Append properties. * */ public void activateOptions() { if (fileName != null) { try { setFile(fileName, fileAppend, bufferedIO, bufferSize); } catch (java.io.IOException e) { reportError("setFile(" + fileName + "," + fileAppend + ") call failed.", e, ErrorManager.OPEN_FAILURE); } } else { reportError("File option not set for appender [" + name + "]." +" Are you using FileHandler instead of ConsoleAppender?", null, ErrorManager.OPEN_FAILURE); } } /** * The Append option takes a boolean value. It is set to * true by default. If true, then File * will be opened in append mode by {@link #setFile(String) setFile} (see * above). Otherwise, {@link #setFile(String) setFile} will open * File in truncate mode. *

*

Note: Actual opening of the file is made when {@link * #activateOptions} is called, not when the options are set. * @param flag */ public void setAppend(boolean flag) { fileAppend = flag; } /** *

Sets and opens the file where the log output will * go. The specified file must be writable. *

*

If there was already an opened file, then the previous file * is closed first. *

*

Do not use this method directly. To configure a FileHandler * or one of its subclasses, set its properties one by one and then * call activateOptions. * * @param fileName The path to the log file. * @param append If true will append to fileName. Otherwise will * truncate fileName. * @param bufferedIO * @param bufferSize * @throws IOException */ public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException { // reportError("setFile called: " + fileName + ", " + append, null, ErrorManager.GENERIC_FAILURE); super.setBufferedIO(bufferedIO); super.setBufferSize(bufferSize); FileOutputStream ostream = null; try { // attempt to create file ostream = new FileOutputStream(fileName, append); } catch (FileNotFoundException ex) { // if parent directory does not exist then // attempt to create it and try to create file String parentName = new File(fileName).getParent(); if (parentName != null) { File parentDir = new File(parentName); if (!parentDir.exists() && parentDir.mkdirs()) { ostream = new FileOutputStream(fileName, append); } else { throw ex; } } else { throw ex; } } super.setOutputStream(ostream); this.fileName = fileName; this.fileAppend = append; // LogLog.debug("setFile ended"); } } libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/xml/0000755000175000017500000000000011105642371032435 5ustar twernertwerner././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/xml/DOMConfigurator.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/xml/DOM0000644000175000017500000010147110774202215033003 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.net.URL; import java.util.Hashtable; import java.util.Properties; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import org.jboss.logging.jdk.handlers.HandlerSkeleton; import org.jboss.util.StringPropertyReplacer; import org.jboss.util.propertyeditor.PropertyEditors; import org.jboss.util.xml.JBossEntityResolver; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; // Contributors: Mark Womack // Arun Katkere /** * Use this class to initialize the log4j environment using a DOM tree. *

*

The DTD is specified in log4j.dtd. *

*

Sometimes it is useful to see how log4j is reading configuration * files. You can enable log4j internal logging by defining the * log4j.debug variable on the java command * line. Alternatively, set the debug attribute in the * jdk:configuration element. As in *

 * <log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
 * ...
 * </log4j:configuration>
 * 
*

*

There are sample XML files included in the package. * * @author Christopher Taylor * @author Ceki Gülcü * @author Anders Kristensen * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class DOMConfigurator { static final String CONFIGURATION_TAG = "jdk:configuration"; static final String OLD_CONFIGURATION_TAG = "configuration"; static final String RENDERER_TAG = "renderer"; static final String APPENDER_TAG = "appender"; static final String APPENDER_REF_TAG = "appender-ref"; static final String PARAM_TAG = "param"; static final String LAYOUT_TAG = "layout"; static final String CATEGORY = "category"; static final String LOGGER = "logger"; static final String LOGGER_REF = "logger-ref"; static final String CATEGORY_FACTORY_TAG = "categoryFactory"; static final String NAME_ATTR = "name"; static final String CLASS_ATTR = "class"; static final String VALUE_ATTR = "value"; static final String ROOT_TAG = "root"; static final String ROOT_REF = "root-ref"; static final String LEVEL_TAG = "level"; static final String PRIORITY_TAG = "priority"; static final String FILTER_TAG = "filter"; static final String ERROR_HANDLER_TAG = "errorHandler"; static final String REF_ATTR = "ref"; static final String ADDITIVITY_ATTR = "additivity"; static final String THRESHOLD_ATTR = "threshold"; static final String CONFIG_DEBUG_ATTR = "configDebug"; static final String INTERNAL_DEBUG_ATTR = "debug"; static final String RENDERING_CLASS_ATTR = "renderingClass"; static final String RENDERED_CLASS_ATTR = "renderedClass"; static final String EMPTY_STR = ""; static final Class[] ONE_STRING_PARAM = new Class[]{String.class}; final static String dbfKey = "javax.xml.parsers.DocumentBuilderFactory"; // key: appenderName, value: appender private Hashtable appenderBag; private ErrorManager errorLog; private LogManager repository; private boolean debug; /** * Configure jdk using a configuration element as * defined in the jdk.dtd. * @param element */ static public void configure(Element element) { DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(element, LogManager.getLogManager()); } /** * A static version of {@link #doConfigure(String, LogManager)}. * @param filename the file name * @throws FactoryConfigurationError for any error */ static public void configure(String filename) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(filename, LogManager.getLogManager()); } /** * A static version of {@link #doConfigure(java.net.URL, LogManager)}. * @param url the url * @throws FactoryConfigurationError for any error */ static public void configure(URL url) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(url, LogManager.getLogManager()); } /** * A static version of {@link #doConfigure(java.net.URL, LogManager)}. * @param is the input stream * @throws FactoryConfigurationError for any error */ static public void configure(InputStream is) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(is, LogManager.getLogManager()); } /** * No argument constructor. */ public DOMConfigurator() { this(new ErrorManager()); } public DOMConfigurator(ErrorManager errorLog) { appenderBag = new Hashtable(); this.errorLog = errorLog; } /** * Used internally to parse appenders by IDREF name. * * @param doc the document * @param appenderName the appender name * @return the handler */ protected Handler findHandlerByName(Document doc, String appenderName) { Handler appender = appenderBag.get(appenderName); if (appender != null) { return appender; } else { // Doesn't work on DOM Level 1 : Element element = doc.getElementById(appenderName); if (element == null) { errorLog.error("No appender named [" + appenderName + "] could be found.", null, ErrorManager.GENERIC_FAILURE); return null; } else { appender = parseHandler(element); appenderBag.put(appenderName, appender); return appender; } } } /** * Used internally to parse appenders by IDREF element. * @param appenderRef * @return the handler */ protected Handler findHandlerByReference(Element appenderRef) { String appenderName = subst(appenderRef.getAttribute(REF_ATTR)); Document doc = appenderRef.getOwnerDocument(); return findHandlerByName(doc, appenderName); } /** * Used internally to parse an appender element. * * @param appenderElement the append element * @return the handler */ protected Handler parseHandler(Element appenderElement) { String className = subst(appenderElement.getAttribute(CLASS_ATTR)); debug("Class name: [" + className + ']'); try { Object instance = instantiateByClassName(className, Handler.class, null); Handler appender = (Handler) instance; Properties beanProps = new Properties(); String name = subst(appenderElement.getAttribute(NAME_ATTR)); HandlerSkeleton handlerSkeleton = null; if( appender instanceof HandlerSkeleton ) { handlerSkeleton = (HandlerSkeleton) appender; handlerSkeleton.setName(name); } NodeList children = appenderElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); /* We're only interested in Elements */ if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; // Parse appender parameters if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, beanProps); } // Set appender layout else if (currentElement.getTagName().equals(LAYOUT_TAG)) { Formatter format = parseLayout(currentElement); appender.setFormatter(format); } // Add filters else if (currentElement.getTagName().equals(FILTER_TAG)) { parseFilters(currentElement, appender); } else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) { parseErrorManager(currentElement, appender); } else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) { String refName = subst(currentElement.getAttribute(REF_ATTR)); errorLog.error("Requesting attachment of handler named [" + refName + "] to handler named [" + appender + "] which does not implement org.apache.jdk.spi.HandlerAttachable.", null, ErrorManager.GENERIC_FAILURE); } } } PropertyEditors.mapJavaBeanProperties(appender, beanProps); if( handlerSkeleton != null ) handlerSkeleton.activateOptions(); return appender; } /* Yes, it's ugly, but all of these exceptions point to the same problem: we can't create an Handler */ catch (Exception oops) { errorLog.error("Could not create an Handler. Reported error follows.", oops, ErrorManager.GENERIC_FAILURE); return null; } } /** * Used internally to parse an {@link ErrorManager} element. * * @param element the xml element * @param appender the appender * @throws Exception for any error */ protected void parseErrorManager(Element element, Handler appender) throws Exception { String className = subst(element.getAttribute(CLASS_ATTR)); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class ehClazz = loader.loadClass(className); ErrorManager eh = (ErrorManager) ehClazz.newInstance(); appender.setErrorManager(eh); } /** * Used internally to parse a filter element. * * @param element the xml element * @param appender the appender * @throws Exception for any error */ protected void parseFilters(Element element, Handler appender) throws Exception { String clazz = subst(element.getAttribute(CLASS_ATTR)); Filter filter = (Filter) instantiateByClassName(clazz, Filter.class, null); if (filter != null) { Properties beanProps = new Properties(); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(PARAM_TAG)) { setParameter(currentElement, beanProps); } } } PropertyEditors.mapJavaBeanProperties(filter, beanProps); debug("Setting filter of type [" + filter.getClass() + "] to appender named [" + appender + "]."); appender.setFilter(filter); } } /** * Used internally to parse an category element. * * @param loggerElement the xml element * @throws Exception for any error */ protected void parseCategory(Element loggerElement) throws Exception { // Create a new org.apache.jdk.Category object from the element. String catName = subst(loggerElement.getAttribute(NAME_ATTR)); Logger logger; String className = subst(loggerElement.getAttribute(CLASS_ATTR)); if (EMPTY_STR.equals(className)) { debug("Retreiving an instance of java.util.logging.Logger."); logger = repository.getLogger(catName); if( logger == null ) { logger = Logger.getLogger(catName); repository.addLogger(logger); } } else { debug("Desired logger sub-class: [" + className + ']'); try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class c = loader.loadClass(className); Class[] sig = {String.class, String.class}; Constructor ctor = c.getConstructor(sig); Object[] args = {catName, null}; logger = (Logger) ctor.newInstance(args); } catch (Exception oops) { errorLog.error("Could not retrieve category [" + catName + "]. Reported error follows.", oops, ErrorManager.GENERIC_FAILURE); return; } } // Setting up a category needs to be an atomic operation, in order // to protect potential log operations while category // configuration is in progress. synchronized (logger) { String flag = subst(loggerElement.getAttribute(ADDITIVITY_ATTR)); boolean additivity = Boolean.valueOf(flag).booleanValue(); debug("Setting [" + logger.getName() + "] additivity to [" + additivity + "]."); logger.setUseParentHandlers(additivity); parseChildrenOfLoggerElement(loggerElement, logger, false); } } /** * Used internally to parse the category factory element. * * @param factoryElement the xml element * @throws Exception for any error */ protected void parseCategoryFactory(Element factoryElement) throws Exception { String className = subst(factoryElement.getAttribute(CLASS_ATTR)); if (EMPTY_STR.equals(className)) { errorLog.error("Category Factory tag " + CLASS_ATTR + " attribute not found.", null, ErrorManager.GENERIC_FAILURE); } else { debug("Desired category factory: [" + className + ']'); Object catFactory = instantiateByClassName(className, Object.class, null); Properties beanProps = new Properties(); Element currentElement = null; Node currentNode = null; NodeList children = factoryElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, beanProps); } } } PropertyEditors.mapJavaBeanProperties(catFactory, beanProps); } } /** * Used internally to parse the root category element. * * @param rootElement the xml element * @throws Exception for any error */ protected void parseRoot(Element rootElement) throws Exception { Logger root = repository.getLogger(""); if( root == null ) { root = Logger.getLogger(""); repository.addLogger(root); } // category configuration needs to be atomic synchronized (root) { parseChildrenOfLoggerElement(rootElement, root, true); } } /** * Used internally to parse the children of a category element. * * @param catElement the xml element * @param logger the logger * @param isRoot whether this is the root * @throws Exception for any error */ protected void parseChildrenOfLoggerElement(Element catElement, Logger logger, boolean isRoot) throws Exception { Properties beanProps = new Properties(); // Remove all existing appenders from logger. They will be // reconstructed if need be. Handler[] handlers = logger.getHandlers(); for(int n = 0; n < handlers.length; n ++) { Handler h = handlers[n]; logger.removeHandler(h); } NodeList children = catElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(APPENDER_REF_TAG)) { Element appenderRef = (Element) currentNode; Handler appender = findHandlerByReference(appenderRef); String refName = subst(appenderRef.getAttribute(REF_ATTR)); if (appender != null) debug("Adding appender named [" + refName + "] to category [" + logger.getName() + "]."); else debug("Handler named [" + refName + "] not found."); logger.addHandler(appender); } else if (tagName.equals(LEVEL_TAG)) { parseLevel(currentElement, logger, isRoot); } else if (tagName.equals(PRIORITY_TAG)) { parseLevel(currentElement, logger, isRoot); } else if (tagName.equals(PARAM_TAG)) { setParameter(currentElement, beanProps); } } } PropertyEditors.mapJavaBeanProperties(logger, beanProps); } /** * Used internally to parse a layout element. * * @param layout_element the xml element * @return the formatter */ protected Formatter parseLayout(Element layout_element) { String className = subst(layout_element.getAttribute(CLASS_ATTR)); debug("Parsing layout of class: \"" + className + "\""); try { Object instance = instantiateByClassName(className, Formatter.class, null); Formatter layout = (Formatter) instance; Properties beanProps = new Properties(); NodeList params = layout_element.getChildNodes(); final int length = params.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = params.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(PARAM_TAG)) { setParameter(currentElement, beanProps); } } } PropertyEditors.mapJavaBeanProperties(layout, beanProps); return layout; } catch (Exception oops) { errorLog.error("Could not create the Layout. Reported error follows.", oops, ErrorManager.GENERIC_FAILURE); return null; } } protected void parseRenderer(Element element) { } /** * Used internally to parse a level element. * * @param element the element * @param logger the logger * @param isRoot whether it is the root */ protected void parseLevel(Element element, Logger logger, boolean isRoot) { String catName = logger.getName(); if (isRoot) { catName = "root"; } String levelName = subst(element.getAttribute(VALUE_ATTR)); debug("Level value for " + catName + " is [" + levelName + "]."); if ("INHERITED".equalsIgnoreCase(levelName) || "NULL".equalsIgnoreCase(levelName)) { if (isRoot) { errorLog.error("Root level cannot be inherited. Ignoring directive.", null, ErrorManager.GENERIC_FAILURE); } else { logger.setLevel(null); } } else { String className = subst(element.getAttribute(CLASS_ATTR)); if (EMPTY_STR.equals(className)) { Level level = Level.parse(levelName); logger.setLevel(level); } else if( className.equals("org.jboss.logging.XLevel") ) { // Special handling of the jboss XLevel logger.setLevel(Level.FINER); } else { debug("Desired Level sub-class: [" + className + ']'); try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass(className); Class[] sig = {String.class, int.class}; Object[] args = {levelName, new Integer(Level.FINEST.intValue())}; Constructor ctor = clazz.getConstructor(sig); Level pri = (Level) ctor.newInstance(args); logger.setLevel(pri); } catch (Exception oops) { errorLog.error("Could not create level [" + levelName + "]. Reported error follows.", oops, ErrorManager.GENERIC_FAILURE); return; } } } debug(catName + " level set to " + logger.getLevel()); } protected void setParameter(Element elem, Properties beanProps) { String name = subst(elem.getAttribute(NAME_ATTR)); String value = (elem.getAttribute(VALUE_ATTR)); value = subst(convertSpecialChars(value)); beanProps.setProperty(name, value); } private interface ParseAction { Document parse(final DocumentBuilder parser) throws SAXException, IOException; } public void doConfigure(final String filename, LogManager repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(new File(filename)); } public String toString() { return "file [" + filename + "]"; } }; doConfigure(action, repository); } public void doConfigure(final URL url, LogManager repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(url.toString()); } public String toString() { return "url [" + url.toString() + "]"; } }; doConfigure(action, repository); } /** * Configure jdk by reading in a jdk.dtd compliant XML * configuration file. * @param inputStream * @param repository * @throws FactoryConfigurationError */ public void doConfigure(final InputStream inputStream, LogManager repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(inputStream); inputSource.setSystemId("dummy://jdk.dtd"); return parser.parse(inputSource); } public String toString() { return "input stream [" + inputStream.toString() + "]"; } }; doConfigure(action, repository); } /** * Configure jdk by reading in a jdk.dtd compliant XML * configuration file. * @param reader * @param repository * @throws FactoryConfigurationError */ public void doConfigure(final Reader reader, LogManager repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(reader); inputSource.setSystemId("dummy://jdk.dtd"); return parser.parse(inputSource); } public String toString() { return "reader [" + reader.toString() + "]"; } }; doConfigure(action, repository); } /** * Configure jdk by reading in a jdk.dtd compliant XML * configuration file. * @param inputSource * @param repository * @throws FactoryConfigurationError */ protected void doConfigure(final InputSource inputSource, LogManager repository) throws FactoryConfigurationError { if (inputSource.getSystemId() == null) { inputSource.setSystemId("dummy://jdk.dtd"); } ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(inputSource); } public String toString() { return "input source [" + inputSource.toString() + "]"; } }; doConfigure(action, repository); } private final void doConfigure(final ParseAction action, final LogManager repository) throws FactoryConfigurationError { DocumentBuilderFactory dbf = null; this.repository = repository; try { dbf = DocumentBuilderFactory.newInstance(); debug("Standard DocumentBuilderFactory search succeded."); debug("DocumentBuilderFactory is: " + dbf.getClass().getName()); } catch (FactoryConfigurationError fce) { Exception e = fce.getException(); errorLog.error("Could not instantiate a DocumentBuilderFactory.", e, ErrorManager.GENERIC_FAILURE); throw fce; } try { dbf.setValidating(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); JBossEntityResolver resolver = new JBossEntityResolver(); resolver.registerLocalEntity("urn:jboss:jdklogger.dtd", "jdklogger.dtd"); docBuilder.setEntityResolver(resolver); Document doc = action.parse(docBuilder); parse(doc.getDocumentElement()); } catch (Exception e) { // I know this is miserable... errorLog.error("Could not parse " + action.toString() + ".", e, ErrorManager.GENERIC_FAILURE); } } /** * Configure by taking in an DOM element. * @param element * @param repository */ public void doConfigure(Element element, LogManager repository) { this.repository = repository; parse(element); } /** * Used internally to configure the jdk framework by parsing a DOM * tree of XML elements based on jdk.dtd. * @param element */ protected void parse(Element element) { String rootElementName = element.getTagName(); if (!rootElementName.equals(CONFIGURATION_TAG)) { if (rootElementName.equals(OLD_CONFIGURATION_TAG)) { errorLog.error("The <" + OLD_CONFIGURATION_TAG + "> element has been deprecated." + ", use the <" + CONFIGURATION_TAG + "> element instead.", null, ErrorManager.GENERIC_FAILURE); } else { errorLog.error("DOM element is - not a <" + CONFIGURATION_TAG + "> element.", null, ErrorManager.GENERIC_FAILURE); return; } } String debugAttrib = subst(element.getAttribute(INTERNAL_DEBUG_ATTR)); debug("debug attribute= '" + debugAttrib + "'."); // if the jdk.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if (!debugAttrib.equals("") && !debugAttrib.equals("null")) { debug = Boolean.valueOf(debugAttrib).booleanValue(); } else { debug("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } String confDebug = subst(element.getAttribute(CONFIG_DEBUG_ATTR)); if (!confDebug.equals("") && !confDebug.equals("null")) { debug = true; } String thresholdStr = subst(element.getAttribute(THRESHOLD_ATTR)); debug("Threshold ='" + thresholdStr + "'."); if (!"".equals(thresholdStr) && !"null".equals(thresholdStr)) { Level threshold = Level.parse(thresholdStr); Logger root = repository.getLogger(""); root.setLevel(threshold); } // First configure each category factory under the root element. // Category factories need to be configured before any of // categories they support. // String tagName = null; Element currentElement = null; Node currentNode = null; NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY_FACTORY_TAG)) { try { parseCategoryFactory(currentElement); } catch(Exception e) { errorLog.error("Failed to parse: "+tagName, e, ErrorManager.GENERIC_FAILURE); } } } } for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); try { if (tagName.equals(CATEGORY) || tagName.equals(LOGGER)) { parseCategory(currentElement); } else if (tagName.equals(ROOT_TAG)) { parseRoot(currentElement); } else if (tagName.equals(RENDERER_TAG)) { parseRenderer(currentElement); } } catch(Exception e) { errorLog.error("Failed to parse element: "+tagName, e, ErrorManager.GENERIC_FAILURE); } } } } protected String subst(String value) { if( value == null ) return null; try { return StringPropertyReplacer.replaceProperties(value); } catch (Exception e) { errorLog.error("Could not perform variable substitution.", e, ErrorManager.GENERIC_FAILURE); return value; } } static String convertSpecialChars(String s) { char c; int len = s.length(); StringBuffer sbuf = new StringBuffer(len); int i = 0; while(i < len) { c = s.charAt(i++); if (c == '\\') { c = s.charAt(i++); if(c == 'n') c = '\n'; else if(c == 'r') c = '\r'; else if(c == 't') c = '\t'; else if(c == 'f') c = '\f'; else if(c == '\b') c = '\b'; else if(c == '\"') c = '\"'; else if(c == '\'') c = '\''; else if(c == '\\') c = '\\'; } sbuf.append(c); } return sbuf.toString(); } protected void debug(String msg) { if( debug ) System.out.println(msg); } Object instantiateByClassName(String className, Class superClass, Object defaultValue) { if (className != null) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class classObj = loader.loadClass(className); if (!superClass.isAssignableFrom(classObj)) { errorLog.error("A \"" + className + "\" object is not assignable to a \"" + superClass.getName() + "\" variable." +"The class \"" + superClass.getName() + "\" was loaded by " +"[" + superClass.getClassLoader() + "] whereas object of type " +"'" + classObj.getName() + "\" was loaded by [" + classObj.getClassLoader() + "].", null, ErrorManager.GENERIC_FAILURE); return defaultValue; } return classObj.newInstance(); } catch (Exception e) { errorLog.error("Could not instantiate class [" + className + "].", e, ErrorManager.GENERIC_FAILURE); } } return defaultValue; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000755000175000017500000000000011105642371033125 5ustar twernertwerner././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/AbsoluteTimeDateFormat.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000000765410774202215033143 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Calendar; import java.util.TimeZone; import java.util.Date; /** * Formats a {@link Date} in the format "HH:mm:ss,SSS" for example, * "15:49:37,459". * * @author Ceki Gülcü * @author Andrew Vajoczki * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class AbsoluteTimeDateFormat extends DateFormat { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** * String constant used to specify {@link * AbsoluteTimeDateFormat} in layouts. Current * value is ABSOLUTE. */ public final static String ABS_TIME_DATE_FORMAT = "ABSOLUTE"; /** * String constant used to specify {@link * DateTimeDateFormat} in layouts. Current * value is DATE. */ public final static String DATE_AND_TIME_DATE_FORMAT = "DATE"; /** * String constant used to specify {@link * ISO8601DateFormat} in layouts. Current * value is ISO8601. */ public final static String ISO8601_DATE_FORMAT = "ISO8601"; public AbsoluteTimeDateFormat() { setCalendar(Calendar.getInstance()); } public AbsoluteTimeDateFormat(TimeZone timeZone) { setCalendar(Calendar.getInstance(timeZone)); } private static long previousTime; private static char[] previousTimeWithoutMillis = new char[9]; // "HH:mm:ss." /** * Appends to sbuf the time in the format * "HH:mm:ss,SSS" for example, "15:49:37,459" * * @param date the date to format * @param sbuf the string buffer to write to * @param fieldPosition remains untouched */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { long now = date.getTime(); int millis = (int) (now % 1000); if ((now - millis) != previousTime) { // We reach this point at most once per second // across all threads instead of each time format() // is called. This saves considerable CPU time. calendar.setTime(date); int start = sbuf.length(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour < 10) { sbuf.append('0'); } sbuf.append(hour); sbuf.append(':'); int mins = calendar.get(Calendar.MINUTE); if (mins < 10) { sbuf.append('0'); } sbuf.append(mins); sbuf.append(':'); int secs = calendar.get(Calendar.SECOND); if (secs < 10) { sbuf.append('0'); } sbuf.append(secs); sbuf.append(','); // store the time string for next time to avoid recomputation sbuf.getChars(start, sbuf.length(), previousTimeWithoutMillis, 0); previousTime = now - millis; } else { sbuf.append(previousTimeWithoutMillis); } if (millis < 100) sbuf.append('0'); if (millis < 10) sbuf.append('0'); sbuf.append(millis); return sbuf; } /** This method does not do anything but return null. */ public Date parse(String s, ParsePosition pos) { return null; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/DateTimeDateFormat.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000000450610774202215033134 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.text.DateFormatSymbols; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.TimeZone; import java.util.Calendar; import java.util.Date; /** * Formats a {@link Date} in the format "dd MMM YYYY HH:mm:ss,SSS" for example, * "06 Nov 1994 15:49:37,459". * * @author Ceki Gülcü * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class DateTimeDateFormat extends AbsoluteTimeDateFormat { /** The serialVersionUID */ private static final long serialVersionUID = 1L; String[] shortMonths; public DateTimeDateFormat() { super(); shortMonths = new DateFormatSymbols().getShortMonths(); } public DateTimeDateFormat(TimeZone timeZone) { this(); setCalendar(Calendar.getInstance(timeZone)); } /** * Appends to sbuf the date in the format "dd MMM YYYY * HH:mm:ss,SSS" for example, "06 Nov 1994 08:49:37,459". * * @param sbuf the string buffer to write to */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { calendar.setTime(date); int day = calendar.get(Calendar.DAY_OF_MONTH); if (day < 10) sbuf.append('0'); sbuf.append(day); sbuf.append(' '); sbuf.append(shortMonths[calendar.get(Calendar.MONTH)]); sbuf.append(' '); int year = calendar.get(Calendar.YEAR); sbuf.append(year); sbuf.append(' '); return super.format(date, sbuf, fieldPosition); } /** * This method does not do anything but return null. */ public Date parse(java.lang.String s, ParsePosition pos) { return null; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/ISO8601DateFormat.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000001155510774202215033136 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.util.TimeZone; import java.util.Date; import java.util.Calendar; import java.text.FieldPosition; import java.text.ParsePosition; // Contributors: Arndt Schoenewald /** * Formats a {@link java.util.Date} in the format "YYYY-mm-dd HH:mm:ss,SSS" for example * "1999-11-27 15:49:37,459". *

*

Refer to the summary of the * International Standard Date and Time Notation for more * information on this format. * * @author Ceki Gülcü * @author Andrew Vajoczki * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class ISO8601DateFormat extends AbsoluteTimeDateFormat { /** The serialVersionUID */ private static final long serialVersionUID = 1L; public ISO8601DateFormat() { } public ISO8601DateFormat(TimeZone timeZone) { super(timeZone); } static private long lastTime; static private char[] lastTimeString = new char[20]; /** * Appends a date in the format "YYYY-mm-dd HH:mm:ss,SSS" * to sbuf. For example: "1999-11-27 15:49:37,459". * * @param sbuf the StringBuffer to write to */ public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) { long now = date.getTime(); int millis = (int) (now % 1000); if ((now - millis) != lastTime) { // We reach this point at most once per second // across all threads instead of each time format() // is called. This saves considerable CPU time. calendar.setTime(date); int start = sbuf.length(); int year = calendar.get(Calendar.YEAR); sbuf.append(year); String month; switch (calendar.get(Calendar.MONTH)) { case Calendar.JANUARY: month = "-01-"; break; case Calendar.FEBRUARY: month = "-02-"; break; case Calendar.MARCH: month = "-03-"; break; case Calendar.APRIL: month = "-04-"; break; case Calendar.MAY: month = "-05-"; break; case Calendar.JUNE: month = "-06-"; break; case Calendar.JULY: month = "-07-"; break; case Calendar.AUGUST: month = "-08-"; break; case Calendar.SEPTEMBER: month = "-09-"; break; case Calendar.OCTOBER: month = "-10-"; break; case Calendar.NOVEMBER: month = "-11-"; break; case Calendar.DECEMBER: month = "-12-"; break; default: month = "-NA-"; break; } sbuf.append(month); int day = calendar.get(Calendar.DAY_OF_MONTH); if (day < 10) sbuf.append('0'); sbuf.append(day); sbuf.append(' '); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour < 10) { sbuf.append('0'); } sbuf.append(hour); sbuf.append(':'); int mins = calendar.get(Calendar.MINUTE); if (mins < 10) { sbuf.append('0'); } sbuf.append(mins); sbuf.append(':'); int secs = calendar.get(Calendar.SECOND); if (secs < 10) { sbuf.append('0'); } sbuf.append(secs); sbuf.append(','); // store the time string for next time to avoid recomputation sbuf.getChars(start, sbuf.length(), lastTimeString, 0); lastTime = now - millis; } else { sbuf.append(lastTimeString); } if (millis < 100) sbuf.append('0'); if (millis < 10) sbuf.append('0'); sbuf.append(millis); return sbuf; } /** * This method does not do anything but return null. */ public Date parse(java.lang.String s, ParsePosition pos) { return null; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/PatternFormatter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000003720710774202215033140 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.util.logging.Formatter; import java.util.logging.LogRecord; import org.jboss.logging.MDC; // Contributors: Nelson Minar // Anders Kristensen /** * A flexible layout configurable with pattern string. *

*

The goal of this class is to {@link #format format} a {@link * LogRecord} and return the results as a String. The results * depend on the conversion pattern. *

*

The conversion pattern is closely related to the conversion * pattern of the printf function in C. A conversion pattern is * composed of literal text and format control expressions called * conversion specifiers. *

*

You are free to insert any literal text within the conversion * pattern. *

*

Each conversion specifier starts with a percent sign (%) and is * followed by optional format modifiers and a conversion * character. The conversion character specifies the type of * data, e.g. category, priority, date, thread name. The format * modifiers control such things as field width, padding, left and * right justification. The following is a simple example. *

*

Let the conversion pattern be "%-5p [%t]: %m%n" and assume * that the log4j environment was set to use a PatternLayout. Then the * statements *

 * Category root = Category.getRoot();
 * root.debug("Message 1");
 * root.warn("Message 2");
 * 
* would yield the output *
 * DEBUG [main]: Message 1
 * WARN  [main]: Message 2
 * 
*

*

Note that there is no explicit separator between text and * conversion specifiers. The pattern parser knows when it has reached * the end of a conversion specifier when it reads a conversion * character. In the example above the conversion specifier * %-5p means the priority of the logging event should be left * justified to a width of five characters. *

* The recognized conversion characters are *

*

* * * *

*

* *

*

* *

*

* *

*

* *

*

* *

*

* *

*

*

*

* *

*

* *

*

* *

*

*

*

*

* * * *

*

* *

*

*

*

* *

*

*

*

* * * *

*

*

*

*

*

* *

*

*

* *

*

*

*

*

*

*

*

*

*

* *

*

*

* *

*

* *

*

*

*

*

*

* *

*

Conversion CharacterEffect
cUsed to output the category of the logging event. The * category conversion specifier can be optionally followed by * precision specifier, that is a decimal constant in * brackets. *

*

If a precision specifier is given, then only the corresponding * number of right most components of the category name will be * printed. By default the category name is printed in full. *

*

For example, for the category name "a.b.c" the pattern * %c{2} will output "b.c". *

*

CUsed to output the fully qualified class name of the caller * issuing the logging request. This conversion specifier * can be optionally followed by precision specifier, that * is a decimal constant in brackets. *

*

If a precision specifier is given, then only the corresponding * number of right most components of the class name will be * printed. By default the class name is output in fully qualified form. *

*

For example, for the class name "org.apache.xyz.SomeClass", the * pattern %C{1} will output "SomeClass". *

*

WARNING Generating the caller class information is * slow. Thus, it's use should be avoided unless execution speed is * not an issue. *

*

d Used to output the date of * the logging event. The date conversion specifier may be * followed by a date format specifier enclosed between * braces. For example, %d{HH:mm:ss,SSS} or * %d{dd MMM yyyy HH:mm:ss,SSS}. If no * date format specifier is given then ISO8601 format is * assumed. *

*

The date format specifier admits the same syntax as the * time pattern string of the {@link * java.text.SimpleDateFormat}. Although part of the standard * JDK, the performance of SimpleDateFormat is * quite poor. *

*

For better results it is recommended to use the log4j date * formatters. These can be specified using one of the strings * "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link * AbsoluteTimeDateFormat * AbsoluteTimeDateFormat}, {@link * DateTimeDateFormat DateTimeDateFormat} * and respectively {@link * ISO8601DateFormat * ISO8601DateFormat}. For example, %d{ISO8601} or * %d{ABSOLUTE}. *

*

These dedicated date formatters perform significantly * better than {@link java.text.SimpleDateFormat}. *

FUsed to output the file name where the logging request was * issued. *

*

WARNING Generating caller location information is * extremely slow. It's use should be avoided unless execution speed * is not an issue. *

*

lUsed to output location information of the caller which generated * the logging event. *

*

The location information depends on the JVM implementation but * usually consists of the fully qualified name of the calling * method followed by the callers source the file name and line * number between parentheses. *

*

The location information can be very useful. However, it's * generation is extremely slow. It's use should be avoided * unless execution speed is not an issue. *

*

LUsed to output the line number from where the logging request * was issued. *

*

WARNING Generating caller location information is * extremely slow. It's use should be avoided unless execution speed * is not an issue. *

*

mUsed to output the application supplied message associated with * the logging event.
MUsed to output the method name where the logging request was * issued. *

*

WARNING Generating caller location information is * extremely slow. It's use should be avoided unless execution speed * is not an issue. *

*

nOutputs the platform dependent line separator character or * characters. *

*

This conversion character offers practically the same * performance as using non-portable line separator strings such as * "\n", or "\r\n". Thus, it is the preferred way of specifying a * line separator. *

*

*

pUsed to output the priority of the logging event.
rUsed to output the number of milliseconds elapsed since the start * of the application until the creation of the logging event.
tUsed to output the name of the thread that generated the * logging event.
xUsed to output the NDC (nested diagnostic context) associated * with the thread that generated the logging event. *
X *

*

Used to output the MDC (mapped diagnostic context) associated * with the thread that generated the logging event. The X * conversion character must be followed by the key for the * map placed between braces, as in %X{clientNumber} where * clientNumber is the key. The value in the MDC * corresponding to the key will be output.

*

*

See {@link MDC} class for more details. *

*

*

%The sequence %% outputs a single percent sign. *
*

*

By default the relevant information is output as is. However, * with the aid of format modifiers it is possible to change the * minimum field width, the maximum field width and justification. *

*

The optional format modifier is placed between the percent sign * and the conversion character. *

*

The first optional format modifier is the left justification * flag which is just the minus (-) character. Then comes the * optional minimum field width modifier. This is a decimal * constant that represents the minimum number of characters to * output. If the data item requires fewer characters, it is padded on * either the left or the right until the minimum width is * reached. The default is to pad on the left (right justify) but you * can specify right padding with the left justification flag. The * padding character is space. If the data item is larger than the * minimum field width, the field is expanded to accommodate the * data. The value is never truncated. *

*

This behavior can be changed using the maximum field * width modifier which is designated by a period followed by a * decimal constant. If the data item is longer than the maximum * field, then the extra characters are removed from the * beginning of the data item and not from the end. For * example, it the maximum field width is eight and the data item is * ten characters long, then the first two characters of the data item * are dropped. This behavior deviates from the printf function in C * where truncation is done from the end. *

*

Below are various format modifier examples for the category * conversion specifier. *

*

* * * * * * *

*

* * * * *

*

* * * * *

*

* * * * *

*

Format modifier * left justify * minimum width * maximum width * comment *

*

%20cfalse20noneLeft pad with spaces if the category name is less than 20 * characters long. *

*

%-20c true 20 none Right pad with * spaces if the category name is less than 20 characters long. *

*

%.30cNAnone30Truncate from the beginning if the category name is longer than 30 * characters. *

*

%20.30cfalse2030Left pad with spaces if the category name is shorter than 20 * characters. However, if category name is longer than 30 characters, * then truncate from the beginning. *

*

%-20.30ctrue2030Right pad with spaces if the category name is shorter than 20 * characters. However, if category name is longer than 30 characters, * then truncate from the beginning. *

*

*

*

Below are some examples of conversion patterns. *

*

*

*

%r [%t] %-5p %c %x - %m\n *

This is essentially the TTCC layout. *

*

%-6r [%15.15t] %-5p %30.30c %x - %m\n *

*

Similar to the TTCC layout except that the relative time is * right padded if less than 6 digits, thread name is right padded if * less than 15 characters and truncated if longer and the category * name is left padded if shorter than 30 characters and truncated if * longer. *

*

*

*

The above text is largely inspired from Peter A. Darnell and * Philip E. Margolis' highly recommended book "C -- a Software * Engineering Approach", ISBN 0-387-97389-3. * * @author James P. Cakalic * @author Ceki Gülcü * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ * */ public class PatternFormatter extends Formatter { /** * Default pattern string for log output. Currently set to the * string "%m%n" which just prints the application supplied * message. */ public final static String DEFAULT_CONVERSION_PATTERN = "%m%n"; /** * A conversion pattern equivalent to the TTCCCLayout. * Current value is %r [%t] %p %c %x - %m%n. */ public final static String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; protected final int BUF_SIZE = 256; protected final int MAX_CAPACITY = 1024; private String pattern; private PatternConverter head; /** * Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. *

* The default pattern just produces the application supplied message. */ public PatternFormatter() { this(DEFAULT_CONVERSION_PATTERN); } /** * Constructs a PatternLayout using the supplied conversion pattern. * @param pattern */ public PatternFormatter(String pattern) { this.pattern = pattern; head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse(); } /** * Set the ConversionPattern option. This is the string which * controls formatting and consists of a mix of literal content and * conversion specifiers. * @param conversionPattern */ public void setConversionPattern(String conversionPattern) { pattern = conversionPattern; head = createPatternParser(conversionPattern).parse(); } /** * Returns the value of the ConversionPattern option. * @return the pattern */ public String getConversionPattern() { return pattern; } /** * Does not do anything as options become effective */ public void activateOptions() { // nothing to do. } /** * The PatternLayout does not handle the throwable contained within * {@link LogRecord LoggingEvents}. Thus, it returns * true. * * @return whether to ignore throwables * @since 0.8.4 */ public boolean ignoresThrowable() { return true; } /** * Returns PatternParser used to parse the conversion string. Subclasses * may override this to return a subclass of PatternParser which recognize * custom conversion characters. * * @param pattern the pattern * @return the parser * @since 0.9.0 */ protected PatternParser createPatternParser(String pattern) { return new PatternParser(pattern); } /** * Produces a formatted string as specified by the conversion pattern. */ public String format(LogRecord event) { // output buffer appended to when format() is invoked StringBuffer sbuf = new StringBuffer(BUF_SIZE); PatternConverter c = head; while (c != null) { c.format(sbuf, event); c = c.next; } return sbuf.toString(); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/PatternConverter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000000576310774202215033142 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.util.logging.LogRecord; /** *

PatternConverter is an abtract class that provides the * formatting functionality that derived classes need. *

*

Conversion specifiers in a conversion patterns are parsed to * individual PatternConverters. Each of which is responsible for * converting a logging event in a converter specific manner. * * @author James P. Cakalic * @author Ceki Gülcü * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public abstract class PatternConverter { public PatternConverter next; int min = -1; int max = 0x7FFFFFFF; boolean leftAlign = false; protected PatternConverter() { } protected PatternConverter(FormattingInfo fi) { min = fi.min; max = fi.max; leftAlign = fi.leftAlign; } /** * Derived pattern converters must override this method in order to * convert conversion specifiers in the correct way. * @param event * @return the converted record */ abstract protected String convert(LogRecord event); /** * A template method for formatting in a converter specific way. * @param sbuf * @param e */ public void format(StringBuffer sbuf, LogRecord e) { String s = convert(e); if (s == null) { if (0 < min) spacePad(sbuf, min); return; } int len = s.length(); if (len > max) sbuf.append(s.substring(len - max)); else if (len < min) { if (leftAlign) { sbuf.append(s); spacePad(sbuf, min - len); } else { spacePad(sbuf, min - len); sbuf.append(s); } } else sbuf.append(s); } static String[] SPACES = {" ", " ", " ", " ", //1,2,4,8 spaces " ", // 16 spaces " "}; // 32 spaces /** * Fast space padding method. * @param sbuf * @param length */ public void spacePad(StringBuffer sbuf, int length) { while (length >= 32) { sbuf.append(SPACES[5]); length -= 32; } for (int i = 4; i >= 0; i--) { if ((length & (1 << i)) != 0) { sbuf.append(SPACES[i]); } } } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/FormattingInfo.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000000237410470642610033135 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; /** * FormattingInfo instances contain the information obtained when parsing * formatting modifiers in conversion modifiers. * * @author Jim Cakalic * @author Ceki Gülcü * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class FormattingInfo { int min = -1; int max = 0x7FFFFFFF; boolean leftAlign = false; void reset() { min = -1; max = 0x7FFFFFFF; leftAlign = false; } void dump() { System.err.println("min=" + min + ", max=" + max + ", leftAlign=" + leftAlign); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/PatternParser.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/format/0000644000175000017500000004476610774202215033150 0ustar twernertwerner/* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.jdk.format; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.LogRecord; import org.jboss.logging.MDC; import org.jboss.logging.NDC; // Contributors: Nelson Minar <(nelson@monkey.org> // Igor E. Poteryaev // Reinhard Deschler /** * Pattern Parser * * @author James P. Cakalic * @author Ceki Gülcü * @author Anders Kristensen * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ public class PatternParser { public final static String LINE_SEP = System.getProperty("line.separator"); private static long startTime = System.currentTimeMillis(); private static final char ESCAPE_CHAR = '%'; private static final int LITERAL_STATE = 0; private static final int CONVERTER_STATE = 1; private static final int DOT_STATE = 3; private static final int MIN_STATE = 4; private static final int MAX_STATE = 5; static final int FULL_LOCATION_CONVERTER = 1000; static final int METHOD_LOCATION_CONVERTER = 1001; static final int CLASS_LOCATION_CONVERTER = 1002; static final int LINE_LOCATION_CONVERTER = 1003; static final int FILE_LOCATION_CONVERTER = 1004; static final int RELATIVE_TIME_CONVERTER = 2000; static final int THREAD_CONVERTER = 2001; static final int LEVEL_CONVERTER = 2002; static final int NDC_CONVERTER = 2003; static final int MESSAGE_CONVERTER = 2004; static final int THREAD_NAME_CONVERTER = 2005; int state; protected StringBuffer currentLiteral = new StringBuffer(32); protected int patternLength; protected int i; PatternConverter head; PatternConverter tail; protected FormattingInfo formattingInfo = new FormattingInfo(); protected String pattern; public PatternParser(String pattern) { this.pattern = pattern; patternLength = pattern.length(); state = LITERAL_STATE; } private void addToList(PatternConverter pc) { if (head == null) { head = tail = pc; } else { tail.next = pc; tail = pc; } } protected String extractOption() { if ((i < patternLength) && (pattern.charAt(i) == '{')) { int end = pattern.indexOf('}', i); if (end > i) { String r = pattern.substring(i + 1, end); i = end + 1; return r; } } return null; } /** * The option is expected to be in decimal and positive. In case of * error, zero is returned. * @return the precision option */ protected int extractPrecisionOption() { String opt = extractOption(); int r = 0; if (opt != null) { try { r = Integer.parseInt(opt); if (r <= 0) { System.err.println("Precision option (" + opt + ") isn't a positive integer."); r = 0; } } catch (NumberFormatException e) { System.err.println("Category option '" + opt + "' not a decimal integer." + e.getMessage()); } } return r; } public PatternConverter parse() { char c; i = 0; while (i < patternLength) { c = pattern.charAt(i++); switch (state) { case LITERAL_STATE: // In literal state, the last char is always a literal. if (i == patternLength) { currentLiteral.append(c); continue; } if (c == ESCAPE_CHAR) { // peek at the next char. switch (pattern.charAt(i)) { case ESCAPE_CHAR: currentLiteral.append(c); i++; // move pointer break; case 'n': currentLiteral.append(LINE_SEP); i++; // move pointer break; default: if (currentLiteral.length() != 0) { addToList(new LiteralPatternConverter( currentLiteral.toString())); //LogLog.debug("Parsed LITERAL converter: \"" // +currentLiteral+"\"."); } currentLiteral.setLength(0); currentLiteral.append(c); // append % state = CONVERTER_STATE; formattingInfo.reset(); } } else { currentLiteral.append(c); } break; case CONVERTER_STATE: currentLiteral.append(c); switch (c) { case '-': formattingInfo.leftAlign = true; break; case '.': state = DOT_STATE; break; default: if (c >= '0' && c <= '9') { formattingInfo.min = c - '0'; state = MIN_STATE; } else finalizeConverter(c); } // switch break; case MIN_STATE: currentLiteral.append(c); if (c >= '0' && c <= '9') formattingInfo.min = formattingInfo.min * 10 + (c - '0'); else if (c == '.') state = DOT_STATE; else { finalizeConverter(c); } break; case DOT_STATE: currentLiteral.append(c); if (c >= '0' && c <= '9') { formattingInfo.max = c - '0'; state = MAX_STATE; } else { System.err.println("Error occured in position " + i + ".\n Was expecting digit, instead got char \"" + c + "\"."); state = LITERAL_STATE; } break; case MAX_STATE: currentLiteral.append(c); if (c >= '0' && c <= '9') formattingInfo.max = formattingInfo.max * 10 + (c - '0'); else { finalizeConverter(c); state = LITERAL_STATE; } break; } // switch } // while if (currentLiteral.length() != 0) { addToList(new LiteralPatternConverter(currentLiteral.toString())); //LogLog.debug("Parsed LITERAL converter: \""+currentLiteral+"\"."); } return head; } protected void finalizeConverter(char c) { PatternConverter pc = null; switch (c) { case 'c': pc = new CategoryPatternConverter(formattingInfo, extractPrecisionOption()); //LogLog.debug("CATEGORY converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'C': pc = new ClassNamePatternConverter(formattingInfo, extractPrecisionOption()); //LogLog.debug("CLASS_NAME converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'd': String dateFormatStr = AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT; DateFormat df; String dOpt = extractOption(); if (dOpt != null) dateFormatStr = dOpt; if (dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.ISO8601_DATE_FORMAT)) df = new ISO8601DateFormat(); else if (dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.ABS_TIME_DATE_FORMAT)) df = new AbsoluteTimeDateFormat(); else if (dateFormatStr.equalsIgnoreCase( AbsoluteTimeDateFormat.DATE_AND_TIME_DATE_FORMAT)) df = new DateTimeDateFormat(); else { try { df = new SimpleDateFormat(dateFormatStr); } catch (IllegalArgumentException e) { System.err.println("Could not instantiate SimpleDateFormat with " + dateFormatStr + ", ex=" + e.getMessage()); df = new ISO8601DateFormat(); } } pc = new DatePatternConverter(formattingInfo, df); //LogLog.debug("DATE converter {"+dateFormatStr+"}."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'F': pc = new LocationPatternConverter(formattingInfo, FILE_LOCATION_CONVERTER); //LogLog.debug("File name converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'l': pc = new LocationPatternConverter(formattingInfo, FULL_LOCATION_CONVERTER); //LogLog.debug("Location converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'L': pc = new LocationPatternConverter(formattingInfo, LINE_LOCATION_CONVERTER); //LogLog.debug("LINE NUMBER converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'm': pc = new BasicPatternConverter(formattingInfo, MESSAGE_CONVERTER); //LogLog.debug("MESSAGE converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'M': pc = new LocationPatternConverter(formattingInfo, METHOD_LOCATION_CONVERTER); //LogLog.debug("METHOD converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'p': pc = new BasicPatternConverter(formattingInfo, LEVEL_CONVERTER); //LogLog.debug("LEVEL converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 'r': pc = new BasicPatternConverter(formattingInfo, RELATIVE_TIME_CONVERTER); //LogLog.debug("RELATIVE time converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; case 't': pc = new BasicPatternConverter(formattingInfo, THREAD_CONVERTER); //LogLog.debug("THREAD converter."); //formattingInfo.dump(); currentLiteral.setLength(0); break; /*case 'u': if(i < patternLength) { char cNext = pattern.charAt(i); if(cNext >= '0' && cNext <= '9') { pc = new UserFieldPatternConverter(formattingInfo, cNext - '0'); LogLog.debug("USER converter ["+cNext+"]."); formattingInfo.dump(); currentLiteral.setLength(0); i++; } else System.err.println("Unexpected char" +cNext+" at position "+i); } break;*/ case 'x': case 'z': pc = new BasicPatternConverter(formattingInfo, NDC_CONVERTER); //LogLog.debug("NDC converter."); currentLiteral.setLength(0); break; case 'X': case 'Z': String xOpt = extractOption(); pc = new MDCPatternConverter(formattingInfo, xOpt); currentLiteral.setLength(0); break; default: System.err.println("Unexpected char [" + c + "] at position " + i + " in conversion patterrn."); pc = new LiteralPatternConverter(currentLiteral.toString()); currentLiteral.setLength(0); } addConverter(pc); } protected void addConverter(PatternConverter pc) { currentLiteral.setLength(0); // Add the pattern converter to the list. addToList(pc); // Next pattern is assumed to be a literal. state = LITERAL_STATE; // Reset formatting info formattingInfo.reset(); } // --------------------------------------------------------------------- // PatternConverters // --------------------------------------------------------------------- private static class BasicPatternConverter extends PatternConverter { int type; BasicPatternConverter(FormattingInfo formattingInfo, int type) { super(formattingInfo); this.type = type; } public String convert(LogRecord event) { switch (type) { case RELATIVE_TIME_CONVERTER: return (Long.toString(event.getMillis() - startTime)); case THREAD_CONVERTER: StringBuffer tmp = new StringBuffer("tid("); tmp.append(event.getThreadID()); tmp.append(')'); return tmp.toString(); case THREAD_NAME_CONVERTER: // @todo figure how to map the thread id to its name return "null"; case LEVEL_CONVERTER: return event.getLevel().toString(); case NDC_CONVERTER: // For now rely on the thread local return NDC.get(); case MESSAGE_CONVERTER: { return event.getMessage(); } default: return null; } } } private static class LiteralPatternConverter extends PatternConverter { private String literal; LiteralPatternConverter(String value) { literal = value; } public final void format(StringBuffer sbuf, LogRecord event) { sbuf.append(literal); } public String convert(LogRecord event) { return literal; } } private static class DatePatternConverter extends PatternConverter { private DateFormat df; private Date date; DatePatternConverter(FormattingInfo formattingInfo, DateFormat df) { super(formattingInfo); date = new Date(); this.df = df; } public String convert(LogRecord event) { date.setTime(event.getMillis()); String converted = null; try { converted = df.format(date); } catch (Exception ex) { System.err.println("Error occured while converting date, " + ex.getMessage()); } return converted; } } private static class MDCPatternConverter extends PatternConverter { private String key; MDCPatternConverter(FormattingInfo formattingInfo, String key) { super(formattingInfo); this.key = key; } public String convert(LogRecord event) { // For now, we rely on the thread local Object val = MDC.get(key); if (val == null) { return null; } else { return val.toString(); } } } private class LocationPatternConverter extends PatternConverter { int type; LocationPatternConverter(FormattingInfo formattingInfo, int type) { super(formattingInfo); this.type = type; } public String convert(LogRecord event) { switch (type) { case FULL_LOCATION_CONVERTER: return "Class: " + event.getSourceClassName() + "." + event.getSourceMethodName(); case METHOD_LOCATION_CONVERTER: return event.getSourceMethodName(); case LINE_LOCATION_CONVERTER: return "0"; case FILE_LOCATION_CONVERTER: return event.getSourceClassName(); default: return null; } } } private static abstract class NamedPatternConverter extends PatternConverter { int precision; NamedPatternConverter(FormattingInfo formattingInfo, int precision) { super(formattingInfo); this.precision = precision; } abstract String getFullyQualifiedName(LogRecord event); public String convert(LogRecord event) { String n = getFullyQualifiedName(event); if (precision <= 0) return n; else { int len = n.length(); // We substract 1 from 'len' when assigning to 'end' to avoid out of // bounds exception in return r.substring(end+1, len). This can happen if // precision is 1 and the category name ends with a dot. int end = len - 1; for (int i = precision; i > 0; i--) { end = n.lastIndexOf('.', end - 1); if (end == -1) return n; } return n.substring(end + 1, len); } } } private class ClassNamePatternConverter extends NamedPatternConverter { ClassNamePatternConverter(FormattingInfo formattingInfo, int precision) { super(formattingInfo, precision); } String getFullyQualifiedName(LogRecord event) { return event.getSourceClassName(); } } private class CategoryPatternConverter extends NamedPatternConverter { CategoryPatternConverter(FormattingInfo formattingInfo, int precision) { super(formattingInfo, precision); } String getFullyQualifiedName(LogRecord event) { return event.getLoggerName(); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKMDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKMDCP0000644000175000017500000000361710644524477032660 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.util.HashMap; import java.util.Map; import org.jboss.logging.MDCProvider; /** * MDC implementation for JDK logging. * * @author Jason T. Greene */ public class JDKMDCProvider implements MDCProvider { private ThreadLocal> map = new ThreadLocal>(); public Object get(String key) { return map.get() == null ? null : map.get().get(key); } public Map getMap() { return map.get(); } public void put(String key, Object value) { Map map = this.map.get(); if (map == null) { map = new HashMap(); this.map.set(map); } map.put(key, value); } public void remove(String key) { Map map = this.map.get(); if (map == null) return; map.remove(key); } }././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKLogManager.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKLogM0000644000175000017500000001172310470642610032753 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.util.logging.LogManager; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.File; import java.net.URL; import org.jboss.logging.jdk.xml.DOMConfigurator; /** @author Scott.Stark@jboss.org @version $Revision: 1958 $ */ public class JDKLogManager extends LogManager { private static final String DEFAULT_CONFIG_PROPS = "jdklogger.properties"; private static final String DEFAULT_CONFIG_XML = "jdklogger.xml"; public JDKLogManager() { } /** * Overriden to attempt to load the java.util.logging.config.file property value * as a classpath resource before treating this as a file as is done by the * standard jdk LogManager. * * In additional, if the resource ends in a .xml suffix, the * org.jboss.logging.jdk.xml.DOMConfigurator is used to parse a logging * configuration that is similar to the 1.2 log4j.xml format. * * @throws IOException * @throws SecurityException */ public void readConfiguration() throws IOException, SecurityException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String config = SecurityActions.getProperty("java.util.logging.config.file"); URL configURL = null; if( config == null ) { // Search for a default configuration on the classpath config = DEFAULT_CONFIG_XML; configURL = loader.getResource(DEFAULT_CONFIG_XML); if( configURL == null ) { config = DEFAULT_CONFIG_PROPS; configURL = loader.getResource(DEFAULT_CONFIG_PROPS); } // Search for a default configuration as a file if( configURL == null ) { config = DEFAULT_CONFIG_XML; File test = new File(DEFAULT_CONFIG_XML); if( test.exists() == true ) configURL = test.toURL(); else { config = DEFAULT_CONFIG_PROPS; test = new File(DEFAULT_CONFIG_PROPS); if( test.exists() == true ) configURL = test.toURL(); } // If there still is no file, throw an exception if( configURL == null ) { String msg = "No java.util.logging.config.file specified, and neither the default " + DEFAULT_CONFIG_XML + " or " + DEFAULT_CONFIG_PROPS + " was found"; throw new FileNotFoundException(msg); } } } // If there was a config specified, try to load it from the classpath if( configURL == null ) configURL = loader.getResource(config); InputStream is = null; if( configURL == null ) { // If the config was not on the classpath try it as a file InputStream in = new FileInputStream(config); is = new BufferedInputStream(in); } else { // Use the located config URL is = configURL.openStream(); } // Is this an xml file? boolean isXML = config.endsWith(".xml"); try { if( isXML ) { DOMConfigurator.configure(is); } else { // Parse the standard jdk properties file format super.readConfiguration(is); } } finally { if( is != null ) is.close(); } } /** * Ignore the reset operation because the default behavior by the jdk LogManager * is to close all handlers. This results in loss of logging information during * the jdk shutdown. The jboss kernel can call doReset to cause a reset of the * logging layer as the last step in shutdown. * * @see #doReset() to force a reset */ public void reset() { } /** * Invokes the LogManager.reset() method. */ public void doReset() { super.reset(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JBossLevel.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JBossLe0000644000175000017500000000161510774202215033064 0ustar twernertwernerpackage org.jboss.logging.jdk; import java.util.logging.Level; /** * */ public final class JBossLevel extends Level { /** The serialVersionUID */ private static final long serialVersionUID = 1L; protected JBossLevel(final String name, final int value) { super(name, value); } protected JBossLevel(final String name, final int value, final String resourceBundleName) { super(name, value, resourceBundleName); } public static final JBossLevel FATAL = new JBossLevel("FATAL", 1100); public static final JBossLevel ERROR = new JBossLevel("ERROR", 1000); public static final JBossLevel WARN = new JBossLevel("WARN", 900); @SuppressWarnings("hiding") public static final JBossLevel INFO = new JBossLevel("INFO", 800); public static final JBossLevel DEBUG = new JBossLevel("DEBUG", 500); public static final JBossLevel TRACE = new JBossLevel("TRACE", 400); } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JBossJDKLogManager.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JBossJD0000644000175000017500000000403610505507604033023 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.util.logging.LogManager; /** * A simple extension to the default JDK LogManager that overrides the reset * call to a noop to avoid the current behavior of the LogManager installing * a shutdown hook which calls reset. The problem with this behavior is that * all usage of the logging api during shutdown produces no output. * * The #doReset() method can be called after the jboss shutdown hook operates * to allow the logging layer to cleanup while still allowing jboss components * to use the jdk logging layer. * * Install using -Djava.util.logging.manager=org.jboss.logging.JBossJDKLogManager * * @see LogManager * * @author Scott.Stark@jboss.org * @version $Revision: 2054 $ */ public class JBossJDKLogManager extends LogManager { /** * Ignore the reset operation * * @see #doReset() to force a reset */ public void reset() { } /** * Invokes the LogManager.reset() method. */ public void doReset() { super.reset(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKNDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDKNDCP0000644000175000017500000000713510774202215032643 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.util.ArrayList; import java.util.EmptyStackException; import org.jboss.logging.NDCProvider; /** * NDC implementation for JDK logging * * @author Jason T. Greene */ public class JDKNDCProvider implements NDCProvider { private class ArrayStack extends ArrayList { private static final long serialVersionUID = -8520038422243642840L; public E pop() { int size = size(); if (size == 0) throw new EmptyStackException(); return remove(size - 1); } public E peek() { int size = size(); if (size == 0) throw new EmptyStackException(); return get(size - 1); } public void push(E val) { add(val); } public void setSize(int newSize) { int size = size(); if (newSize >= size || newSize < 0) return; removeRange(newSize, size); } } private class Entry { private String merged; private String current; public Entry(String current) { this.merged = current; this.current = current; } public Entry(Entry parent, String current) { this.merged = parent.merged + ' ' + current; this.current = current; } } private ThreadLocal> stack = new ThreadLocal>(); public void clear() { ArrayStack stack = this.stack.get(); if (stack != null) stack.clear(); } public String get() { ArrayStack stack = this.stack.get(); return stack == null || stack.isEmpty() ? null : stack.peek().merged; } public int getDepth() { ArrayStack stack = this.stack.get(); return stack == null ? 0 : stack.size(); } public String peek() { ArrayStack stack = this.stack.get(); return stack == null || stack.isEmpty() ? "" : stack.peek().current; } public String pop() { ArrayStack stack = this.stack.get(); return stack == null || stack.isEmpty() ? "" : stack.pop().current; } public void push(String message) { ArrayStack stack = this.stack.get(); if (stack == null) { stack = new ArrayStack(); this.stack.set(stack); } stack.push(stack.isEmpty() ? new Entry(message) : new Entry(stack.peek(), message)); } public void setMaxDepth(int maxDepth) { ArrayStack stack = this.stack.get(); if (stack != null) stack.setSize(maxDepth); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/SecurityActions.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/Securit0000644000175000017500000000555110774202215033204 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.security.AccessController; import java.security.PrivilegedAction; /** * @author Scott.Stark@jboss.org * @version $Revision: 2786 $ */ class SecurityActions { interface Actions { Actions NON_PRIVILEGED = new Actions() { public String getProperty(final String name) { return System.getProperty(name); } public String getProperty(final String name, final String def) { return System.getProperty(name, def); } }; Actions PRIVILEGED = new Actions() { public String getProperty(final String name) { return AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(name); } }); } public String getProperty(final String name, final String def) { return AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(name, def); } }); } }; String getProperty(String name); String getProperty(String name, String def); } static String getProperty(String name) { String value; if( System.getSecurityManager() == null ) value = Actions.NON_PRIVILEGED.getProperty(name); else value = Actions.PRIVILEGED.getProperty(name); return value; } static String getProperty(String name, String def) { String value; if( System.getSecurityManager() == null ) value = Actions.NON_PRIVILEGED.getProperty(name, def); else value = Actions.PRIVILEGED.getProperty(name, def); return value; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDK14LoggerPlugin.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/jdk/JDK14Lo0000644000175000017500000000713410774202215032635 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.jdk; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.LogRecord; import org.jboss.logging.LoggerPlugin; import org.jboss.logging.MDCProvider; import org.jboss.logging.MDCSupport; import org.jboss.logging.NDCProvider; import org.jboss.logging.NDCSupport; /** An example LoggerPlugin which uses the JDK java.util.logging framework. * * @author Scott.Stark@jboss.org * @version $Revison:$ */ public class JDK14LoggerPlugin implements LoggerPlugin, MDCSupport, NDCSupport { private Logger log; private String name; public void init(String name) { this.name = name; log = Logger.getLogger(name); } private void doLog(Level level, Object message, Throwable t) { LogRecord record = new LogRecord(level, message.toString()); record.setLoggerName(name); record.setThrown(t); record.setSourceMethodName(null); // prevent expensive, yet pointless, lookup log.log(record); } public boolean isTraceEnabled() { return log.isLoggable(JBossLevel.TRACE); } public void trace(Object message) { doLog(JBossLevel.TRACE, message, null); } public void trace(Object message, Throwable t) { doLog(JBossLevel.TRACE, message, t); } @Deprecated public boolean isDebugEnabled() { return log.isLoggable(JBossLevel.DEBUG); } public void debug(Object message) { doLog(JBossLevel.DEBUG, message, null); } public void debug(Object message, Throwable t) { doLog(JBossLevel.DEBUG, message, t); } @Deprecated public boolean isInfoEnabled() { return log.isLoggable(JBossLevel.INFO); } public void info(Object message) { doLog(JBossLevel.INFO, message, null); } public void info(Object message, Throwable t) { doLog(JBossLevel.INFO, message, t); } public void warn(Object message) { doLog(JBossLevel.WARN, message, null); } public void warn(Object message, Throwable t) { doLog(JBossLevel.WARN, message, t); } public void error(Object message) { doLog(JBossLevel.ERROR, message, null); } public void error(Object message, Throwable t) { doLog(JBossLevel.ERROR, message, t); } public void fatal(Object message) { doLog(JBossLevel.FATAL, message, null); } public void fatal(Object message, Throwable t) { doLog(JBossLevel.FATAL, message, t); } public NDCProvider getNDCProvider() { return new JDKNDCProvider(); } public MDCProvider getMDCProvider() { return new JDKMDCProvider(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/JBossJDKLogManager.javalibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/main/java/org/jboss/logging/JBossJDKLog0000644000175000017500000000244510506032725033030 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * Noop compatibility class that links to * org.jboss.logging.jdk.JBossJDKLogManager * @author Scott.Stark@jboss.org * @version $Revision:$ */ public class JBossJDKLogManager extends org.jboss.logging.jdk.JBossJDKLogManager { } libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/etc/0000755000175000017500000000000011105642371024436 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/src/etc/default.mf0000644000175000017500000000067110470642610026412 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @specification.title@ Specification-Version: @specification.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @implementation.title@ Implementation-URL: @implementation.url@ Implementation-Version: @implementation.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/.classpath0000644000175000017500000000047610776674035025105 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/.project0000644000175000017500000000052510776674035024564 0ustar twernertwerner jboss-logging-jdk JBoss Logging JDK Implementation org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/.settings/0000755000175000017500000000000011105642371025012 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-jdk/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000031410774162660032003 0ustar twernertwerner#Mon Mar 31 14:44:19 CEST 2008 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/projectSet.psf0000644000175000017500000000040210776674035025743 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-jdk/pom.xml0000644000175000017500000000520010776674375024434 0ustar twernertwerner org.jboss jboss-parent 3 4.0.0 org.jboss.logging jboss-logging-jdk 2.0.6-SNAPSHOT jar JBoss Logging JDK http://www.jboss.org JBoss Logging JDK Implementation scm:svn:https://svn.jboss.org/repos/common/common-logging-jdk/trunk/ maven-release-plugin https://svn.jboss.org/repos/common/common-logging-jdk/tags jboss.maven-plugins jboss-deploy-maven-plugin repository.jboss.org JBoss Repository default http://repository.jboss.org/maven2/ false snapshots.jboss.org JBoss Snapshot Repository default http://snapshots.jboss.org/maven2/ false true org.jboss.logging jboss-logging-spi 2.0.5.GA org.jboss jboss-common-core 2.2.5.GA true libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/0000755000175000017500000000000011105642375023347 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/0000755000175000017500000000000011105642375024136 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/0000755000175000017500000000000011105642374025061 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/0000755000175000017500000000000011105642374026002 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/0000755000175000017500000000000011105642374026571 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/0000755000175000017500000000000011105642374027711 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/0000755000175000017500000000000011105642375031340 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/0000755000175000017500000000000011105642374032356 5ustar twernertwerner././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log4jNDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log0000644000175000017500000000327410774177547033050 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.log4j; import org.apache.log4j.NDC; import org.jboss.logging.NDCProvider; /** * Log4j implementation of NDCProvider, delegates to log4j NDC. * * @author Jason T. Greene */ public class Log4jNDCProvider implements NDCProvider { public void clear() { NDC.clear(); } public String get() { return NDC.get(); } public int getDepth() { return NDC.getDepth(); } public String peek() { return NDC.peek(); } public String pop() { return NDC.pop(); } public void push(String message) { NDC.push(message); } public void setMaxDepth(int maxDepth) { NDC.setMaxDepth(maxDepth); } }././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log4jLoggerPlugin.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log0000644000175000017500000002004410774177547033042 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.log4j; import org.apache.log4j.Category; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Priority; import org.jboss.logging.Logger; import org.jboss.logging.LoggerPlugin; import org.jboss.logging.MDCProvider; import org.jboss.logging.MDCSupport; import org.jboss.logging.NDCProvider; import org.jboss.logging.NDCSupport; /** * Delegate for org.jboss.logging.Logger logging to log4j. Body of implementation * mainly copied from old Logger implementation. * * @see org.jboss.logging.Logger * @see org.jboss.logging.LoggerPlugin * * @author Sacha Labourey. * @author Jason T. Greene * @version $Revision: 2785 $ */ public class Log4jLoggerPlugin implements LoggerPlugin, NDCSupport, MDCSupport { // Constants ----------------------------------------------------- /** * Fully qualified classname for this class so Log4J locationinfo will be * correct */ private static final String FQCN = Logger.class.getName(); // Attributes ---------------------------------------------------- /** The Log4j delegate logger. */ private transient org.apache.log4j.Logger log; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public Log4jLoggerPlugin () { } public void init (String name) { log = LogManager.getLogger(name); } // Public -------------------------------------------------------- public Category getCategory() { return log; } /** * Exposes the delegate Log4j Logger. * * @return the underlying logger */ public org.apache.log4j.Logger getLogger() { return log; } // LoggerPlugin implementation ---------------------------------------------- public boolean isTraceEnabled() { Level l = Level.TRACE; if (log.isEnabledFor(l) == false) return false; return l.isGreaterOrEqual(log.getEffectiveLevel()); } /** * Issue a log msg with a level of TRACE. * Invokes log.log(Level.TRACE, message); */ public void trace(Object message) { log.log(FQCN, Level.TRACE, message, null); } /** * Issue a log msg and throwable with a level of TRACE. * Invokes log.log(Level.TRACE, message, t); */ public void trace(Object message, Throwable t) { log.log(FQCN, Level.TRACE, message, t); } /** * Check to see if the TRACE level is enabled for this logger. * * @return true if a {@link #trace(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ @Deprecated public boolean isDebugEnabled() { Level l = Level.DEBUG; if (log.isEnabledFor(l) == false) return false; return l.isGreaterOrEqual(log.getEffectiveLevel()); } /** * Issue a log msg with a level of DEBUG. * Invokes log.log(Level.DEBUG, message); */ public void debug(Object message) { log.log(FQCN, Level.DEBUG, message, null); } /** * Issue a log msg and throwable with a level of DEBUG. * Invokes log.log(Level.DEBUG, message, t); */ public void debug(Object message, Throwable t) { log.log(FQCN, Level.DEBUG, message, t); } /** * Check to see if the INFO level is enabled for this logger. * * @return true if a {@link #info(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ @Deprecated public boolean isInfoEnabled() { Level l = Level.INFO; if (log.isEnabledFor(l) == false) return false; return l.isGreaterOrEqual(log.getEffectiveLevel()); } /** * Issue a log msg with a level of INFO. * Invokes log.log(Level.INFO, message); */ public void info(Object message) { log.log(FQCN, Level.INFO, message, null); } /** * Issue a log msg and throwable with a level of INFO. * Invokes log.log(Level.INFO, message, t); */ public void info(Object message, Throwable t) { log.log(FQCN, Level.INFO, message, t); } /** * Issue a log msg with a level of WARN. * Invokes log.log(Level.WARN, message); */ public void warn(Object message) { log.log(FQCN, Level.WARN, message, null); } /** * Issue a log msg and throwable with a level of WARN. * Invokes log.log(Level.WARN, message, t); */ public void warn(Object message, Throwable t) { log.log(FQCN, Level.WARN, message, t); } /** * Issue a log msg with a level of ERROR. * Invokes log.log(Level.ERROR, message); */ public void error(Object message) { log.log(FQCN, Level.ERROR, message, null); } /** * Issue a log msg and throwable with a level of ERROR. * Invokes log.log(Level.ERROR, message, t); */ public void error(Object message, Throwable t) { log.log(FQCN, Level.ERROR, message, t); } /** * Issue a log msg with a level of FATAL. * Invokes log.log(Level.FATAL, message); */ public void fatal(Object message) { log.log(FQCN, Level.FATAL, message, null); } /** * Issue a log msg and throwable with a level of FATAL. * Invokes log.log(Level.FATAL, message, t); */ public void fatal(Object message, Throwable t) { log.log(FQCN, Level.FATAL, message, t); } /** * Issue a log msg with the given level. * Invokes log.log(p, message); * * @param p the priority * @param message the message * @deprecated Use Level versions. */ public void log(Priority p, Object message) { log.log(FQCN, p, message, null); } /** * Issue a log msg with the given priority. * Invokes log.log(p, message, t); * * * @param p the priority * @param message the message * @param t the throwable * @deprecated Use Level versions. */ public void log(Priority p, Object message, Throwable t) { log.log(FQCN, p, message, t); } /** * Issue a log msg with the given level. * Invokes log.log(l, message); * * @param l the level * @param message the message */ public void log(Level l, Object message) { log.log(FQCN, l, message, null); } /** * Issue a log msg with the given level. * Invokes log.log(l, message, t); * * @param l the level * @param message the message * @param t the throwable */ public void log(Level l, Object message, Throwable t) { log.log(FQCN, l, message, t); } public NDCProvider getNDCProvider() { return new Log4jNDCProvider(); } public MDCProvider getMDCProvider() { return new Log4jMDCProvider(); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log4jMDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/log4j/Log0000644000175000017500000000310510644524367033031 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.log4j; import java.util.Map; import org.apache.log4j.MDC; import org.jboss.logging.MDCProvider; /** * Log4j implementation of MDCProvider. * * @author Jason T. Greene */ public class Log4jMDCProvider implements MDCProvider { public Object get(String key) { return MDC.get(key); } @SuppressWarnings("unchecked") public Map getMap() { return MDC.getContext(); } public void put(String key, Object val) { MDC.put(key, val); } public void remove(String key) { MDC.remove(key); } }libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/filter/0000755000175000017500000000000011105642374032624 5ustar twernertwerner././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/filter/TCLFilter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/filter/TC0000644000175000017500000001206110774177547033075 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.filter; import java.lang.reflect.Method; import java.net.URL; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.jboss.util.collection.WeakSet; /** An appender filter that accepts log events based on whether the thread context class loader has a classpath URL that has the DeployURL attribute as a substring. A sample usage would be: @author Scott.Stark@jboss.org @version $Revision: 2785 $ */ public class TCLFilter extends Filter { /** The set of TCLs seen to match DeployURL */ private WeakSet matchSet = new WeakSet(); /** The set of TCLs seen to not match DeployURL */ private WeakSet missSet = new WeakSet(); /** The deployment URL string fragment to match against */ private String deployURL; /** Whether a match should return ACCEPT or DENY */ private boolean acceptOnMatch = true; public boolean isAcceptOnMatch() { return acceptOnMatch; } public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } public String getDeployURL() { return deployURL; } public void setDeployURL(String deployURL) { this.deployURL = deployURL; } public int decide(LoggingEvent event) { int ok = Filter.NEUTRAL; if( acceptOnMatch == true ) { if( isMatchingTCL() ) ok = Filter.ACCEPT; } else { if( isMatchingTCL() ) ok = Filter.DENY; } return ok; } /** Start with the current thread context class loader * @return true if the caller tcl has a url matching our deployURL */ private boolean isMatchingTCL() { ClassLoader tcl = Thread.currentThread().getContextClassLoader(); if( matchSet.contains(tcl) ) return true; if( missSet.contains(tcl) ) return false; // Search the class loader URLs for a match ClassLoader cl = tcl; boolean match = false; while( cl != null ) { URL[] urls = getClassLoaderURLs(cl); for(int n = 0; n < urls.length; n ++) { URL u = urls[n]; String file = u.getFile(); if( file.indexOf(deployURL) > 0 ) { match = true; break; } } cl = cl.getParent(); } if( match == true ) matchSet.add(tcl); else missSet.add(tcl); return match; } /** Use reflection to access a URL[] getURLs method so that non-URLClassLoader class loaders that support this method can provide info. */ private static URL[] getClassLoaderURLs(ClassLoader cl) { URL[] urls = {}; try { Class returnType = urls.getClass(); Class[] parameterTypes = {}; Method getURLs = cl.getClass().getMethod("getURLs", parameterTypes); if( returnType.isAssignableFrom(getURLs.getReturnType()) ) { Object[] args = {}; urls = (URL[]) getURLs.invoke(cl, args); } if( urls == null || urls.length == 0 ) { getURLs = cl.getClass().getMethod("getClasspath", parameterTypes); if( returnType.isAssignableFrom(getURLs.getReturnType()) ) { Object[] args = {}; urls = (URL[]) getURLs.invoke(cl, args); } } } catch(Exception ignore) { } return urls; } } libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/0000755000175000017500000000000011105642375032655 5ustar twernertwerner././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/ThreadMDCConverter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/Th0000644000175000017500000000366410774177547033203 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.layout; import org.apache.log4j.MDC; import org.apache.log4j.helpers.FormattingInfo; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.spi.LoggingEvent; /** A PatternConverter that uses the current thread MDC rather than the * LoggingEvent MDC value. * * @author Scott.Stark@jboss.org * @version $Revision: 2785 $ */ public class ThreadMDCConverter extends PatternConverter { private String key; /** Creates a new instance of ThreadMDCPatternConverter * @param formattingInfo the formatting info * @param key the key */ public ThreadMDCConverter(FormattingInfo formattingInfo, String key) { super(formattingInfo); this.key = key; } protected String convert(LoggingEvent loggingEvent) { Object val = MDC.get(key); String strVal = null; if( val != null ) strVal = val.toString(); return strVal; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/ThreadNDCConverter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/Th0000644000175000017500000000353610774177547033201 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.layout; import org.apache.log4j.NDC; import org.apache.log4j.helpers.FormattingInfo; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.spi.LoggingEvent; /** A PatternConverter that uses the current thread NDC rather than the * LoggingEvent NDC value. * * @author Scott.Stark@jboss.org * @version $Revision: 2785 $ */ public class ThreadNDCConverter extends PatternConverter { /** Creates a new instance of ThreadMDCPatternConverter * @param formattingInfo the formatting info */ public ThreadNDCConverter(FormattingInfo formattingInfo) { super(formattingInfo); } protected String convert(LoggingEvent loggingEvent) { Object val = NDC.get(); String strVal = null; if( val != null ) strVal = val.toString(); return strVal; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/PatternParserEx.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/Pa0000644000175000017500000000562410774177547033166 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.layout; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.helpers.PatternParser; /** A subclass of the log4j PatternParser that add the following conversion characters:

* @author Scott.Stark@jboss.org * @version $Revision: 2785 $ */ public class PatternParserEx extends PatternParser { /** Creates a new instance of PatternParser * @param pattern the patatern */ public PatternParserEx(String pattern) { super(pattern); } protected void finalizeConverter(char c) { PatternConverter pc = null; switch(c) { case 'z': pc = new ThreadNDCConverter(formattingInfo); currentLiteral.setLength(0); break; case 'Z': String key = extractOption(); pc = new ThreadMDCConverter(formattingInfo, key); currentLiteral.setLength(0); break; default: super.finalizeConverter(c); return; } addConverter(pc); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/PatternLayout.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/layout/Pa0000644000175000017500000000445310470642610033142 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.layout; import org.apache.log4j.helpers.PatternParser; /** A subclass of the log4j PatternLayout that add the following conversion characters:

Conversion Character Effect
z Used to output current thread NDC value. This can be used to obtain an NDC to augment any NDC associated with the LoggingEvent. This might be necessary if the LoggingEvent has been serialized between VMs.
Z Used to output current thread MDC value. This can be used to obtain an MDC to augment any MDC associated with the LoggingEvent. This might be necessary if the LoggingEvent has been serialized between VMs. The Z conversion character must be followed by the key for the map placed between braces, as in %Z{theKey} where theKey is the key. The value in the MDC corresponding to the key will be output.
* @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class PatternLayout extends org.apache.log4j.PatternLayout { protected PatternParser createPatternParser(String pattern) { return new PatternParserEx(pattern); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/XLevel.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/XLevel.ja0000644000175000017500000001021110774177547033065 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import org.apache.log4j.Level; /** * Provides custom extention levels for use with the Log4j logging framework. *

* Adds a trace level that is below the standard Log4j DEBUG level. *

* This is a custom level that is 100 below the {@link Level#TRACE_INT} * and represents a lower level useful for logging events that should only * be displayed when deep debugging is required. * * @see org.apache.log4j.Level * @deprecated as log4j 1.2.14 has a native TRACE level * * @author Scott Stark * @version $Revision: 2785 $ */ public class XLevel extends Level { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The integer representation of the level, ({@link Level#TRACE_INT} - 100) */ @SuppressWarnings("hiding") public static final int TRACE_INT = Level.TRACE_INT - 100; /** The string name of the trace level. */ public static final String TRACE_STR = "TRACE"; /** The TRACE level object singleton */ @SuppressWarnings("hiding") public static final XLevel TRACE = new XLevel(TRACE_INT, TRACE_STR, 7); /** * Construct a XLevel. * * @param level the level * @param strLevel ??? * @param syslogEquiv the system log equivalent */ protected XLevel(final int level, final String strLevel, final int syslogEquiv) { super(level, strLevel, syslogEquiv); } ///////////////////////////////////////////////////////////////////////// // Factory Methods // ///////////////////////////////////////////////////////////////////////// /** * Convert an integer passed as argument to a level. If the conversion * fails, then this method returns the specified default. * * @return the Level object for name if one exists, defaultLevel otherwize. */ public static Level toLevel(final String name, final Level defaultLevel) { if (name == null) return defaultLevel; String upper = name.toUpperCase(); if (upper.equals(TRACE_STR)) { return TRACE; } return Level.toLevel(name, defaultLevel); } /** * Convert an integer passed as argument to a level. * * @return the Level object for name if one exists */ public static Level toLevel(final String name) { return toLevel(name, TRACE); } /** * Convert an integer passed as argument to a priority. If the conversion * fails, then this method returns the specified default. * @return the Level object for i if one exists, defaultLevel otherwize. */ public static Level toLevel(int i) { return toLevel(i, TRACE); } /** * Convert an integer passed as argument to a level. If the conversion * fails, then this method returns the specified default. * * @return the Level object for i if one exists, defaultLevel otherwize. */ public static Level toLevel(final int i, final Level defaultLevel) { Level p; if (i == TRACE_INT) p = TRACE; else p = Level.toLevel(i); return p; } } libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/0000755000175000017500000000000011105642375032315 5ustar twernertwerner././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/OnlyOnceErrorHandler.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Only0000644000175000017500000000622210470642610033157 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.PrintStream; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.Logger; import org.apache.log4j.Appender; /** The OnlyOnceErrorHandler implements log4j's default error handling policy which consists of emitting a message for the first error in an appender and ignoring all following errors.

The error message is printed on the specified print stream.

This policy aims at protecting an otherwise working application from being flooded with error messages when logging fails. @author Ceki Gülcü @author Adrian Brock (adrian@jboss.org); @since 0.9.0 */ public class OnlyOnceErrorHandler implements ErrorHandler { final String WARN_PREFIX = "log4j warning: "; final String ERROR_PREFIX = "log4j error: "; boolean firstTime = true; static PrintStream output = System.err; public static void setOutput(PrintStream out) { output = out; } /** Does not do anything. */ public void setLogger(Logger logger) { } /** No options to activate. */ public void activateOptions() { } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode) { error(message, e, errorCode, null); } /** Prints the message and the stack trace of the exception on System.err. */ public void error(String message, Exception e, int errorCode, LoggingEvent event) { if(firstTime) { output.println(ERROR_PREFIX + message); e.printStackTrace(output); firstTime = false; } } /** Print a the error message passed as parameter on System.err. */ public void error(String message) { if(firstTime) { output.println(ERROR_PREFIX + message); firstTime = false; } } /** Does not do anything. */ public void setAppender(Appender appender) { } /** Does not do anything. */ public void setBackupAppender(Appender appender) { } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/LoggerPluginWriter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Logg0000755000175000017500000000523010470642610033127 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import org.jboss.logging.LoggerPlugin; /** A subclass of PrintWriter that redirects its output to a LoggerPlugin at * INFO level. The only usecase for this is legacy java apis which require * integration with the logging layer through a Writer. * * @author David Jencks * @author Scott.Stark@jboss.org * @version $Revision: 1958 $ */ public class LoggerPluginWriter extends PrintWriter { /** * * @param logger the logging plugin used to write messages */ public LoggerPluginWriter(final LoggerPlugin logger) { super(new PluginWriter(logger), true); } static class PluginWriter extends Writer { private LoggerPlugin logger; private boolean closed; public PluginWriter(final LoggerPlugin logger) { lock = logger; this.logger = logger; } public void write(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IOException("Called write on closed Writer"); } // Remove the end of line chars while (len > 0 && (cbuf[len - 1] == '\n' || cbuf[len - 1] == '\r')) { len--; } if (len > 0) { logger.info(String.copyValueOf(cbuf, off, len)); } } public void flush() throws IOException { if (closed) { throw new IOException("Called flush on closed Writer"); } } public void close() { closed = true; } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/CategoryStream.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Cate0000644000175000017500000001204410774177547033134 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.IOException; import java.io.PrintStream; import org.apache.log4j.Category; import org.apache.log4j.Priority; /** * A subclass of PrintStream that redirects its output to a log4j Category. * *

This class is used to map PrintStream/PrintWriter oriented logging onto * the log4j Categories. Examples include capturing System.out/System.err * * @deprecated Use {@link LoggerStream} instead. * * @version $Revision: 2785 $ * @author Scott Stark. * @author Jason Dillon */ @SuppressWarnings("deprecation") public class CategoryStream extends PrintStream { /** * Default flag to enable/disable tracing println calls. * from the system property org.jboss.logging.util.CategoryStream.trace * or if not set defaults to false. */ public static final boolean TRACE = getBoolean(CategoryStream.class.getName() + ".trace", false); /** Helper to get boolean value from system property or use default if not set. */ private static boolean getBoolean(String name, boolean defaultValue) { String value = System.getProperty(name, null); if (value == null) return defaultValue; return new Boolean(value).booleanValue(); } private Category category; private Priority priority; private boolean issuedWarning; /** * Redirect logging to the indicated category using Priority.INFO * * @param category the category */ public CategoryStream(final Category category) { this(category, Priority.INFO, System.out); } /** * Redirect logging to the indicated category using the given * priority. The ps is simply passed to super but is not used. * * @param category the category * @param priority the priority * @param ps the print stream */ public CategoryStream(final Category category, final Priority priority, final PrintStream ps) { super(ps); this.category = category; this.priority = priority; } public void println(String msg) { if( msg == null ) msg = "null"; byte[] bytes = msg.getBytes(); write(bytes, 0, bytes.length); } public void println(Object msg) { if( msg == null ) msg = "null"; byte[] bytes = msg.toString().getBytes(); write(bytes, 0, bytes.length); } public void write(byte b) { byte[] bytes = {b}; write(bytes, 0, 1); } private ThreadLocal recursiveCheck = new ThreadLocal(); public void write(byte[] b, int off, int len) { Boolean recursed = recursiveCheck.get(); if (recursed != null && recursed.equals(Boolean.TRUE)) { /* There is a configuration error that is causing looping. Most likely there are two console appenders so just return to prevent spinning. */ if( issuedWarning == false ) { String msg = "ERROR: invalid console appender config detected, console stream is looping"; try { out.write(msg.getBytes()); } catch(IOException ignore) { } issuedWarning = true; } return; } // Remove the end of line chars while( len > 0 && (b[len-1] == '\n' || b[len-1] == '\r') && len > off ) len --; // HACK, something is logging exceptions line by line (including // blanks), but I can't seem to find it, so for now just ignore // empty lines... they aren't very useful. if (len != 0) { String msg = new String(b, off, len); recursiveCheck.set(Boolean.TRUE); if (TRACE) { category.log(priority, msg, new Throwable()); } else { category.log(priority, msg); } recursiveCheck.set(Boolean.FALSE); } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/CategoryWriter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Cate0000644000175000017500000000702110774177547033133 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import org.apache.log4j.Category; import org.apache.log4j.Priority; /** * A subclass of PrintWriter that redirects its output to a log4j Category.

* * This class is used to have something to give api methods that require a * PrintWriter for logging. JBoss-owned classes of this nature generally ignore * the PrintWriter and do their own log4j logging. * * @deprecated Use {@link LoggerWriter} instead. * * @author David Jencks * . * @created August 19, 2001 * @version $$ */ @SuppressWarnings("deprecation") public class CategoryWriter extends PrintWriter { /** * Redirect logging to the indicated category using Priority.INFO * * @param category Description of Parameter */ public CategoryWriter( final Category category ) { this( category, Priority.INFO ); } /** * Redirect logging to the indicated category using the given priority. The * ps is simply passed to super but is not used. * * @param category Description of Parameter * @param priority Description of Parameter */ public CategoryWriter( final Category category, final Priority priority ) { super( new InternalCategoryWriter( category, priority ), true ); } /** * @created August 19, 2001 */ static class InternalCategoryWriter extends Writer { private Category category; private Priority priority; private boolean closed; public InternalCategoryWriter( final Category category, final Priority priority ) { lock = category; //synchronize on this category this.category = category; this.priority = priority; } public void write( char[] cbuf, int off, int len ) throws IOException { if ( closed ) { throw new IOException( "Called write on closed Writer" ); } // Remove the end of line chars while ( len > 0 && ( cbuf[len - 1] == '\n' || cbuf[len - 1] == '\r' ) ) { len--; } if ( len > 0 ) { category.log( priority, String.copyValueOf( cbuf, off, len ) ); } } public void flush() throws IOException { if ( closed ) { throw new IOException( "Called flush on closed Writer" ); } } public void close() { closed = true; } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/LoggerStream.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Logg0000644000175000017500000001155710774177547033160 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.IOException; import java.io.PrintStream; import org.apache.log4j.Logger; import org.apache.log4j.Level; /** * A subclass of PrintStream that redirects its output to a log4j Logger. * *

This class is used to map PrintStream/PrintWriter oriented logging onto * the log4j Categories. Examples include capturing System.out/System.err * * @version $Revision: 2785 $ * @author Scott Stark. * @author Jason Dillon */ public class LoggerStream extends PrintStream { /** * Default flag to enable/disable tracing println calls. * from the system property org.jboss.logging.util.LoggerStream.trace * or if not set defaults to false. */ public static final boolean TRACE = getBoolean(LoggerStream.class.getName() + ".trace", false); /** Helper to get boolean value from system property or use default if not set. */ private static boolean getBoolean(String name, boolean defaultValue) { String value = System.getProperty(name, null); if (value == null) return defaultValue; return new Boolean(value).booleanValue(); } private Logger logger; private Level level; private boolean issuedWarning; /** * Redirect logging to the indicated logger using Level.INFO * * @param logger the logger */ public LoggerStream(final Logger logger) { this(logger, Level.INFO, System.out); } /** * Redirect logging to the indicated logger using the given * level. The ps is simply passed to super but is not used. * * @param logger the logger * @param level the level * @param ps the stream */ public LoggerStream(final Logger logger, final Level level, final PrintStream ps) { super(ps); this.logger = logger; this.level = level; } public void println(String msg) { if( msg == null ) msg = "null"; byte[] bytes = msg.getBytes(); write(bytes, 0, bytes.length); } public void println(Object msg) { if( msg == null ) msg = "null"; byte[] bytes = msg.toString().getBytes(); write(bytes, 0, bytes.length); } public void write(byte b) { byte[] bytes = {b}; write(bytes, 0, 1); } private ThreadLocal recursiveCheck = new ThreadLocal(); public void write(byte[] b, int off, int len) { Boolean recursed = recursiveCheck.get(); if (recursed != null && recursed.equals(Boolean.TRUE)) { /* There is a configuration error that is causing looping. Most likely there are two console appenders so just return to prevent spinning. */ if( issuedWarning == false ) { String msg = "ERROR: invalid console appender config detected, console stream is looping"; try { out.write(msg.getBytes()); } catch(IOException ignore) { } issuedWarning = true; } return; } // Remove the end of line chars while( len > 0 && (b[len-1] == '\n' || b[len-1] == '\r') && len > off ) len --; // HACK, something is logging exceptions line by line (including // blanks), but I can't seem to find it, so for now just ignore // empty lines... they aren't very useful. if (len != 0) { String msg = new String(b, off, len); recursiveCheck.set(Boolean.TRUE); if (TRACE) { logger.log(level, msg, new Throwable()); } else { logger.log(level, msg); } recursiveCheck.set(Boolean.FALSE); } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/LoggerWriter.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/Logg0000644000175000017500000000652410774177547033156 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.util; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import org.apache.log4j.Logger; import org.apache.log4j.Level; /** * A subclass of PrintWriter that redirects its output to a log4j Logger.

* * This class is used to have something to give api methods that require a * PrintWriter for logging. JBoss-owned classes of this nature generally ignore * the PrintWriter and do their own log4j logging. * * @author David Jencks * . * @created August 19, 2001 * @version $$ */ public class LoggerWriter extends PrintWriter { /** * Redirect logging to the indicated logger using Level.INFO * * @param logger Description of Parameter */ public LoggerWriter( final Logger logger ) { this( logger, Level.INFO ); } /** * Redirect logging to the indicated logger using the given level. The * ps is simply passed to super but is not used. * * @param logger Description of Parameter * @param level Description of Parameter */ public LoggerWriter( final Logger logger, final Level level ) { super( new InternalLoggerWriter( logger, level ), true ); } /** * @created August 19, 2001 */ static class InternalLoggerWriter extends Writer { private Logger logger; private Level level; private boolean closed; public InternalLoggerWriter( final Logger logger, final Level level ) { lock = logger; //synchronize on this logger this.logger = logger; this.level = level; } public void write( char[] cbuf, int off, int len ) throws IOException { if ( closed ) { throw new IOException( "Called write on closed Writer" ); } // Remove the end of line chars while ( len > 0 && ( cbuf[len - 1] == '\n' || cbuf[len - 1] == '\r' ) ) { len--; } if ( len > 0 ) { logger.log( level, String.copyValueOf( cbuf, off, len ) ); } } public void flush() throws IOException { if ( closed ) { throw new IOException( "Called flush on closed Writer" ); } } public void close() { closed = true; } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/package.htmllibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/util/pack0000644000175000017500000000152010470642610033150 0ustar twernertwerner

Logging utilties and helpers.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000755000175000017500000000000011105642375033136 5ustar twernertwerner././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/package.htmllibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000644000175000017500000000150310470642610033133 0ustar twernertwerner

Log4j appenders.

Package Specification

Related Documentation

Package Status

  • STABLE

Todo

  • ???
././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/RegexEventEvaluator.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000755000175000017500000000553710774177547033174 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.appender; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.TriggeringEventEvaluator; /** An implementation of the log4j TriggeringEventEvaluator that matches the * LoggingEvent message against the MDB{RegexEventEvaluator} regular * expression. * @author Scott.Stark@jboss.org * @version $Revision: 2785 $ */ public class RegexEventEvaluator implements TriggeringEventEvaluator { /** A cache HashMap of previously compiled REs */ private HashMap regexMap = new HashMap(); /** Lookup the current MDC 'RegexEventEvaluator' to determine the regular * expression context that should be applied to determine if the logging * event should be considered a triggering event. If there is no value * for the 'RegexEventEvaluator' key then no comparision is made. * * @param event the logging event to check * @return true if MDC{RegexEventEvaluator} is a regex expression that * matches the event.getRenderedMessage(), false otherwise. */ public boolean isTriggeringEvent(LoggingEvent event) { String regex = (String) event.getMDC("RegexEventEvaluator"); boolean isTriggeringEvent = false; if( regex != null ) { // Look for a cached regex pattern Pattern re = regexMap.get(regex); if( re == null ) { re = Pattern.compile(regex); regexMap.put(regex, re); } if( re != null ) { String msg = event.getRenderedMessage(); if( msg != null ) { Matcher m = re.matcher(msg); isTriggeringEvent = m.matches(); } } } return isTriggeringEvent; } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/RollingFileAppender.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000644000175000017500000000277010470642610033142 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.appender; /** * An extention of the default Log4j RollingFileAppender which * will make the directory structure for the set log file. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class RollingFileAppender extends org.apache.log4j.RollingFileAppender { public void setFile(final String filename) { FileAppender.Helper.makePath(filename); super.setFile(filename); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/FileAppender.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000644000175000017500000000433210470642610033136 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.appender; import java.io.File; import java.net.URL; import java.net.MalformedURLException; import org.apache.log4j.helpers.LogLog; /** * An extention of the default Log4j FileAppender which * will make the directory structure for the set log file. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class FileAppender extends org.apache.log4j.FileAppender { public void setFile(final String filename) { FileAppender.Helper.makePath(filename); super.setFile(filename); } /** * A helper for FileAppenders. */ public static class Helper { public static void makePath(final String filename) { File dir; try { URL url = new URL(filename.trim()); dir = new File(url.getFile()).getParentFile(); } catch (MalformedURLException e) { dir = new File(filename.trim()).getParentFile(); } if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { LogLog.error("Failed to create directory structure: " + dir); } } } } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/DailyRollingFileAppender.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/appender/0000644000175000017500000000301010470642610033126 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.appender; /** * An extention of the default Log4j DailyRollingFileAppender * which will make the directory structure for the set log file. * * @version $Revision: 1958 $ * @author Jason Dillon */ public class DailyRollingFileAppender extends org.apache.log4j.DailyRollingFileAppender { public void setFile(final String filename) { FileAppender.Helper.makePath(filename); super.setFile(filename); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/Log4jLoggerPlugin.javalibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/main/java/org/jboss/logging/Log4jLogg0000644000175000017500000000244310506033604033047 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * Noop compatibility class that links to * org.jboss.logging.log4j.Log4jLoggerPlugin * @author Scott.Stark@jboss.org * @version $Revision:$ */ public class Log4jLoggerPlugin extends org.jboss.logging.log4j.Log4jLoggerPlugin { } libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/etc/0000755000175000017500000000000011105642375024711 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/src/etc/default.mf0000644000175000017500000000067110470642610026661 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @specification.title@ Specification-Version: @specification.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @implementation.title@ Implementation-URL: @implementation.url@ Implementation-Version: @implementation.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/.classpath0000644000175000017500000000100110776676512025337 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/.project0000644000175000017500000000053110776676512025032 0ustar twernertwerner jboss-logging-log4j JBoss Logging Log4j Implementation org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/.settings/0000755000175000017500000000000011105642375025265 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-log4j/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000031410774162634032253 0ustar twernertwerner#Mon Mar 31 14:43:24 CEST 2008 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/projectSet.psf0000644000175000017500000000040010776676512026212 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-log4j/pom.xml0000644000175000017500000000516310776677111024702 0ustar twernertwerner org.jboss jboss-parent 3 4.0.0 org.jboss.logging jboss-logging-log4j 2.0.6-SNAPSHOT jar JBoss Logging Log4j http://www.jboss.org JBoss Logging Log4j Implementation scm:svn:https://svn.jboss.org/repos/common/common-logging-log4j/trunk/ maven-release-plugin https://svn.jboss.org/repos/common/common-logging-log4j/tags jboss.maven-plugins jboss-deploy-maven-plugin repository.jboss.org JBoss Repository default http://repository.jboss.org/maven2/ false snapshots.jboss.org JBoss Snapshot Repository default http://snapshots.jboss.org/maven2/ false true org.jboss.logging jboss-logging-spi 2.0.5.GA org.jboss jboss-common-core 2.2.5.GA true apache-log4j log4j 1.2.14 libjboss-common-java-0.0+svn2938.orig/common-logging-spi/0000755000175000017500000000000011105642400023110 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/0000755000175000017500000000000011105642400023677 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/0000755000175000017500000000000011105642400024623 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/0000755000175000017500000000000011105642400025544 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/0000755000175000017500000000000011105642400026333 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/0000755000175000017500000000000011105642400027453 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/0000755000175000017500000000000011105642400031101 5ustar twernertwerner././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/DynamicLogger.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/DynamicLogg0000644000175000017500000001604610774176322033250 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * An extension of the JBoss Logger that adds a log() * primitive that maps to a dynamically defined log level. * * TODO - Make sure serialization works correctly * * @author Dimitris Andreadis * @version $Revision: 2784 $ * * @since 4.0.3 */ public class DynamicLogger extends Logger { /** The serialVersionUID */ private static final long serialVersionUID = -5963699806863917370L; /** No logging */ public static final int LOG_LEVEL_NONE = 0; /** Fatal level logging */ public static final int LOG_LEVEL_FATAL = 1; /** Error level logging */ public static final int LOG_LEVEL_ERROR = 2; /** Warn level logging */ public static final int LOG_LEVEL_WARN = 3; /** Info level logging */ public static final int LOG_LEVEL_INFO = 4; /** Debug level logging */ public static final int LOG_LEVEL_DEBUG = 5; /** Trace level logging */ public static final int LOG_LEVEL_TRACE = 6; /** The available log level strings */ public final static String[] LOG_LEVEL_STRINGS = { "NONE", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE" }; /** The log level to use for the "log" primitive */ private int logLevel = LOG_LEVEL_DEBUG; /** * Create a DynamicLogger instance given the logger name. * * @param name the logger name * @return the dynamic logger */ public static DynamicLogger getDynamicLogger(String name) { return new DynamicLogger(name); } /** * Create a DynamicLogger instance given the logger name with the given suffix. * *

This will include a logger seperator between classname and suffix * * @param name The logger name * @param suffix A suffix to append to the classname. * @return the dynamic logger */ public static DynamicLogger getDynamicLogger(String name, String suffix) { return new DynamicLogger(name + "." + suffix); } /** * Create a DynamicLogger instance given the logger class. This simply * calls create(clazz.getName()). * * @param clazz the Class whose name will be used as the logger name * @return the dynamic logger */ public static DynamicLogger getDynamicLogger(Class clazz) { return new DynamicLogger(clazz.getName()); } /** * Create a DynamicLogger instance given the logger class with the given suffix. * *

This will include a logger seperator between classname and suffix * * @param clazz The Class whose name will be used as the logger name. * @param suffix A suffix to append to the classname. * @return the dynamic logger */ public static DynamicLogger getDynamicLogger(Class clazz, String suffix) { return new DynamicLogger(clazz.getName() + "." + suffix); } /** * Create a new DynamicLogger. * * @param name the log name */ protected DynamicLogger(final String name) { super(name); } /** * Sets the logLevel for the log() primitive * * @param logLevel between LOG_LEVEL_NONE and LOG_LEVEL_TRACE */ public void setLogLevel(int logLevel) { if (logLevel >= LOG_LEVEL_NONE && logLevel <= LOG_LEVEL_TRACE) { this.logLevel = logLevel; } } /** * Gets the logLevel of the log() primitive * * @return the logLevel of the log() primitive */ public int getLogLevel() { return logLevel; } /** * Sets the logLevel of the log() primitive * * @param logLevelString the log level in String form */ public void setLogLevelAsString(String logLevelString) { if (logLevelString != null) { logLevelString = logLevelString.toUpperCase().trim(); for (int i = 0; i <= LOG_LEVEL_TRACE; i++) { if (logLevelString.equals(LOG_LEVEL_STRINGS[i])) { // match this.logLevel = i; break; } } } } /** * Gets the logLevel of the log() primitive in String form * * @return the logLevel of the log() primitive in String form */ public String getLogLevelAsString() { return LOG_LEVEL_STRINGS[logLevel]; } /** * Logs a message using dynamic log level * * @param message the message to log */ public void log(Object message) { switch (logLevel) { case LOG_LEVEL_TRACE: super.trace(message); break; case LOG_LEVEL_DEBUG: super.debug(message); break; case LOG_LEVEL_INFO: super.info(message); break; case LOG_LEVEL_WARN: super.warn(message); break; case LOG_LEVEL_ERROR: super.error(message); break; case LOG_LEVEL_FATAL: super.fatal(message); break; case LOG_LEVEL_NONE: default: // do nothing break; } } /** * Logs a message and a throwable using dynamic log level * * @param message the message to log * @param t the throwable to log */ public void log(Object message, Throwable t) { switch (logLevel) { case LOG_LEVEL_TRACE: super.trace(message, t); break; case LOG_LEVEL_DEBUG: super.debug(message, t); break; case LOG_LEVEL_INFO: super.info(message, t); break; case LOG_LEVEL_WARN: super.warn(message, t); break; case LOG_LEVEL_ERROR: super.error(message, t); break; case LOG_LEVEL_FATAL: super.fatal(message, t); break; case LOG_LEVEL_NONE: default: // do nothing break; } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NDCProvider0000644000175000017500000000253710644524014033161 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * An NDC SPI for the backend logging implementation. * * @author Jason T. Greene */ public interface NDCProvider { public void clear(); public String get(); public int getDepth(); public String pop(); public String peek(); public void push(String message); public void setMaxDepth(int maxDepth); }././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/Logger.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/Logger.java0000644000175000017500000002716710774176322033220 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * Logger wrapper that tries to dynamically load a log4j class to * determine if log4j is available in the VM. If it is the case, * a log4j delegate is built and used. In the contrary, a null * logger is used. This class cannot directly reference log4j * classes otherwise the JVM will try to load it and make it fail. * To set * *

Only exposes the relevent factory and logging methods. * *

For JBoss the logging should be done as follows: *

    *
  • FATAL - JBoss is likely to/will crash *
  • ERROR - A definite problem *
  • WARN - Likely to be a problem, or it could be JBoss * detected a problem it can recover from *
  • INFO - Lifecycle low volume, e.g. "Bound x into jndi", * things that are of interest to a user *
  • DEBUG - Lifecycle low volume but necessarily of interest * to the user, e.g. "Starting listener thread" *
  • TRACE - High volume detailed logging *
* * @see #isTraceEnabled * @see #trace(Object) * @see #trace(Object,Throwable) * * @version $Revision: 2784 $ * @author Scott.Stark@jboss.org * @author Jason Dillon * @author Sacha Labourey */ public class Logger implements Serializable { /** Serialization */ private static final long serialVersionUID = 4232175575988879434L; /** The system property to look for an externalized LoggerPlugin implementation class */ protected static String PLUGIN_CLASS_PROP = "org.jboss.logging.Logger.pluginClass"; /** The default LoggerPlugin implementation is log4j */ protected static final String LOG4J_PLUGIN_CLASS_NAME = "org.jboss.logging.log4j.Log4jLoggerPlugin"; /** The LoggerPlugin implementation class to use */ protected static Class pluginClass = null; /** The class name of the LoggerPlugin implementation class to use */ protected static String pluginClassName = null; static { init(); } /** The logger name. */ private final String name; /** The logger plugin delegate */ protected transient LoggerPlugin loggerDelegate = null; /** The LoggerPlugin implementation class name in use * * @return LoggerPlugin implementation class name */ public static String getPluginClassName() { return Logger.pluginClassName; } /** * Set the LoggerPlugin implementation class name in use * * @param pluginClassName the LoggerPlugin implementation class name */ public static void setPluginClassName(String pluginClassName) { if (pluginClassName.equals(Logger.pluginClassName) == false) { Logger.pluginClassName = pluginClassName; init(); } } /** * Creates new Logger the given logger name. * * @param name the logger name. */ protected Logger(final String name) { this.name = name; this.loggerDelegate = getDelegatePlugin(name); } /** * Return the name of this logger. * * @return The name of this logger. */ public String getName() { return name; } /** * Get the logger plugin delegate * * @return the delegate */ public LoggerPlugin getLoggerPlugin() { return this.loggerDelegate; } /** * Check to see if the TRACE level is enabled for this logger. * * @return true if a {@link #trace(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ public boolean isTraceEnabled() { return loggerDelegate.isTraceEnabled(); } /** * Issue a log msg with a level of TRACE. * * @param message the message */ public void trace(Object message) { loggerDelegate.trace(message); } /** * Issue a log msg and throwable with a level of TRACE. * * @param message the message * @param t the throwable */ public void trace(Object message, Throwable t) { loggerDelegate.trace(message, t); } /** * Check to see if the DEBUG level is enabled for this logger. * * @deprecated DEBUG is for low volume logging, you don't need this * @return true if a {@link #trace(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ public boolean isDebugEnabled() { return loggerDelegate.isDebugEnabled(); } /** * Issue a log msg with a level of DEBUG. * * @param message the message */ public void debug(Object message) { loggerDelegate.debug(message); } /** * Issue a log msg and throwable with a level of DEBUG. * * @param message the message * @param t the throwable */ public void debug(Object message, Throwable t) { loggerDelegate.debug(message, t); } /** * Check to see if the INFO level is enabled for this logger. * * @deprecated INFO is for low volume information, you don't need this * @return true if a {@link #info(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ public boolean isInfoEnabled() { return loggerDelegate.isInfoEnabled(); } /** * Issue a log msg with a level of INFO. * * @param message the message */ public void info(Object message) { loggerDelegate.info(message); } /** * Issue a log msg and throwable with a level of INFO. * * @param message the message * @param t the throwable */ public void info(Object message, Throwable t) { loggerDelegate.info(message, t); } /** * Issue a log msg with a level of WARN. * * @param message the message */ public void warn(Object message) { loggerDelegate.warn(message); } /** * Issue a log msg and throwable with a level of WARN. * * @param message the message * @param t the throwable */ public void warn(Object message, Throwable t) { loggerDelegate.warn(message, t); } /** * Issue a log msg with a level of ERROR. * * @param message the message */ public void error(Object message) { loggerDelegate.error(message); } /** * Issue a log msg and throwable with a level of ERROR. * * @param message the message * @param t the throwable */ public void error(Object message, Throwable t) { loggerDelegate.error(message, t); } /** * Issue a log msg with a level of FATAL. * * @param message the message */ public void fatal(Object message) { loggerDelegate.fatal(message); } /** * Issue a log msg and throwable with a level of FATAL. * * @param message the message * @param t the throwable */ public void fatal(Object message, Throwable t) { loggerDelegate.fatal(message, t); } /** * Custom serialization to reinitalize the delegate * * @param stream the object stream * @throws IOException for any error * @throws ClassNotFoundException if a class is not found during deserialization */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { // restore non-transient fields (aka name) stream.defaultReadObject(); // Restore logging if (pluginClass == null) { init(); } this.loggerDelegate = getDelegatePlugin(name); } /** * Create a Logger instance given the logger name. * * @param name the logger name * @return the logger */ public static Logger getLogger(String name) { return new Logger(name); } /** * Create a Logger instance given the logger name with the given suffix. * *

This will include a logger seperator between classname and suffix * * @param name the logger name * @param suffix a suffix to append to the classname. * @return the logger */ public static Logger getLogger(String name, String suffix) { return new Logger(name + "." + suffix); } /** * Create a Logger instance given the logger class. This simply * calls create(clazz.getName()). * * @param clazz the Class whose name will be used as the logger name * @return the logger */ public static Logger getLogger(Class clazz) { return new Logger(clazz.getName()); } /** * Create a Logger instance given the logger class with the given suffix. * *

This will include a logger seperator between classname and suffix * * @param clazz the Class whose name will be used as the logger name. * @param suffix a suffix to append to the classname. * @return the logger */ public static Logger getLogger(Class clazz, String suffix) { return new Logger(clazz.getName() + "." + suffix); } /** * Get the delegate plugin * * @param name the name of the logger * @return the plugin */ protected static LoggerPlugin getDelegatePlugin(String name) { LoggerPlugin plugin = null; try { plugin = (LoggerPlugin) pluginClass.newInstance(); } catch (Throwable e) { plugin = new NullLoggerPlugin(); } try { plugin.init(name); } catch (Throwable e) { String extraInfo = e.getMessage(); System.err.println("Failed to initalize plugin: " + plugin + (extraInfo != null ? ", cause: " + extraInfo : "")); plugin = new NullLoggerPlugin(); } return plugin; } /** * Initialize the LoggerPlugin class to use as the delegate to the * logging system. This first checks to see if a pluginClassName has * been specified via the {@link #setPluginClassName(String)} method, * then the PLUGIN_CLASS_PROP system property and finally the * LOG4J_PLUGIN_CLASS_NAME default. If the LoggerPlugin implementation * class cannot be loaded the default NullLoggerPlugin will be used. */ protected static void init() { try { // See if there is a PLUGIN_CLASS_PROP specified if (pluginClassName == null) { pluginClassName = System.getProperty(PLUGIN_CLASS_PROP, LOG4J_PLUGIN_CLASS_NAME); } // Try to load the plugin via the TCL ClassLoader cl = Thread.currentThread().getContextClassLoader(); pluginClass = cl.loadClass(pluginClassName); } catch (Throwable e) { // The plugin could not be setup, default to a null logger pluginClass = org.jboss.logging.NullLoggerPlugin.class; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullLoggerPlugin.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullLoggerP0000644000175000017500000000477110506442505033237 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * LoggerPlugin implementation producing no output at all. Used for client * side logging when no log4j.jar is available on the classpath. * * @see org.jboss.logging.Logger * @see org.jboss.logging.LoggerPlugin * * @author Sacha Labourey. * @version $Revision: 2081 $ */ public class NullLoggerPlugin implements LoggerPlugin { public void init(String name) { /* don't care */ } public boolean isTraceEnabled() { return false; } public void trace(Object message) { // nothing } public void trace(Object message, Throwable t) { // nothing } public boolean isDebugEnabled() { return false; } public void debug(Object message) { // nothing } public void debug(Object message, Throwable t) { // nothing } public boolean isInfoEnabled() { return false; } public void info(Object message) { // nothing } public void info(Object message, Throwable t) { // nothing } public void error(Object message) { // nothing } public void error(Object message, Throwable t) { // nothing } public void fatal(Object message) { // nothing } public void fatal(Object message, Throwable t) { // nothing } public void warn(Object message) { // nothing } public void warn(Object message, Throwable t) { // nothing } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/MDCSupport.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/MDCSupport.0000644000175000017500000000226010644524014033111 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * Indicates that a Logger plugin supports MDC. * * @author Jason T. Greene */ public interface MDCSupport { public MDCProvider getMDCProvider(); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NDCSupport.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NDCSupport.0000644000175000017500000000226010644524014033112 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * Indicates that a logger plugin supports NDC. * * @author Jason T. Greene */ public interface NDCSupport { public NDCProvider getNDCProvider(); } libjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/MDC.java0000644000175000017500000000360211012144425032351 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.util.Map; /** * A "Map Diagnostic Context" abstraction. * * @author Jason T. Greene */ public class MDC { private final static MDCProvider mdc; static { MDCProvider m = null; if (MDCSupport.class.isAssignableFrom(Logger.pluginClass)) { try { m = ((MDCSupport) Logger.pluginClass.newInstance()).getMDCProvider(); } catch (Throwable t) { // Eat } } if (m == null) m = new NullMDCProvider(); mdc = m; } public static void put(String key, Object val) { mdc.put(key, val); } public static Object get(String key) { return mdc.get(key); } public static void remove(String key) { mdc.remove(key); } public static Map getMap() { return mdc.getMap(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/MDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/MDCProvider0000644000175000017500000000250110644524014033147 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.util.Map; /** * MDC SPI for the backend logging implementation. * * @author Jason T. Greene */ public interface MDCProvider { public void put(String key, Object value); public Object get(String key); public void remove(String key); public Map getMap(); } libjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NDC.java0000644000175000017500000000404011012144425032347 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * A "Nested Diagnostic Context" abstraction. * * @author Jason T. Greene */ public class NDC { private final static NDCProvider ndc; static { NDCProvider n = null; if (NDCSupport.class.isAssignableFrom(Logger.pluginClass)) { try { n = ((NDCSupport) Logger.pluginClass.newInstance()).getNDCProvider(); } catch (Throwable t) { // Eat } } if (n == null) n = new NullNDCProvider(); ndc = n; } public static void clear() { ndc.clear(); } public static String get() { return ndc.get(); } public static int getDepth() { return ndc.getDepth(); } public static String pop() { return ndc.pop(); } public static String peek() { return ndc.peek(); } public static void push(String message) { ndc.push(message); } public static void setMaxDepth(int maxDepth) { ndc.setMaxDepth(maxDepth); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullMDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullMDCProv0000644000175000017500000000262310644524014033143 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.util.Map; /** * An MDC provider which does nothing. * * @author Jason T. Greene */ public class NullMDCProvider implements MDCProvider { public Object get(String key) { return null; } public Map getMap() { return null; } public void put(String key, Object val) { } public void remove(String key) { } }././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullNDCProvider.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/NullNDCProv0000644000175000017500000000324510774176322033156 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.util.Stack; /** * An NDC provider which does nothing. * * @author Jason T. Greene */ public class NullNDCProvider implements NDCProvider { public void clear() { } public Stack cloneStack() { return null; } public String get() { return null; } public int getDepth() { return 0; } public void inherit(Stack stack) { } public String peek() { return null; } public String pop() { return null; } public void push(String message) { } public void remove() { } public void setMaxDepth(int maxDepth) { } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/LoggerPlugin.javalibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/main/java/org/jboss/logging/LoggerPlugi0000644000175000017500000001040310506442505033252 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; /** * Defines a "pluggable" login module. In fact, this is only used to split between * log4j and /dev/null. Choice is made in org.jboss.logging.Logger * * @see org.jboss.logging.Logger * @see org.jboss.logging.NullLoggerPlugin * * @author Sacha Labourey. * @version $Revision: 2081 $ */ public interface LoggerPlugin { /** * Initialise the logger with the given name * * @param name the name */ void init(String name); /** * Check to see if the TRACE level is enabled for this logger. * * @return true if a {@link #trace(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ boolean isTraceEnabled(); /** * Issue a log msg with a level of TRACE. * * @param message the message */ void trace(Object message); /** * Issue a log msg and throwable with a level of TRACE. * * @param message the message * @param t the throwable */ void trace(Object message, Throwable t); /** * Check to see if the DEBUG level is enabled for this logger. * * @deprecated DEBUG is for low volume logging, you don't need this * @return true if a {@link #trace(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ boolean isDebugEnabled(); /** * Issue a log msg with a level of DEBUG. * * @param message the message */ void debug(Object message); /** * Issue a log msg and throwable with a level of DEBUG. * * @param message the message * @param t the throwable */ void debug(Object message, Throwable t); /** * Check to see if the INFO level is enabled for this logger. * * @deprecated INFO is for low volume information, you don't need this * @return true if a {@link #info(Object)} method invocation would pass * the msg to the configured appenders, false otherwise. */ boolean isInfoEnabled(); /** * Issue a log msg with a level of INFO. * * @param message the message */ void info(Object message); /** * Issue a log msg and throwable with a level of INFO. * * @param message the message * @param t the throwable */ void info(Object message, Throwable t); /** * Issue a log msg with a level of WARN. * * @param message the message */ void warn(Object message); /** * Issue a log msg and throwable with a level of WARN. * * @param message the message * @param t the throwable */ void warn(Object message, Throwable t); /** * Issue a log msg with a level of ERROR. * * @param message the message */ void error(Object message); /** * Issue a log msg and throwable with a level of ERROR. * * @param message the message * @param t the throwable */ void error(Object message, Throwable t); /** * Issue a log msg with a level of FATAL. * * @param message the message */ void fatal(Object message); /** * Issue a log msg and throwable with a level of FATAL. * * @param message the message * @param t the throwable */ void fatal(Object message, Throwable t); } libjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/etc/0000755000175000017500000000000011105642400024452 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/src/etc/default.mf0000644000175000017500000000067110470642610026435 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @specification.title@ Specification-Version: @specification.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @implementation.title@ Implementation-URL: @implementation.url@ Implementation-Version: @implementation.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ libjboss-common-java-0.0+svn2938.orig/common-logging-spi/.classpath0000644000175000017500000000032210774161365025111 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-spi/.project0000644000175000017500000000054610776644031024603 0ustar twernertwerner jboss-logging-spi The JBoss Logging Framework Programming Interface org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature libjboss-common-java-0.0+svn2938.orig/common-logging-spi/.settings/0000755000175000017500000000000011105642400025026 5ustar twernertwernerlibjboss-common-java-0.0+svn2938.orig/common-logging-spi/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000031410774162570032026 0ustar twernertwerner#Mon Mar 31 14:11:36 CEST 2008 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 libjboss-common-java-0.0+svn2938.orig/common-logging-spi/projectSet.psf0000644000175000017500000000037410776644031025767 0ustar twernertwerner libjboss-common-java-0.0+svn2938.orig/common-logging-spi/pom.xml0000644000175000017500000000403310776644405024451 0ustar twernertwerner org.jboss jboss-parent 3 4.0.0 org.jboss.logging jboss-logging-spi 2.0.6-SNAPSHOT jar JBoss Logging Programming Interface http://www.jboss.org The JBoss Logging Framework Programming Interface scm:svn:https://svn.jboss.org/repos/common/common-logging-spi/trunk/ maven-release-plugin https://svn.jboss.org/repos/common/common-logging-spi/tags jboss.maven-plugins jboss-deploy-maven-plugin repository.jboss.org JBoss Repository default http://repository.jboss.org/maven2/ false snapshots.jboss.org JBoss Snapshot Repository default http://snapshots.jboss.org/maven2/ false true

Conversion Character Effect
z Used to output current thread NDC value. This can be used to obtain an NDC to augment any NDC associated with the LoggingEvent. This might be necessary if the LoggingEvent has been serialized between VMs.
Z Used to output current thread MDC value. This can be used to obtain an MDC to augment any MDC associated with the LoggingEvent. This might be necessary if the LoggingEvent has been serialized between VMs. The Z conversion character must be followed by the key for the map placed between braces, as in %Z{theKey} where theKey is the key. The value in the MDC corresponding to the key will be output.