diff options
Diffstat (limited to 'sca-java-1.x/tags/java-stable-20060304/sca/common/src')
20 files changed, 1834 insertions, 0 deletions
diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyException.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyException.java new file mode 100644 index 0000000000..74110fef99 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyException.java @@ -0,0 +1,85 @@ +package org.apache.tuscany.common; + +import java.util.ArrayList; +import java.util.List; + +/** + * The root checked exception for the Tuscany rubntime + * + * @version $Rev: 368822 $ $Date: 2006-01-13 10:54:38 -0800 (Fri, 13 Jan 2006) $ + */ +public abstract class TuscanyException extends Exception { + + protected List<String> contextStack; + + public TuscanyException() { + super(); + } + + public TuscanyException(String message) { + super(message); + } + + public TuscanyException(String message, Throwable cause) { + super(message, cause); + } + + public TuscanyException(Throwable cause) { + super(cause); + } + + /** + * Returns a collection of names representing the context call stack where the error occured. The top of the stack + * is the first element in the collection. + */ + public List<String> returnContextNames(String name) { + if (contextStack == null) { + contextStack = new ArrayList(); + } + return contextStack; + } + + /** + * Pushes a context name where an error occured onto the call stack + */ + public void addContextName(String name) { + if (contextStack == null) { + contextStack = new ArrayList(); + } + contextStack.add(name); + } + + private String identifier; + + /** + * Returns a string representing additional error information referred to in the error message + */ + public String getIdentifier() { + return identifier; + } + + /** + * Sets an additional error information referred to in the error message + */ + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getMessage() { + if (identifier == null && contextStack == null) { + return super.getMessage(); + } + StringBuffer b = new StringBuffer(); + if (identifier != null) { + b.append(" [" + identifier + "]"); + } + if (contextStack != null) { + b.append("\nContext stack trace: "); + for (int i = contextStack.size() - 1; i >= 0; i--) { + b.append("[" + contextStack.get(i) + "]"); + } + } + return super.getMessage() + b.toString(); + + } +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyRuntimeException.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyRuntimeException.java new file mode 100644 index 0000000000..922705f7b5 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/TuscanyRuntimeException.java @@ -0,0 +1,91 @@ +package org.apache.tuscany.common; + +import java.util.ArrayList; +import java.util.List; + +/** + * The root unchecked exception for the Tuscany runtime + * + * @version $Rev: 368822 $ $Date: 2006-01-13 10:54:38 -0800 (Fri, 13 Jan 2006) $ + */ + +public abstract class TuscanyRuntimeException extends RuntimeException { + + protected List<String> contextStack; + + protected String moduleComponentName; + + protected String componentName; + + public TuscanyRuntimeException() { + super(); + } + + public TuscanyRuntimeException(String message) { + super(message); + } + + public TuscanyRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + public TuscanyRuntimeException(Throwable cause) { + super(cause); + } + + /** + * Returns a collection of names representing the context call stack where the error occured. The top of the stack + * is the first element in the collection. + */ + public List<String> returnContextNames(String name) { + if (contextStack == null) { + contextStack = new ArrayList(); + } + return contextStack; + } + + /** + * Pushes a context name where an error occured onto the call stack + */ + public void addContextName(String name) { + if (contextStack == null) { + contextStack = new ArrayList(); + } + contextStack.add(name); + } + + private String identifier; + + /** + * Returns a string representing additional error information referred to in the error message + */ + public String getIdentifier() { + return identifier; + } + + /** + * Sets an additional error information referred to in the error message + */ + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getMessage() { + if (identifier == null && contextStack == null) { + return super.getMessage(); + } + StringBuffer b = new StringBuffer(); + if (identifier != null) { + b.append(" [" + identifier + "]"); + } + if (contextStack != null) { + b.append("\nContext stack trace: "); + for (int i = contextStack.size() - 1; i >= 0; i--) { + b.append("[" + contextStack.get(i) + "]"); + } + } + return super.getMessage() + b.toString(); + + } + +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/discovery/util/ServiceProviderRegistry.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/discovery/util/ServiceProviderRegistry.java new file mode 100644 index 0000000000..65ede08a32 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/discovery/util/ServiceProviderRegistry.java @@ -0,0 +1,177 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.discovery.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.tuscany.common.io.util.FixedURLInputStream; + +//FIXME Port to 1.5 collections + +/** + * A Registry for service providers defined using the + * <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">JAR service provider mechanism</a>. + * + */ +public class ServiceProviderRegistry { + + private Map registry = Collections.synchronizedMap(new WeakHashMap()); + + private final static ServiceProviderRegistry instance = new ServiceProviderRegistry(); + + /** + * Constructor. + */ + public ServiceProviderRegistry() { + super(); + } + + /** + * @return Returns the instance. + */ + public static ServiceProviderRegistry getInstance() { + return instance; + } + + /** + * Get the available providers of a given type. + * + * @param clazz + * @return + */ + public List getServiceProviders(final Class clazz) { + List providers = (List) registry.get(clazz); + if (providers != null) + return providers; + + providers = (List) AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + return loadServiceProviders(clazz); + } + }); + + registry.put(clazz, providers); + return providers; + } + + /** + * Get an provider of a given type. + * + * @param clazz + * @return + */ + public Object getServiceProvider(Class clazz) { + List providers = getServiceProviders(clazz); + if (providers.isEmpty()) + return null; + else { + return providers.get(0); + } + } + + /** + * Registers an provider programatically + * + * @param clazz + * @param provider + */ + public void registerServiceProvider(Class clazz, Object provider) { + getServiceProviders(clazz).add(provider); + } + + /** + * Load providers of the given type + * + * @param clazz + * @return + */ + private List loadServiceProviders(Class clazz) { + List classNames = new ArrayList(); + + // First look for a system property named <SPI className> + String className = System.getProperty(clazz.getName()); + if (className != null) + classNames.add(className); + + // Find all the class names mentioned in all the META-INF/services/<SPI className> + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + try { + Enumeration files = loader.getResources("META-INF/services/" + clazz.getName()); + while (files.hasMoreElements()) { + URL url = (URL) files.nextElement(); + readClassNames(url, classNames); + } + } catch (IOException e) { + } + + // Instantiate an provider for each of the named classes + List providers = new ArrayList(); + Iterator i = classNames.iterator(); + while (i.hasNext()) { + String name = (String) i.next(); + try { + Class providerClass = Class.forName(name, true, loader); + providers.add(providerClass.newInstance()); + } catch (Exception e) { + // Ignore ClassNotFoundException + } + } + return providers; + } + + /** + * Read class names from the given URL. + * @param url + * @param classNames + * @throws IOException + */ + private void readClassNames(URL url, List classNames) throws IOException { + InputStream is = new FixedURLInputStream(url); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); + String inputLine = null; + while ((inputLine = in.readLine()) != null) { + int i = inputLine.indexOf('#'); + if (i >= 0) { + inputLine = inputLine.substring(0, i); + } + inputLine = inputLine.trim(); + if (inputLine.length() > 0) { + if (!classNames.contains(inputLine)) { + classNames.add(inputLine); + } + } + } + } finally { + is.close(); + } + } + +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/ClassLoaderObjectInputStream.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/ClassLoaderObjectInputStream.java new file mode 100644 index 0000000000..607267a464 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/ClassLoaderObjectInputStream.java @@ -0,0 +1,73 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.io.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; + +/** + * <p/> + * An implementation of an ObjectInputStream that takes a ClassLoader or works + * with the current Thread context ClassLoader. + */ +public class ClassLoaderObjectInputStream extends ObjectInputStream { + protected ClassLoader classLoader; + + /** + * Constructor + * + * @param in + * @param classLoader + * @throws IOException + */ + public ClassLoaderObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { + super(in); + this.classLoader = classLoader; + } + + /** + * @see java.io.ObjectInputStream#resolveClass(java.io.ObjectStreamClass) + */ + protected Class resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { + + final String name = desc.getName(); + try { + return (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws ClassNotFoundException, IOException { + try { + return Class.forName(name, false, classLoader); + } catch (ClassNotFoundException e) { + return ClassLoaderObjectInputStream.super.resolveClass(desc); + } + } + }); + } catch (PrivilegedActionException ex) { + Exception e = ex.getException(); + if (e instanceof ClassNotFoundException) { + throw (ClassNotFoundException) e; + } else if (e instanceof IOException) { + throw (IOException) e; + } + return null; + } + } +}
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLClassLoader.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLClassLoader.java new file mode 100644 index 0000000000..f2f6f958f7 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLClassLoader.java @@ -0,0 +1,310 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.io.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.JarURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; +import java.security.Permission; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * <p/> + * This class is a workaround for URL stream issue as illustrated below. + * <p/> + * InputStream is=url.getInputStream(); + * is.close(); // This line doesn't close the JAR file if the URL is a jar entry like "jar:file:/a.jar!/sca.module" + * <p/> + * We also need to turn off the JarFile cache. + */ +public class FixedURLClassLoader extends URLClassLoader { + + /** + * @param urls + * @param parent + */ + public FixedURLClassLoader(URL[] urls, ClassLoader parent) { + super(normalizeURLs(urls), parent, new FixedURLStreamHandlerFactory()); + } + + private static URL[] normalizeURLs(URL[] urls) { + URL[] newURLs = new URL[urls.length]; + for (int i = 0; i < urls.length; i++) + try { + /** + * Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to + * refer to a JAR file which will be downloaded and opened as needed. + */ + String spec = urls[i].toString(); + if (!(urls[i].getProtocol().equals("jar") || urls[i].getFile().endsWith("/"))) { + spec = "jar:" + spec + "!/"; + } + newURLs[i] = new URL(null, spec, FixedURLStreamHandler.instance); + } catch (MalformedURLException e) { + } + return newURLs; + } + + /** + * @see java.lang.Object#finalize() + */ + protected void finalize() throws Throwable { + super.finalize(); + } + + public static class FixedURLStreamHandlerFactory implements URLStreamHandlerFactory { + public URLStreamHandler createURLStreamHandler(String protocol) { + return FixedURLStreamHandler.instance; + } + } + + public static class FixedURLStreamHandler extends URLStreamHandler { + public static final URLStreamHandler instance = new FixedURLStreamHandler(); + + public FixedURLStreamHandler() { + super(); + } + + protected URLConnection openConnection(URL url) throws IOException { + URLConnection connection = new URL(url.toString()).openConnection(); + connection.setUseCaches(false); + return new FixedURLConnection(connection, url); + } + } + + public static class FixedURLConnection extends URLConnection { + private URLConnection connection; + + public FixedURLConnection(URLConnection connection, URL url) { + super(url); + this.connection = connection; + } + + public void addRequestProperty(String key, String value) { + connection.addRequestProperty(key, value); + } + + public void connect() throws IOException { + connection.connect(); + } + + public boolean getAllowUserInteraction() { + return connection.getAllowUserInteraction(); + } + + public Object getContent() throws IOException { + return connection.getContent(); + } + + public Object getContent(Class[] classes) throws IOException { + return connection.getContent(classes); + } + + public String getContentEncoding() { + return connection.getContentEncoding(); + } + + public int getContentLength() { + return connection.getContentLength(); + } + + public String getContentType() { + return connection.getContentType(); + } + + public long getDate() { + return connection.getDate(); + } + + public boolean getDefaultUseCaches() { + return connection.getDefaultUseCaches(); + } + + public boolean getDoInput() { + return connection.getDoInput(); + } + + public boolean getDoOutput() { + return connection.getDoOutput(); + } + + public long getExpiration() { + return connection.getExpiration(); + } + + public String getHeaderField(int n) { + return connection.getHeaderField(n); + } + + public String getHeaderField(String name) { + return connection.getHeaderField(name); + } + + public long getHeaderFieldDate(String name, long Default) { + return connection.getHeaderFieldDate(name, Default); + } + + public int getHeaderFieldInt(String name, int Default) { + return connection.getHeaderFieldInt(name, Default); + } + + public String getHeaderFieldKey(int n) { + return connection.getHeaderFieldKey(n); + } + + public Map getHeaderFields() { + return connection.getHeaderFields(); + } + + public long getIfModifiedSince() { + return connection.getIfModifiedSince(); + } + + public InputStream getInputStream() throws IOException { + if (connection instanceof JarURLConnection && url.toString().startsWith("jar:file:")) { + return getByteArrayInputStream(); + // return new FixedURLInputStream((JarURLConnection) connection); + } else { + return connection.getInputStream(); + } + } + + private InputStream getByteArrayInputStream() throws IOException { + JarFile jFile = null; + try { + String spec = url.toString(); + spec = spec.substring("jar:".length()); + int index = spec.lastIndexOf("!/"); + String file = new URL(spec.substring(0, index)).getFile(); + jFile = new JarFile(file); + String entryName = spec.substring(index + 2); + JarEntry jarEntry = jFile.getJarEntry(entryName); + if (jarEntry != null) { + InputStream jarStream = null; + try { + jarStream = jFile.getInputStream(jarEntry); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte buf[] = new byte[4096]; + int length = 0; + length = jarStream.read(buf); + while (length > 0) { + out.write(buf, 0, length); + length = jarStream.read(buf); + } + // out.flush(); + jarStream.close(); + // out.close(); + return new ByteArrayInputStream(out.toByteArray()); + } catch (IOException e) { + if (jarStream != null) + jarStream.close(); + throw e; + } + } else { + throw new IOException("Entry " + entryName + " is not found in " + file); + } + } catch (IOException ex) { + throw ex; + } finally { + if (jFile != null) { + try { + jFile.close(); + } catch (IOException e) { + // Ignore it + } + } + } + } + + public long getLastModified() { + return connection.getLastModified(); + } + + public OutputStream getOutputStream() throws IOException { + return connection.getOutputStream(); + } + + public Permission getPermission() throws IOException { + return connection.getPermission(); + } + + public Map getRequestProperties() { + return connection.getRequestProperties(); + } + + public String getRequestProperty(String key) { + return connection.getRequestProperty(key); + } + + public URL getURL() { + return url; + } + + public boolean getUseCaches() { + return connection.getUseCaches(); + } + + public int hashCode() { + return connection.hashCode(); + } + + public void setAllowUserInteraction(boolean allowuserinteraction) { + connection.setAllowUserInteraction(allowuserinteraction); + } + + public void setDefaultUseCaches(boolean defaultusecaches) { + connection.setDefaultUseCaches(defaultusecaches); + } + + public void setDoInput(boolean doinput) { + connection.setDoInput(doinput); + } + + public void setDoOutput(boolean dooutput) { + connection.setDoOutput(dooutput); + } + + public void setIfModifiedSince(long ifmodifiedsince) { + connection.setIfModifiedSince(ifmodifiedsince); + } + + public void setRequestProperty(String key, String value) { + connection.setRequestProperty(key, value); + } + + public void setUseCaches(boolean usecaches) { + connection.setUseCaches(usecaches); + } + + public String toString() { + return connection.toString(); + } + + } + +}
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLInputStream.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLInputStream.java new file mode 100644 index 0000000000..192798ff26 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/FixedURLInputStream.java @@ -0,0 +1,119 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.io.util; + +import java.io.IOException; +import java.io.InputStream; +import java.net.JarURLConnection; +import java.net.URL; +import java.util.jar.JarFile; + +/** + * <p/> + * This class is a workaround for URL stream issue as illustrated below. + * <p/> + * InputStream is=url.getInputStream(); + * is.close(); // This line doesn't close the JAR file if the URL is a jar entry like "jar:file:/a.jar!/sca.module" + * <p/> + * We also need to turn off the JarFile cache. + */ +public class FixedURLInputStream extends InputStream { + + private JarFile jarFile; + private InputStream is; + + /** + * Constructor + * + * @param url + * @throws IOException + */ + public FixedURLInputStream(URL url) throws IOException { + String protocol = url.getProtocol(); + if (protocol != null && (protocol.equals("jar") || protocol.equals("wsjar"))) { + String urlStr = url.toString(); + if (urlStr.startsWith("wsjar:")) { + url = new URL("jar:" + urlStr.substring(6)); + } + JarURLConnection connection = (JarURLConnection) url.openConnection(); + // We cannot use cache + connection.setUseCaches(false); + try { + is = connection.getInputStream(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + jarFile = connection.getJarFile(); + } else { + is = url.openStream(); + } + } + + /** + * Constructor + * + * @param connection + * @throws IOException + */ + public FixedURLInputStream(JarURLConnection connection) throws IOException { + // We cannot use cache + connection.setUseCaches(false); + is = connection.getInputStream(); + jarFile = connection.getJarFile(); + } + + public int available() throws IOException { + return is.available(); + } + + public void close() throws IOException { + is.close(); + // We need to close the JAR file + if (jarFile != null) + jarFile.close(); + } + + public synchronized void mark(int readlimit) { + is.mark(readlimit); + } + + public boolean markSupported() { + return is.markSupported(); + } + + public int read() throws IOException { + return is.read(); + } + + public int read(byte[] b, int off, int len) throws IOException { + return is.read(b, off, len); + } + + public int read(byte[] b) throws IOException { + return is.read(b); + } + + public synchronized void reset() throws IOException { + is.reset(); + } + + public long skip(long n) throws IOException { + return is.skip(n); + } + +}
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/IOHelper.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/IOHelper.java new file mode 100644 index 0000000000..8227a052df --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/IOHelper.java @@ -0,0 +1,128 @@ +/* + * + * 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.apache.tuscany.common.io.util; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * I/O utility methods + * + * @version $Rev$ $Date$ + */ +public class IOHelper { + + // ---------------------------------- + // Fields + // ---------------------------------- + + public static int BYTES = 8192; + + // ---------------------------------- + // Constructors + // ---------------------------------- + + private IOHelper() { + } + + // ---------------------------------- + // Methods + // ---------------------------------- + + public static void copy(InputStream in, OutputStream out) throws IOException { + copy(in, out, -1); + } + + public static void copy(InputStream in, OutputStream out, long byteCount) throws IOException { + byte buffer[] = new byte[BYTES]; + int len = BYTES; + + if (byteCount >= 0) { + while (byteCount > 0) { + if (byteCount < BYTES) { + len = in.read(buffer, 0, (int) byteCount); + } else { + len = in.read(buffer, 0, BYTES); + } + if (len == -1) { + break; + } + byteCount -= len; + out.write(buffer, 0, len); + } + } else { + while (true) { + len = in.read(buffer, 0, BYTES); + if (len < 0) { + break; + } + out.write(buffer, 0, len); + } + } + } + + public static byte[] read(InputStream in) throws IOException { + byte buffer[] = new byte[BYTES]; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int len = BYTES; + while (true) { + len = in.read(buffer, 0, BYTES); + if (len < 0) { + break; + } + out.write(buffer, 0, len); + } + return out.toByteArray(); + } + + /** + * Removes a directory from the file sytsem + */ + public static boolean deleteDir(File pDir) { + if (pDir.isDirectory()) { + String[] children = pDir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(pDir, children[i])); + if (!success) { + return false; + } + } + } + return pDir.delete(); + } + + /** + * Returns a stream to the resource associated with pPath in the directory + * pRoot + */ + public static InputStream getResource(File pRoot, String pPath) throws FileNotFoundException { + + File[] files = pRoot.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isFile() && files[i].getName().equals(pPath)) { + return new BufferedInputStream(new FileInputStream(files[i])); + } + } + return null; + } + +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/UTF8String.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/UTF8String.java new file mode 100644 index 0000000000..651c81f92a --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/io/util/UTF8String.java @@ -0,0 +1,107 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.io.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; + +/** + * String encoded with UTF-8 + * + */ +public class UTF8String { + public static final String UTF8 = "UTF-8"; + private String string; + + /** + * + */ + public UTF8String(String str) { + super(); + this.string = str; + } + + public UTF8String(byte[] bytes) { + this(toString(bytes)); + } + + public static String toString(byte[] bytes) { + try { + if (bytes == null) + return null; + return new String(bytes, UTF8); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e.getMessage()); + } + } + + public static byte[] getBytes(String str) { + try { + if (str == null) + return null; + return str.getBytes(UTF8); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e.getMessage()); + } + } + + public ByteArrayInputStream getInputStream() { + return new ByteArrayInputStream(getBytes()); + } + + public static ByteArrayInputStream getInputStream(String str) { + return new ByteArrayInputStream(getBytes(str)); + } + + public static String toString(ByteArrayOutputStream bos) { + try { + return bos.toString(UTF8); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e.getMessage()); + } + } + + public byte[] getBytes() { + try { + if (string == null) + return null; + return string.getBytes(UTF8); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e.getMessage()); + } + } + + public String toString() { + return string; + } + + public int hashCode() { + return (string == null) ? 0 : string.hashCode(); + } + + public boolean equals(Object object) { + if (!(object instanceof UTF8String)) + return false; + UTF8String s = (UTF8String) object; + if (string == s.string) + return true; + if (string == null || s.string == null) + return false; + return string.equals(s.string); + } +}
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/LogLevel.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/LogLevel.java new file mode 100644 index 0000000000..f3362b13cb --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/LogLevel.java @@ -0,0 +1,37 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor; + +import static java.lang.annotation.ElementType.METHOD; +import java.lang.annotation.Retention; +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import java.lang.annotation.Target; + +/** + * Annotation that can be applied to methods in a monitoring interface + * to indicate to logging frameworks the severity of the event. + * + * @version $Rev$ $Date$ + */ +@Target({METHOD}) +@Retention(RUNTIME) +public @interface LogLevel { + /** + * The log level as specified by {@link java.util.logging.Level}. + */ + String value(); +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/MonitorFactory.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/MonitorFactory.java new file mode 100644 index 0000000000..aa92092005 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/MonitorFactory.java @@ -0,0 +1,35 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor; + +/** + * A MonitorFactory creates implementations of components' monitor interfaces + * that interface with a its monitoring scheme. For example, a implementation + * may create versions that emit appropriate logging events or which send + * notifications to a management API. + * + * @version $Rev$ $Date$ + */ +public interface MonitorFactory { + /** + * Return a monitor for a component's monitor interface. + * + * @param monitorInterface the component's monitoring interface + * @return an implementation of the monitoring interface; will not be null + */ + <T> T getMonitor(Class<T> monitorInterface); +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/InvalidLevelException.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/InvalidLevelException.java new file mode 100644 index 0000000000..cfb924d8fb --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/InvalidLevelException.java @@ -0,0 +1,43 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor.impl; + +/** + * @version $Rev$ $Date$ + */ +public class InvalidLevelException extends IllegalArgumentException { + private final String method; + private final String level; + + public InvalidLevelException(String method, String level) { + super(); + this.method = method; + this.level = level; + } + + public String getMethod() { + return method; + } + + public String getLevel() { + return level; + } + + public String getMessage() { + return "Invalid level for method " + method + " : " + level; + } +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/JavaLoggingMonitorFactory.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/JavaLoggingMonitorFactory.java new file mode 100644 index 0000000000..06bb87d6dd --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/JavaLoggingMonitorFactory.java @@ -0,0 +1,139 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor.impl; + +import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.WeakHashMap; +import java.util.Map; +import java.util.HashMap; +import java.util.Properties; +import java.util.Iterator; +import java.util.logging.Logger; +import java.util.logging.Level; + +import org.apache.tuscany.common.monitor.MonitorFactory; +import org.apache.tuscany.common.monitor.LogLevel; + +/** + * A factory for monitors that forwards events to a {@link java.util.logging.Logger Java Logging (JSR47) Logger}. + * + * @version $Rev$ $Date$ + */ +public class JavaLoggingMonitorFactory implements MonitorFactory { + private final String bundleName; + private final Level defaultLevel; + private final Map<String, Level> levels; + + private final Map<Class<?>, WeakReference<?>> proxies = new WeakHashMap(); + + /** + * + * @param levels + * @param defaultLevel + * @param bundleName + */ + public JavaLoggingMonitorFactory(Properties levels, Level defaultLevel, String bundleName) { + this.defaultLevel = defaultLevel; + this.bundleName = bundleName; + this.levels = new HashMap(levels.size()); + for (Iterator<Map.Entry<Object, Object>> i = levels.entrySet().iterator(); i.hasNext();) { + Map.Entry<Object, Object> entry = i.next(); + String method = (String) entry.getKey(); + String level = (String) entry.getValue(); + try { + this.levels.put(method, Level.parse(level)); + } catch (IllegalArgumentException e) { + throw new InvalidLevelException(method, level); + } + } + } + + public synchronized <T> T getMonitor(Class<T> monitorInterface) { + T proxy = getCachedMonitor(monitorInterface); + if (proxy == null) { + proxy = createMonitor(monitorInterface); + proxies.put(monitorInterface, new WeakReference(proxy)); + } + return proxy; + } + + private <T>T getCachedMonitor(Class<T> monitorInterface) { + WeakReference<T> ref = (WeakReference<T>) proxies.get(monitorInterface); + return (ref != null) ? ref.get() : null; + } + + private <T>T createMonitor(Class<T> monitorInterface) { + String className = monitorInterface.getName(); + Logger logger = Logger.getLogger(className, bundleName); + Method[] methods = monitorInterface.getMethods(); + Map<String, Level> levels = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + String key = className + '#' + method.getName(); + Level level = this.levels.get(key); + + // if not specified the in config properties, look for an annotation on the method + if (level == null) { + LogLevel annotation = method.getAnnotation(LogLevel.class); + if (annotation != null && annotation.value() != null) { + try { + level = Level.parse(annotation.value()); + } catch (IllegalArgumentException e) { + // bad value, just use the default + level = defaultLevel; + } + } + } + if (level != null) { + levels.put(method.getName(), level); + } + } + InvocationHandler handler = new LoggingHandler(logger, levels); + return (T) Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class<?>[]{monitorInterface}, handler); + } + + private static final class LoggingHandler implements InvocationHandler { + private final Logger logger; + private final Map<String, Level> methodLevels; + + public LoggingHandler(Logger logger, Map<String, Level> methodLevels) { + this.logger = logger; + this.methodLevels = methodLevels; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String sourceMethod = method.getName(); + Level level = methodLevels.get(sourceMethod); + if (level != null && logger.isLoggable(level)) { + // construct the key for the resource bundle + String className = logger.getName(); + String key = className + '#' + sourceMethod; + + // if the only argument is a Throwable use the special logger for it + if (args != null && args.length == 1 && args[0] instanceof Throwable) { + logger.logp(level, className, sourceMethod, key, (Throwable) args[0]); + } else { + logger.logp(level, className, sourceMethod, key, args); + } + } + return null; + } + } +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/NullMonitorFactory.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/NullMonitorFactory.java new file mode 100644 index 0000000000..a2bbbd3965 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/monitor/impl/NullMonitorFactory.java @@ -0,0 +1,48 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor.impl; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import org.apache.tuscany.common.monitor.MonitorFactory; + +/** + * Implementation of a {@link MonitorFactory} that produces implementations that simply return. + * + * @version $Rev$ $Date$ + */ +public class NullMonitorFactory implements MonitorFactory { + public <T> T getMonitor(Class<T> monitorInterface) { + /* + * This uses a reflection proxy to implement the monitor interface which + * is a simple but perhaps not very performant solution. Performance + * might be improved by code generating an implementation with empty methods. + */ + return monitorInterface.cast(Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class<?>[]{monitorInterface}, NULL_MONITOR)); + } + + /** + * Singleton invocation hander that does nothing. + */ + private static final InvocationHandler NULL_MONITOR = new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) { + return null; + } + }; +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/ResourceLoader.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/ResourceLoader.java new file mode 100644 index 0000000000..9771c1e966 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/ResourceLoader.java @@ -0,0 +1,94 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.resource; + +import java.io.IOException; +import java.net.URL; +import java.util.Iterator; +import java.util.List; + +/** + * Interface which abstracts the implementation of something that is able to + * load resources (such as a ClassLoader). All Tuscany code should use this + * API rather than a ClassLoader directly in order to reduce the risk of + * memory leaks due to ClassLoader references. + * + * @version $Rev: 379878 $ $Date: 2006-02-22 12:45:50 -0800 (Wed, 22 Feb 2006) $ + */ +public interface ResourceLoader { + + /** + * Returns the parent resource loaders. + * + * @return resource loaders that are parents to this one + */ + List<ResourceLoader> getParents(); + + /** + * Loads the class with the specified binary name. + * + * @param name the binary name of the class + * @return the resulting Class object + * @throws ClassNotFoundException if the class was not found + * @see ClassLoader#loadClass(String) + */ + Class<?> loadClass(String name) throws ClassNotFoundException; + + /** + * Converts an array of bytes into a Class. + * @param bytes + * @return + */ + Class<?> addClass(byte[] bytes); + + /** + * Finds the first resource with the given name. + * <p/> + * Each parent is searched first (in the order returned by {@link #getParents()}) + * and the first resource located is found. If no parent returns a resource then + * the first resource defined by this ResourceLoader is returned. + * + * @param name the resource name + * @return a {@link URL} that can be used to read the resource, or null if no resource could be found + * @throws IOException if there was a problem locating the resource + */ + URL getResource(String name) throws IOException; + + /** + * Find resources with the given name that are available directly from this + * ResourceLoader. Resources from parent ResourceLoaders are not returned. + * + * @param name the resource name + * @return an Iterator of {@link URL} objects for the resource + * @throws IOException if there was a problem locating the resources + */ + Iterator<URL> getResources(String name) throws IOException; + + /** + * Find resources with the given name that are available from this + * ResourceLoader or any of its parents. + * + * @param name the resource name + * @return an Iterator of {@link URL} objects for the resource + * @throws IOException if there was a problem locating the resources + */ + Iterator<URL> getAllResources(String name) throws IOException; + + //FIXME this is temporary to work around classloader problems with SDO when running in Tomcat + ClassLoader getClassLoader(); + +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/impl/ResourceLoaderImpl.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/impl/ResourceLoaderImpl.java new file mode 100644 index 0000000000..5f83596f19 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/java/org/apache/tuscany/common/resource/impl/ResourceLoaderImpl.java @@ -0,0 +1,175 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.resource.impl; + +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.net.URL; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.tuscany.common.resource.ResourceLoader; + +/** + * Default implementation of the ResourceLoader interface. + * + * @version $Rev: 369102 $ $Date: 2006-01-14 13:48:56 -0800 (Sat, 14 Jan 2006) $ + */ +public class ResourceLoaderImpl implements ResourceLoader { + private final WeakReference<ClassLoader> classLoaderReference; + private WeakReference<GeneratedClassLoader> generatedClassLoaderReference; + private final List<ResourceLoader> parents; + + /** + * A class loader that allows new classes to be defined from an array of bytes + */ + private class GeneratedClassLoader extends ClassLoader { + + /** + * Constructs a new ResourceLoaderImpl.GeneratedClassLoader. + */ + public GeneratedClassLoader(ClassLoader classLoader) { + super(classLoader); + } + + /** + * Converts an array of bytes into a Class. + * @param bytes + * @return + */ + private Class<?> addClass(byte[] bytes) { + return defineClass(null, bytes, 0, bytes.length); + } + + } + + /** + * Constructs a new ResourceLoaderImpl. + * @param classLoader + */ + public ResourceLoaderImpl(ClassLoader classLoader) { + classLoaderReference = new WeakReference(classLoader); + generatedClassLoaderReference = new WeakReference(new GeneratedClassLoader(classLoader)); + ClassLoader parentCL = classLoader.getParent(); + parents = parentCL == null ? Collections.EMPTY_LIST : Collections.singletonList(new ResourceLoaderImpl(parentCL)); + } + + + /** + * Return the classloader backing this resource loader. + * + * @return the classloader that backs this resource loader + * @throws IllegalStateException if the classloader has been garbage collected + */ + //FIXME Temporary used to set the classloader on the thread context, need to changed to private + public ClassLoader getClassLoader() throws IllegalStateException { + ClassLoader cl = classLoaderReference.get(); + if (cl == null) { + throw new IllegalStateException("Referenced ClassLoader has been garbage collected"); + } + return cl; + } + + public List<ResourceLoader> getParents() { + return parents; + } + + public Class loadClass(String name) throws ClassNotFoundException { + GeneratedClassLoader cl = generatedClassLoaderReference.get(); + if (cl != null) { + return Class.forName(name, true, cl); + } else { + return Class.forName(name, true, getClassLoader()); + } + } + + public Class<?> addClass(byte[] bytes) { + GeneratedClassLoader cl = generatedClassLoaderReference.get(); + if (cl == null) { + cl=new GeneratedClassLoader(getClassLoader()); + generatedClassLoaderReference = new WeakReference(cl); + } + return cl.addClass(bytes); + } + + public Iterator<URL> getResources(String name) throws IOException { + // This implementation used to cache but users are not likely + // to ask for the same resource multiple times. + + // Create a new set, add all the resources visible from the current ClassLoader + Set<URL> set = new HashSet(); + ClassLoader classLoader = getClassLoader(); + for (Enumeration<URL> e = classLoader.getResources(name); e.hasMoreElements();) { + set.add(e.nextElement()); + } + + // Remove the resources visible from the parent ClassLoaders + for (ResourceLoader parent : getParents()) { + for (Iterator<URL> i = parent.getAllResources(name); i.hasNext();) { + set.remove(i.next()); + } + } + return set.iterator(); + } + + public Iterator<URL> getAllResources(String name) throws IOException { + return new EnumerationIterator(getClassLoader().getResources(name)); + } + + public URL getResource(String name) throws IOException { + return getClassLoader().getResource(name); + } + + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof ResourceLoaderImpl)) { + return false; + } + final ResourceLoaderImpl other = (ResourceLoaderImpl) obj; + return getClassLoader() == other.getClassLoader(); + } + + public int hashCode() { + return getClassLoader().hashCode(); + } + + private static class EnumerationIterator<E> implements Iterator<E> { + private final Enumeration<E> e; + + public EnumerationIterator(Enumeration<E> e) { + this.e = e; + } + + public boolean hasNext() { + return e.hasMoreElements(); + } + + public E next() { + return e.nextElement(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.logging.LogProvider b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.logging.LogProvider new file mode 100644 index 0000000000..6cf181502c --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.logging.LogProvider @@ -0,0 +1 @@ +org.apache.tuscany.common.logging.impl.JSR47LogProviderImpl
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.resource.loader.ResourceLoaderProvider b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.resource.loader.ResourceLoaderProvider new file mode 100644 index 0000000000..70456ec1d0 --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/META-INF/services/org.apache.tuscany.common.resource.loader.ResourceLoaderProvider @@ -0,0 +1 @@ +org.apache.tuscany.common.resource.loader.impl.ResourceLoaderProviderImpl
\ No newline at end of file diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/org/apache/tuscany/common/Messages.properties b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/org/apache/tuscany/common/Messages.properties new file mode 100644 index 0000000000..4581e44bff --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/main/resources/org/apache/tuscany/common/Messages.properties @@ -0,0 +1,25 @@ +# Copyright (c) 2005 The Apache Software Foundation or its licensors, as applicable. +# +# 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. +# ==================================================================== +# To code developer: +# Do NOT change the properties between this line and the +# "%%% END OF TRANSLATED PROPERTIES %%%" line. +# Make a new property name, append to the end of the file and change +# the code to use the new property. +# ==================================================================== + +# ===================================================================== +# %%% END OF TRANSLATED PROPERTIES %%% +# ===================================================================== +# NLS_MESSAGEFORMAT_ALL diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/java/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase.java b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/java/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase.java new file mode 100644 index 0000000000..011ccf63ab --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/java/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase.java @@ -0,0 +1,145 @@ +/** + * + * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. + * + * 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.apache.tuscany.common.monitor.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import junit.framework.TestCase; + +import org.apache.tuscany.common.monitor.MonitorFactory; +import org.apache.tuscany.common.monitor.LogLevel; + +/** + * @version $Rev$ $Date$ + */ +public class JavaLoggingTestCase extends TestCase { + private static final Logger logger = Logger.getLogger(Monitor.class.getName()); + private static final MockHandler handler = new MockHandler(); + + private MonitorFactory factory; + + /** + * Smoke test to ensure the logger is working + */ + public void testLogger() { + logger.info("test"); + assertEquals(1, handler.logs.size()); + } + + public void testUnloggedEvent() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventNotToLog(); + assertEquals(0, handler.logs.size()); + } + + public void testEventWithNoArgs() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithNoArgs(); + assertEquals(1, handler.logs.size()); + LogRecord record = handler.logs.get(0); + assertEquals(Level.INFO, record.getLevel()); + assertEquals(logger.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithNoArgs", record.getMessage()); + } + + public void testEventWithAnnotation() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithAnnotation(); + assertEquals(1, handler.logs.size()); + LogRecord record = handler.logs.get(0); + assertEquals(Level.INFO, record.getLevel()); + assertEquals(logger.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithAnnotation", record.getMessage()); + } + + public void testEventWithThrowable() { + Exception e = new Exception(); + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithThrowable(e); + assertEquals(1, handler.logs.size()); + LogRecord record = handler.logs.get(0); + assertEquals(Level.WARNING, record.getLevel()); + assertEquals(logger.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithThrowable", record.getMessage()); + assertSame(e, record.getThrown()); + } + + public void testEventWithOneArg() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithOneArg("ARG"); + assertEquals(1, handler.logs.size()); + LogRecord record = handler.logs.get(0); + assertEquals(Monitor.class.getName() + "#eventWithOneArg", record.getMessage()); + assertEquals(Monitor.class.getName(), record.getResourceBundleName()); + } + + protected void setUp() throws Exception { + super.setUp(); + logger.setUseParentHandlers(false); + logger.addHandler(handler); + handler.flush(); + + String sourceClass = Monitor.class.getName(); + Properties levels = new Properties(); + levels.setProperty(sourceClass + "#eventWithNoArgs", "INFO"); + levels.setProperty(sourceClass + "#eventWithOneArg", "INFO"); + levels.setProperty(sourceClass + "#eventWithThrowable", "WARNING"); + factory = new JavaLoggingMonitorFactory(levels, Level.FINE, sourceClass); + } + + protected void tearDown() throws Exception { + logger.removeHandler(handler); + handler.flush(); + super.tearDown(); + } + + public static class MockHandler extends Handler { + List<LogRecord> logs = new ArrayList(); + + public void publish(LogRecord record) { + logs.add(record); + } + + public void flush() { + logs.clear(); + } + + public void close() throws SecurityException { + } + } + + public static interface Monitor { + void eventNotToLog(); + + void eventWithNoArgs(); + + void eventWithOneArg(String msg); + + void eventWithTwoArgs(String m1, String m2); + + void eventWithThrowable(Exception e); + + @LogLevel("INFO") + void eventWithAnnotation(); + } +} diff --git a/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/resources/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase$Monitor.properties b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/resources/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase$Monitor.properties new file mode 100644 index 0000000000..e16fa437fa --- /dev/null +++ b/sca-java-1.x/tags/java-stable-20060304/sca/common/src/test/resources/org/apache/tuscany/common/monitor/impl/JavaLoggingTestCase$Monitor.properties @@ -0,0 +1 @@ +org.apache.tuscany.common.monitor.impl.JavaLoggingTestCase$Monitor#eventWithOneArg=Log message with arg={0}
\ No newline at end of file |