xbean-3.7/0000755000175000017500000000000011610661040012347 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/0000755000175000017500000000000011610661040015424 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/pom.xml0000644000175000017500000000265011373256143016756 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-classpath bundle Apache XBean :: ClassPath xbean-3.7/xbean-classpath/src/0000755000175000017500000000000011610661040016213 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/0000755000175000017500000000000011610661040017137 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/resources/0000755000175000017500000000000011610661040021151 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/resources/META-INF/0000755000175000017500000000000011610661040022311 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/0000755000175000017500000000000011610661040020060 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/0000755000175000017500000000000011610661040020647 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/apache/0000755000175000017500000000000011610661040022070 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661040023165 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/0000755000175000017500000000000011610661040025147 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/SystemClassPath.java0000644000175000017500000000521410473277125031120 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; import java.net.URLClassLoader; import java.net.URL; import java.io.File; public class SystemClassPath extends SunURLClassPath { private URLClassLoader sysLoader; public void addJarsToPath(File dir) throws Exception { this.addJarsToPath(dir, getSystemLoader()); this.rebuildJavaClassPathVariable(); } public void addJarToPath(URL jar) throws Exception { //System.out.println("[|] SYSTEM "+jar.toExternalForm()); this.addJarToPath(jar, getSystemLoader()); this.rebuildJavaClassPathVariable(); } public ClassLoader getClassLoader() { try { return getSystemLoader(); } catch (Exception e) { throw new RuntimeException(e); } } private URLClassLoader getSystemLoader() throws Exception { if (sysLoader == null) { sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); } return sysLoader; } private void rebuildJavaClassPathVariable() throws Exception { sun.misc.URLClassPath cp = getURLClassPath(getSystemLoader()); URL[] urls = cp.getURLs(); //for (int i=0; i < urls.length; i++){ // System.out.println(urls[i].toExternalForm()); //} if (urls.length < 1) return; StringBuffer path = new StringBuffer(urls.length * 32); File s = new File(urls[0].getFile()); path.append(s.getPath()); //System.out.println(s.getPath()); for (int i = 1; i < urls.length; i++) { path.append(File.pathSeparator); s = new File(urls[i].getFile()); //System.out.println(s.getPath()); path.append(s.getPath()); } try { System.setProperty("java.class.path", path.toString()); } catch (Exception e) { } } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/ClassPath.java0000644000175000017500000000203410473277125027710 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; import java.io.File; import java.net.URL; public interface ClassPath { ClassLoader getClassLoader(); void addJarsToPath(File dir) throws Exception; void addJarToPath(URL dir) throws Exception; } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/ClassPathFactory.java0000644000175000017500000000324410473277125031244 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; public class ClassPathFactory { public static ClassPath createClassPath(String name){ if (name.equalsIgnoreCase("tomcat")) { return new TomcatClassPath(); } else if (name.equalsIgnoreCase("tomcat-common")) { return new TomcatClassPath(); } else if (name.equalsIgnoreCase("tomcat-webapp")) { return new TomcatWebAppClassPath(); } else if (name.equalsIgnoreCase("bootstrap")) { return new SystemClassPath(); } else if (name.equalsIgnoreCase("system")) { return new SystemClassPath(); } else if (name.equalsIgnoreCase("thread")) { return new ContextClassPath(); } else if (name.equalsIgnoreCase("context")) { return new ContextClassPath(); } else { return new ContextClassPath(); } } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/TomcatWebAppClassPath.java0000644000175000017500000000213710473277125032163 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; public class TomcatWebAppClassPath extends TomcatClassPath { public TomcatWebAppClassPath() { this(getContextClassLoader()); } public TomcatWebAppClassPath(ClassLoader classLoader){ super(classLoader); } protected void rebuild() { } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/maven/0000755000175000017500000000000011610661040026255 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/maven/MavenResolver.java0000644000175000017500000000450110473277125031725 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath.maven; import java.net.URL; /** * Transitively resolves dependencies using Maven. * * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class MavenResolver { // private final ArtifactFactory artifactFactory; // private final Set artifacts = new HashSet(); /** * Creates a new resolver. */ public MavenResolver() { // artifactFactory = new DefaultArtifactFactory(); } /** * Add an artifact to resolve. * @param groupId the id of the group to which the dependency belongs * @param artifactId the id of the artifact to resolve * @param version the version of the artifact */ public void addArtifact(String groupId, String artifactId, String version) { addArtifact(groupId, artifactId, version, "jar"); } /** * Add an artifact to resolve. * @param groupId the id of the group to which the dependency belongs * @param artifactId the id of the artifact to resolve * @param version the version of the artifact * @param type the type of the artifact */ public void addArtifact(String groupId, String artifactId, String version, String type) { // Artifact artifact = artifactFactory.createArtifact( groupId, artifactId, version, "runtime", type ); // artifacts.add(artifact); } /** * Downloads all of the artificts, all of the artificts they depend on and so on. * @return the URLs to all artifacts */ public URL[] resolve() { return null; } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/ContextClassPath.java0000644000175000017500000000324410473277125031261 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; import java.io.File; import java.net.URLClassLoader; import java.net.URL; public class ContextClassPath extends SunURLClassPath { public ClassLoader getClassLoader() { return getContextClassLoader(); } public void addJarsToPath(File dir) throws Exception { ClassLoader contextClassLoader = getContextClassLoader(); if (contextClassLoader instanceof URLClassLoader) { URLClassLoader loader = (URLClassLoader) contextClassLoader; this.addJarsToPath(dir, loader); } } public void addJarToPath(URL jar) throws Exception { ClassLoader contextClassLoader = getContextClassLoader(); if (contextClassLoader instanceof URLClassLoader) { URLClassLoader loader = (URLClassLoader) contextClassLoader; this.addJarToPath(jar, loader); } } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/SunURLClassPath.java0000644000175000017500000000643610473277125030773 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; public abstract class SunURLClassPath implements ClassPath { public static ClassLoader getContextClassLoader() { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return Thread.currentThread().getContextClassLoader(); } }); } private java.lang.reflect.Field ucpField; protected void addJarToPath(final URL jar, final URLClassLoader loader) throws Exception { this.getURLClassPath(loader).addURL(jar); } protected void addJarsToPath(final File dir, final URLClassLoader loader) throws Exception { if (dir == null || !dir.exists()) return; //System.out.println("DIR "+dir); // Get the list of jars and zips String[] jarNames = dir.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { //System.out.println("FILE "+name); return (name.endsWith(".jar") || name.endsWith(".zip")); } }); // Create URLs from them final URL[] jars = new URL[jarNames.length]; for (int j = 0; j < jarNames.length; j++) { jars[j] = new File(dir, jarNames[j]).toURL(); } sun.misc.URLClassPath path = getURLClassPath(loader); for (int i = 0; i < jars.length; i++) { //System.out.println("URL "+jars[i]); path.addURL(jars[i]); } } protected sun.misc.URLClassPath getURLClassPath(URLClassLoader loader) throws Exception { return (sun.misc.URLClassPath) getUcpField().get(loader); } private java.lang.reflect.Field getUcpField() throws Exception { if (ucpField == null) { // Add them to the URLClassLoader's classpath ucpField = (java.lang.reflect.Field) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { java.lang.reflect.Field ucp = null; try { ucp = URLClassLoader.class.getDeclaredField("ucp"); ucp.setAccessible(true); } catch (Exception e2) { e2.printStackTrace(); } return ucp; } }); } return ucpField; } } xbean-3.7/xbean-classpath/src/main/java/org/apache/xbean/classpath/TomcatClassPath.java0000644000175000017500000001361510473277125031067 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; public class TomcatClassPath extends SunURLClassPath { /** * The Tomcat Common ClassLoader */ private final ClassLoader classLoader; /** * The addRepository(String jar) method of the Tomcat Common ClassLoader */ private Method addRepositoryMethod; private Method addURLMethod; public TomcatClassPath() { this(getCommonLoader(getContextClassLoader()).getParent()); } public TomcatClassPath(ClassLoader classLoader){ this.classLoader = classLoader; try { addRepositoryMethod = getAddRepositoryMethod(); } catch (Exception tomcat4Exception) { // Must be tomcat 5 try { addURLMethod = getAddURLMethod(); } catch (Exception tomcat5Exception) { throw new RuntimeException("Failed accessing classloader for Tomcat 4 or 5", tomcat5Exception); } } } private static ClassLoader getCommonLoader(ClassLoader loader) { if (loader.getClass().getName().equals("org.apache.catalina.loader.StandardClassLoader")) { return loader; } else { return getCommonLoader(loader.getParent()); } } public ClassLoader getClassLoader() { return classLoader; } public void addJarsToPath(File dir) throws Exception { String[] jarNames = dir.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".jar") || name.endsWith(".zip")); } }); if (jarNames == null) { return; } for (int j = 0; j < jarNames.length; j++) { this.addJarToPath(new File(dir, jarNames[j]).toURL()); } rebuild(); } public void addJarToPath(URL jar) throws Exception { this._addJarToPath(jar); rebuild(); } public void _addJarToPath(URL jar) throws Exception { String path = jar.toExternalForm(); this.addRepository(path); } public void addRepository(String path) throws Exception { if (addRepositoryMethod != null){ addRepositoryMethod.invoke(getClassLoader(), new Object[]{path}); } else { addURLMethod.invoke(getClassLoader(), new Object[]{new File(path).toURL()}); } } protected void rebuild() { try { sun.misc.URLClassPath cp = getURLClassPath((URLClassLoader) getClassLoader()); URL[] urls = cp.getURLs(); //for (int i=0; i < urls.length; i++){ // System.out.println(urls[i].toExternalForm()); //} if (urls.length < 1) return; StringBuffer path = new StringBuffer(urls.length * 32); File s = new File(urls[0].getFile()); path.append(s.getPath()); //System.out.println(s.getPath()); for (int i = 1; i < urls.length; i++) { path.append(File.pathSeparator); s = new File(urls[i].getFile()); //System.out.println(s.getPath()); path.append(s.getPath()); } System.setProperty("java.class.path", path.toString()); } catch (Exception e) { } } /** * This method gets the Tomcat StandardClassLoader.addRepository method * via reflection. This allows us to call the addRepository method for * Tomcat integration, but doesn't require us to include or ship any * Tomcat libraries. * * @return URLClassLoader.addURL method instance */ private Method getAddURLMethod() throws Exception { return (Method) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Method method = null; try { Class clazz = URLClassLoader.class; method = clazz.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); return method; } catch (Exception e2) { e2.printStackTrace(); } return method; } }); } private Method getAddRepositoryMethod() throws Exception { return (Method) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Method method = null; try { Class clazz = getClassLoader().getClass(); method = clazz.getDeclaredMethod("addRepository", new Class[]{String.class}); method.setAccessible(true); return method; } catch (Exception e2) { throw (IllegalStateException) new IllegalStateException("Unable to find or access the addRepository method in StandardClassLoader").initCause(e2); } } }); } } xbean-3.7/xbean-classpath/src/test/0000755000175000017500000000000011610661040017172 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/resources/0000755000175000017500000000000011610661040021204 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/0000755000175000017500000000000011610661040020113 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/org/0000755000175000017500000000000011610661040020702 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/org/apache/0000755000175000017500000000000011610661040022123 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661040023220 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/org/apache/xbean/classpath/0000755000175000017500000000000011610661040025202 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/test/java/org/apache/xbean/classpath/SystemClassPathTest.java0000644000175000017500000000334610473277125032017 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classpath; /** * @version $Revision$ $Date$ */ import junit.framework.TestCase; public class SystemClassPathTest extends TestCase { public void testAddJarToPath() throws Exception { SystemClassPath systemClassPath = new SystemClassPath(); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); try { systemClassLoader.loadClass("groovy.lang.GroovyShell"); fail("Class already exists"); } catch (ClassNotFoundException e) { // this should fail } // URL groovyJar = new URL("http://www.ibiblio.org/maven/groovy/jars/groovy-SNAPSHOT.jar"); // systemClassPath.addJarToPath(groovyJar); // // try { // systemClassLoader.loadClass("groovy.lang.GroovyShell"); // } catch (ClassNotFoundException e) { // // this should fail pass // fail("Class already exists"); // } } } xbean-3.7/xbean-classpath/src/test/java/org/xbean/0000755000175000017500000000000011610661040021777 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/site/0000755000175000017500000000000011610661040017157 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/site/apt/0000755000175000017500000000000011610661040017743 5ustar drazzibdrazzibxbean-3.7/xbean-classpath/src/site/site.xml0000644000175000017500000000210010473277125020653 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/xbean-spring/0000755000175000017500000000000011610661036014751 5ustar drazzibdrazzibxbean-3.7/xbean-spring/pom.xml0000644000175000017500000001420611373256143016276 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-spring bundle Apache XBean :: Spring xbean-spring provides a schema-driven proprietary namespace handler for spring contexts com.thoughtworks.qdox*;resolution:=optional, org.apache.tools.ant*;resolution:=optional, org.springframework.core;resolution:=optional, org.springframework.web*;resolution:=optional, * commons-logging commons-logging org.springframework spring-beans provided org.springframework spring-context provided org.springframework spring-web true com.thoughtworks.qdox qdox true ant ant true src/test/resources target/test-generated org.apache.maven.plugins maven-surefire-plugin **/BeerUsingXBeanNSTest.java maven-antrun-plugin process-classes run org.apache.felix maven-bundle-plugin true com.thoughtworks.qdox*;resolution:=optional, org.apache.tools.ant*;resolution:=optional, org.springframework.core;resolution:=optional, org.springframework.web*;resolution:=optional, * META-INF.services.org.apache.xbean.spring.*,META-INF.services.org.xbean.spring <_failok>true xbean-3.7/xbean-spring/src/0000755000175000017500000000000011610661036015540 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/0000755000175000017500000000000011610661036016464 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/0000755000175000017500000000000011610661036020476 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/META-INF/0000755000175000017500000000000011610661036021636 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/org/0000755000175000017500000000000011610661036021265 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/org/apache/0000755000175000017500000000000011610661036022506 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/org/apache/xbean/0000755000175000017500000000000011610661036023603 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/org/apache/xbean/spring/0000755000175000017500000000000011610661036025105 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/resources/org/apache/xbean/spring/spring-beans.xsd0000644000175000017500000007251711373033431030227 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/main/java/0000755000175000017500000000000011610661036017405 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/0000755000175000017500000000000011610661036020174 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/0000755000175000017500000000000011610661036021415 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661036022512 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/0000755000175000017500000000000011610661036024014 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/0000755000175000017500000000000011610661036026002 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/XsdGenerator.java0000644000175000017500000002333411252465671031270 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XsdGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public XsdGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { // TODO can only handle 1 schema document so far... File file = destFile; log.log("Generating XSD file: " + file + " for namespace: " + namespaceMapping.getNamespace()); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateSchema(out, namespaceMapping); } finally { out.close(); } } public void generateSchema(PrintWriter out, NamespaceMapping namespaceMapping) { out.println(""); out.println(""); out.println(); out.println(""); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementMapping(out, namespaceMapping, element); } out.println(); out.println(""); } private void generateElementMapping(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { out.println(); out.println(" "); String localName = element.getElementName(); out.println(" "); if (!isEmptyString(element.getDescription())) { out.println(" "); out.println(" "); out.println(" "); } out.println(" "); int complexCount = 0; for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (!namespaceMapping.isSimpleType(attributeMapping.getType())) { complexCount++; } } if (complexCount > 0) { out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (!namespaceMapping.isSimpleType(attributeMapping.getType())) { generateElementMappingComplexProperty(out, namespaceMapping, attributeMapping); } } out.println(" "); out.println(" "); } for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (namespaceMapping.isSimpleType(attributeMapping.getType())) { generateElementMappingSimpleProperty(out, attributeMapping); } else if (!attributeMapping.getType().isCollection()) { generateElementMappingComplexPropertyAsRef(out, attributeMapping); } } generateIDAttributeMapping(out, namespaceMapping, element); out.println(" "); out.println(" "); out.println(" "); out.println(); } private boolean isEmptyString(String str) { if (str == null) { return true; } for (int i = 0; i < str.length(); i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } private void generateIDAttributeMapping(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if ("id".equals(attributeMapping.getAttributeName())) { return; } } out.println(" "); } private void generateElementMappingSimpleProperty(PrintWriter out, AttributeMapping attributeMapping) { // types with property editors need to be xs:string in the schema to validate String type = attributeMapping.getPropertyEditor() != null ? Utils.getXsdType(Type.newSimpleType(String.class.getName())) : Utils.getXsdType(attributeMapping.getType()); if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); } else { out.println(" "); } } private void generateElementMappingComplexPropertyAsRef(PrintWriter out, AttributeMapping attributeMapping) { if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); } else { out.println(" "); } } private void generateElementMappingComplexProperty(PrintWriter out, NamespaceMapping namespaceMapping, AttributeMapping attributeMapping) { Type type = attributeMapping.getType(); List types; if (type.isCollection()) { types = Utils.findImplementationsOf(namespaceMapping, type.getNestedType()); } else { types = Utils.findImplementationsOf(namespaceMapping, type); } String maxOccurs = type.isCollection() || "java.util.Map".equals(type.getName()) ? "unbounded" : "1"; out.println(" "); if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); } out.println(" "); if (types.isEmpty()) { // We don't know the type because it's generic collection. Allow folks to insert objets from any namespace out.println(" "); } else { out.println(" "); for (Iterator iterator = types.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.println(" "); } out.println(" "); out.println(" "); } out.println(" "); out.println(" "); } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/XmlWriter.java0000644000175000017500000001116610473277125030617 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.PrintWriter; import java.io.Writer; import java.util.LinkedList; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XmlWriter { private PrintWriter writer; private LinkedList elementStack = new LinkedList(); private boolean tagInProgress; private int depth; private String lineIndenter; private String encoding; private String docType; private boolean readyForNewLine; private boolean tagIsEmpty; public XmlWriter(PrintWriter writer, String lineIndenter) { this(writer, lineIndenter, null, null); } public XmlWriter(Writer writer, String lineIndenter) { this(new PrintWriter(writer), lineIndenter); } public XmlWriter(PrintWriter writer) { this(writer, null, null); } public XmlWriter(Writer writer) { this(new PrintWriter(writer)); } public XmlWriter(PrintWriter writer, String lineIndenter, String encoding, String doctype) { this.writer = writer; this.lineIndenter = lineIndenter; this.encoding = encoding; this.docType = doctype; if (docType != null || encoding != null) { writeDocumentHeaders(); } } public XmlWriter(Writer writer, String lineIndenter, String encoding, String doctype) { this(new PrintWriter(writer), lineIndenter, encoding, doctype); } public XmlWriter(PrintWriter writer, String encoding, String doctype) { this(writer, " ", encoding, doctype); } public XmlWriter(Writer writer, String encoding, String doctype) { this(new PrintWriter(writer), encoding, doctype); } public void startElement(String name) { tagIsEmpty = false; finishTag(); write("<"); write(name); elementStack.addLast(name); tagInProgress = true; depth++; readyForNewLine = true; tagIsEmpty = true; } public void writeText(String text) { writeText(text, true); } public void writeMarkup(String text) { writeText(text, false); } private void writeText(String text, boolean escapeHtml) { readyForNewLine = false; tagIsEmpty = false; finishTag(); if (escapeHtml) { text = text.replaceAll("&", "&"); text = text.replaceAll("<", "<"); text = text.replaceAll(">", ">"); } write(text); } public void addAttribute(String key, String value) { write(" "); write(key); write("=\""); write(value); write("\""); } public void endElement() { depth--; if (tagIsEmpty) { write("/"); readyForNewLine = false; finishTag(); elementStack.removeLast(); } else { finishTag(); write(""); } readyForNewLine = true; } private void write(String str) { writer.write(str); } private void finishTag() { if (tagInProgress) { write(">"); } tagInProgress = false; if (readyForNewLine) { endOfLine(); } readyForNewLine = false; tagIsEmpty = false; } protected void endOfLine() { write("\n"); for (int i = 0; i < depth; i++) { write(lineIndenter); } } private void writeDocumentHeaders() { write(""); endOfLine(); if (docType != null) { write(""); endOfLine(); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/SchemaGenerator.java0000644000175000017500000000354210473277125031730 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.IOException; import java.util.Iterator; import java.util.Set; /** * @version $Revision: 434369 $ */ public class SchemaGenerator { private final MappingLoader mappingLoader; private final GeneratorPlugin[] plugins; private final LogFacade log; public SchemaGenerator(LogFacade log, MappingLoader mappingLoader, GeneratorPlugin[] plugins) { this.log = log; this.mappingLoader = mappingLoader; this.plugins = plugins; } public void generate() throws IOException { Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { log.log("Warning: no namespaces found!"); } for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.generate(namespaceMapping); } } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/ParameterMapping.java0000644000175000017500000000233010473277125032107 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; /** * @version $Rev$ $Date$ */ public class ParameterMapping { private final String name; private final Type type; public ParameterMapping(String name, Type type) { this.name = name; this.type = type; } public String getName() { return name; } public Type getType() { return type; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/Utils.java0000644000175000017500000001177410537745034027767 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public final class Utils { public static final String XBEAN_ANNOTATION = "org.apache.xbean.XBean"; public static final String PROPERTY_ANNOTATION = "org.apache.xbean.Property"; private Utils() { } public static String decapitalise(String value) { if (value == null || value.length() == 0) { return value; } return value.substring(0, 1).toLowerCase() + value.substring(1); } public static boolean isSimpleType(Type type) { if (type.isPrimitive()) { return true; } if (type.isCollection()) { return false; } String name = type.getName(); if (name.equals("java.lang.Class") || name.equals("javax.xml.namespace.QName")) { return true; } return hasPropertyEditor(name); } private static boolean hasPropertyEditor(String type) { Class theClass; try { theClass = loadClass(type); // lets see if we can find a property editor for this type PropertyEditor editor = PropertyEditorManager.findEditor(theClass); return editor != null; } catch (Throwable e) { System.out.println("Warning, could not load class: " + type + ": " + e); return false; } } /** * Attempts to load the class on the current thread context class loader or * the class loader which loaded us */ private static Class loadClass(String name) throws ClassNotFoundException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { return contextClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } } return Utils.class.getClassLoader().loadClass(name); } public static String getXsdType(Type type) { String name = type.getName(); String xsdType = (String) XSD_TYPES.get(name); if (xsdType == null) { xsdType = "xs:string"; } return xsdType; } public static final Map XSD_TYPES; static { // TODO check these XSD types are right... Map map = new HashMap(); map.put(String.class.getName(), "xs:string"); map.put(Boolean.class.getName(), "xs:boolean"); map.put(boolean.class.getName(), "xs:boolean"); map.put(Byte.class.getName(), "xs:byte"); map.put(byte.class.getName(), "xs:byte"); map.put(Short.class.getName(), "xs:short"); map.put(short.class.getName(), "xs:short"); map.put(Integer.class.getName(), "xs:integer"); map.put(int.class.getName(), "xs:integer"); map.put(Long.class.getName(), "xs:long"); map.put(long.class.getName(), "xs:long"); map.put(Float.class.getName(), "xs:float"); map.put(float.class.getName(), "xs:float"); map.put(Double.class.getName(), "xs:double"); map.put(double.class.getName(), "xs:double"); map.put(java.util.Date.class.getName(), "xs:date"); map.put(java.sql.Date.class.getName(), "xs:date"); map.put("javax.xml.namespace.QName", "xs:QName"); XSD_TYPES = Collections.unmodifiableMap(map); } public static List findImplementationsOf(NamespaceMapping namespaceMapping, Type type) { List elements = new ArrayList(); String nestedTypeName = type.getName(); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); if (element.getClassName().equals(nestedTypeName) || element.getInterfaces().contains(nestedTypeName) || element.getSuperClasses().contains(nestedTypeName)) { elements.add(element); } } return elements; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/LogFacade.java0000644000175000017500000000172410473277125030466 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; public interface LogFacade { void log(String message); void log(String message, int level); } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/AttributeMapping.java0000644000175000017500000000557310473277125032146 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class AttributeMapping implements Comparable { private final String attributeName; private final String propertyName; private final String description; private final Type type; private final String value; private final boolean fixed; private final boolean required; private final String propertyEditor; public AttributeMapping(String attributeName, String propertyName, String description, Type type, String value, boolean fixed, boolean required, String propertyEditor) { this.propertyEditor = propertyEditor; if (attributeName == null) throw new NullPointerException("attributeName"); if (propertyName == null) throw new NullPointerException("propertyName"); if (type == null) throw new NullPointerException("type"); this.attributeName = attributeName; this.propertyName = propertyName; if (description == null) description = ""; this.description = description; this.type = type; this.value = value; this.fixed = fixed; this.required = required; } public String getAttributeName() { return attributeName; } public String getPropertyName() { return propertyName; } public String getDescription() { return description; } public Type getType() { return type; } public String getValue() { return value; } public boolean isFixed() { return fixed; } public boolean isRequired() { return required; } public int hashCode() { return attributeName.hashCode(); } public boolean equals(Object obj) { if (obj instanceof AttributeMapping) { return attributeName.equals(((AttributeMapping) obj).attributeName); } return false; } public int compareTo(Object obj) { return attributeName.compareTo(((AttributeMapping) obj).attributeName); } public String getPropertyEditor() { return propertyEditor; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/MapMapping.java0000644000175000017500000000336010575233120030676 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; public class MapMapping { private String entryName; private String keyName; private boolean flat; private String dupsMode; private String defaultKey; public MapMapping(String entryName, String keyName, boolean flat, String dupsMode, String defaultKey) { this.entryName = entryName; this.keyName = keyName; this.flat = flat; this.dupsMode = dupsMode; this.defaultKey = defaultKey; } public String getEntryName() { return entryName; } public String getKeyName() { return keyName; } public boolean isFlat() { return flat; } public String getDupsMode() { return dupsMode; } public String getDefaultKey() { return defaultKey; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/WikiDocumentationGenerator.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/WikiDocumentationGenerator.ja0000644000175000017500000002166711251237773033646 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * @author Hiram Chirino * @version $Id$ * @since 1.0 */ public class WikiDocumentationGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public WikiDocumentationGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); File file = new File(destFile.getParentFile(), destFile.getName() + ".wiki"); log.log("Generating WIKI documentation file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateDocumentation(out, namespaceMapping); } finally { out.close(); } } private void generateDocumentation(PrintWriter out, NamespaceMapping namespaceMapping) { HashMap refercencedTypes = new HashMap(); // Build of map of types that are referenced by element types. for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attribute = (AttributeMapping) iterator.next(); Type type = getNestedType( attribute.getType() ); if( namespaceMapping.isSimpleType( type) ) continue; if( !refercencedTypes.containsKey(type.getName()) ) refercencedTypes.put(type.getName(), new ArrayList()); } } // Add all the elements that implement those types. for (Iterator iter = refercencedTypes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String type = (String) entry.getKey(); ArrayList implementations = (ArrayList) entry.getValue(); for (Iterator iterator = namespaceMapping.getElements().iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); // Check to see if the class is matches boolean matched=false; if (type.equals(element.getClassName())) { implementations.add(element); matched=true; } // Perhaps a super class matches. if(!matched) { for (Iterator j = element.getSuperClasses().iterator(); j.hasNext();) { String t = (String) j.next(); if( type.equals(t) ) { implementations.add(element); matched=true; break; } } } // Or it might be an interface. if(!matched) { for (Iterator j = element.getInterfaces().iterator(); j.hasNext();) { String t = (String) j.next(); if( type.equals(t) ) { implementations.add(element); matched=true; break; } } } } } // Remove any entries that did not have associated elements for (Iterator iter = refercencedTypes.values().iterator(); iter.hasNext();) { ArrayList implementations = (ArrayList) iter.next(); if( implementations.isEmpty() ) iter.remove(); } generateElementsByType(out, namespaceMapping, refercencedTypes); generateElementsDetail(out, namespaceMapping, refercencedTypes); generateElementsIndex(out, namespaceMapping, refercencedTypes); } private Type getNestedType(Type type) { if( type.isCollection() ) { return getNestedType(type.getNestedType()); } else { return type; } } private void generateElementsByType(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { out.println("h3. Elements By Type"); for (Iterator iter = refercencedTypes.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry) iter.next(); String className = (String) entry.getKey(); Collection elements = (Collection) entry.getValue(); out.println("{anchor:"+className+"-types}"); out.println("h4. The _["+className+"|#"+className+"-types]_ Type Implementations"); for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.println(" | _[<"+element.getElementName() +">|#"+element.getElementName() +"-element]_ | {html}"+element.getDescription()+"{html} |"); } out.println(); } out.println(); } private void generateElementsIndex(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { out.println("h3. Element Index"); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); out.println(" | _[<"+element.getElementName() +">|#"+element.getElementName() +"-element]_ | {html}"+element.getDescription()+"{html} |"); } out.println(); } private void generateElementsDetail(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementDetail(out, namespaceMapping, element, refercencedTypes); } } private void generateElementDetail(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element, HashMap refercencedTypes) { out.println("{anchor:" + element.getElementName() + "-element}"); out.println("h3. The _[<" + element.getElementName() + ">|#" + element.getElementName() + "-element]_ Element"); out.println(" {html}"+element.getDescription()+"{html}"); if( element.getAttributes().size() > 0 ) { out.println("h4. Properties"); out.println(" || Property Name || Type || Description ||"); for ( Iterator iterator = element.getAttributes().iterator(); iterator.hasNext(); ) { AttributeMapping attribute = (AttributeMapping) iterator.next(); Type type = attribute.getPropertyEditor() != null ? Type.newSimpleType(String.class.getName()): attribute.getType(); out.println(" | " + attribute.getAttributeName() + " | "+getTypeLink(type, refercencedTypes)+" | {html}"+attribute.getDescription()+"{html} |"); } } out.println(); } private String getTypeLink(Type type, HashMap refercencedTypes) { if (type.isCollection()) { return "(" + getTypeLink(type.getNestedType(), refercencedTypes) + ")\\*"; } else { if( refercencedTypes.containsKey(type.getName()) ) { return "_["+type.getName()+"|#"+type.getName()+"-types]_"; } else { return "_"+type.getName()+"_"; } } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/ElementMapping.java0000644000175000017500000001256310473277125031571 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class ElementMapping implements Comparable { private final String namespace; private final String elementName; private final String className; private final String description; private final boolean rootElement; private final String initMethod; private final String destroyMethod; private final String factoryMethod; private final String contentProperty; private final Set attributes; private final Map attributesByName; private final List constructors; private final List flatProperties; private final Map maps; private final Map flatCollections; private final List superClasses; private final HashSet interfaces; public ElementMapping(String namespace, String elementName, String className, String description, boolean rootElement, String initMethod, String destroyMethod, String factoryMethod, String contentProperty, Set attributes, List constructors, List flatProperties, Map maps, Map flatCollections, List superClasses, HashSet interfaces) { this.superClasses = superClasses; this.interfaces = interfaces; if (namespace == null) throw new NullPointerException("namespace"); if (elementName == null) throw new NullPointerException("elementName"); if (className == null) throw new NullPointerException("className"); if (attributes == null) throw new NullPointerException("attributes"); if (constructors == null) throw new NullPointerException("constructors"); this.namespace = namespace; this.elementName = elementName; this.className = className; this.description = description; this.rootElement = rootElement; this.initMethod = initMethod; this.destroyMethod = destroyMethod; this.factoryMethod = factoryMethod; this.contentProperty = contentProperty; this.constructors = constructors; this.attributes = Collections.unmodifiableSet(new TreeSet(attributes)); this.maps = Collections.unmodifiableMap(maps); this.flatProperties = Collections.unmodifiableList(flatProperties); this.flatCollections = Collections.unmodifiableMap(flatCollections); Map attributesByName = new HashMap(); for (Iterator iterator = attributes.iterator(); iterator.hasNext();) { AttributeMapping attribute = (AttributeMapping) iterator.next(); attributesByName.put(attribute.getAttributeName(), attribute); } this.attributesByName = Collections.unmodifiableMap(attributesByName); } public String getNamespace() { return namespace; } public String getElementName() { return elementName; } public String getClassName() { return className; } public String getDescription() { return description; } public boolean isRootElement() { return rootElement; } public String getInitMethod() { return initMethod; } public String getDestroyMethod() { return destroyMethod; } public String getFactoryMethod() { return factoryMethod; } public String getContentProperty() { return contentProperty; } public Set getAttributes() { return attributes; } public AttributeMapping getAttribute(String attributeName) { return (AttributeMapping) attributesByName.get(attributeName); } public Map getMapMappings() { return maps; } public MapMapping getMapMapping(String name) { return (MapMapping) maps.get(name); } public Map getFlatCollections() { return flatCollections; } public List getFlatProperties() { return flatProperties; } public List getConstructors() { return constructors; } public int hashCode() { return elementName.hashCode(); } public boolean equals(Object obj) { if (obj instanceof ElementMapping) { return elementName.equals(((ElementMapping) obj).elementName); } return false; } public int compareTo(Object obj) { return elementName.compareTo(((ElementMapping) obj).elementName); } public HashSet getInterfaces() { return interfaces; } public List getSuperClasses() { return superClasses; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/Type.java0000644000175000017500000000622010473277125027576 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.util.Set; import java.util.HashSet; import java.util.Collections; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class Type { private final String name; private final Type nestedType; private final boolean primitive; public static Type newSimpleType(String name) { if (name == null) throw new NullPointerException("type"); if (name.indexOf("[") >= 0 || name.indexOf("]") >= 0) { throw new IllegalArgumentException("Name can not contain '[' or ']' " + name); } return new Type(name, null); } public static Type newArrayType(String type, int dimensions) { if (type == null) throw new NullPointerException("type"); if (dimensions < 1) throw new IllegalArgumentException("dimensions must be atleast one"); StringBuffer buf = new StringBuffer(type.length() + (dimensions * 2)); buf.append(type); for (int i = 0; i < dimensions; i ++) { buf.append("[]"); } return new Type(buf.toString(), newSimpleType(type)); } public static Type newCollectionType(String collectionType, Type elementType) { if (collectionType == null) throw new NullPointerException("collectionType"); if (elementType == null) throw new NullPointerException("elementType"); return new Type(collectionType, elementType); } private Type(String name, Type nestedType) { this.name = name; this.nestedType = nestedType; primitive = (nestedType == null) && primitives.contains(name); } public String getName() { return name; } public Type getNestedType() { return nestedType; } public boolean isCollection() { return nestedType != null; } public boolean isPrimitive() { return primitive; } public int hashCode() { return super.hashCode(); } public boolean equals(Object obj) { return super.equals(obj); } private static final Set primitives; static { Set set = new HashSet(); set.add("boolean"); set.add("byte"); set.add("char"); set.add("short"); set.add("int"); set.add("long"); set.add("float"); set.add("double"); primitives = Collections.unmodifiableSet(set); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/MappingLoader.java0000644000175000017500000000204610641026035031366 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.IOException; import java.util.Set; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public interface MappingLoader { Set loadNamespaces() throws IOException; } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/XmlMetadataGenerator.java0000644000175000017500000002546711006262710032726 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Properties; import org.apache.xbean.spring.context.impl.NamespaceHelper; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XmlMetadataGenerator implements GeneratorPlugin { private final String metaInfDir; private LogFacade log; private final File schema; public static final String NAMESPACE_HANDLER = "org.apache.xbean.spring.context.v2.XBeanNamespaceHandler"; private final boolean generateSpringSchemasFile; private final boolean generateSpringHandlersFile; public XmlMetadataGenerator(String metaInfDir, File schema) { this(metaInfDir, schema, true, true); } public XmlMetadataGenerator(String metaInfDir, File schema, boolean generateSpringSchemasFile, boolean generateSpringHandlersFile) { this.metaInfDir = metaInfDir; this.schema = schema; this.generateSpringSchemasFile = generateSpringSchemasFile; this.generateSpringHandlersFile = generateSpringHandlersFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); if (namespace == null) { return; } File file = new File(metaInfDir, NamespaceHelper.createDiscoveryPathName(namespace)); file.getParentFile().mkdirs(); log.log("Generating META-INF properties file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generatePropertiesFile(out, namespaceMapping.getElements()); } finally { out.close(); } if( generateSpringHandlersFile ) { // Generate spring 2.0 mapping file = new File(metaInfDir, "META-INF/spring.handlers"); Properties properties = new Properties(); if (!file.exists()) { log.log("Generating Spring 2.0 handler mapping: " + file + " for namespace: " + namespace); } else { log.log("Updating Spring 2.0 handler mapping: " + file + " for namespace: " + namespace); // read in current file InputStream in = new FileInputStream(file); try { properties.load(in); } catch (IOException e) { in.close(); } } // add property properties.put(namespace, NAMESPACE_HANDLER); // write properties OutputStream fout = new FileOutputStream(file); try { properties.store(fout, "Generated by xbean-spring"); } finally { fout.close(); } } if (schema != null && generateSpringSchemasFile ) { String cp = new File(metaInfDir).toURI().relativize(schema.toURI()).toString(); file = new File(metaInfDir, "META-INF/spring.schemas"); Properties properties = new Properties(); if (!file.exists()) { log.log("Generating Spring 2.0 schema mapping: " + file + " for namespace: " + namespace); } else { log.log("Updating Spring 2.0 schema mapping: " + file + " for namespace: " + namespace); // read in current file InputStream in = new FileInputStream(file); try { properties.load(in); } catch (IOException e) { in.close(); } } // add property String uri = namespace; if (!uri.endsWith("/")) { uri += "/"; } properties.put(uri + cp, cp); // write properties OutputStream fout = new FileOutputStream(file); try { properties.store(fout, "Generated by xbean-spring"); } finally { fout.close(); } } } private void generatePropertiesFile(PrintWriter out, Set elements) { out.println("# NOTE: this file is autogenerated by Apache XBean"); out.println(); out.println("# beans"); for (Iterator iter = elements.iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); out.println(element.getElementName() + " = " + element.getClassName()); generatePropertiesFileContent(out, element); generatePropertiesFilePropertyAliases(out, element); generatePropertiesFileConstructors(out, element); out.println(); } } private void generatePropertiesFileContent(PrintWriter out, ElementMapping element) { String contentProperty = element.getContentProperty(); if (contentProperty != null) { out.println(element.getElementName() + ".contentProperty = " + contentProperty); } String initMethod = element.getInitMethod(); if (initMethod != null) { out.println(element.getElementName() + ".initMethod = " + initMethod); } String destroyMethod = element.getDestroyMethod(); if (destroyMethod != null) { out.println(element.getElementName() + ".destroyMethod = " + destroyMethod); } String factoryMethod = element.getFactoryMethod(); if (factoryMethod != null) { out.println(element.getElementName() + ".factoryMethod = " + factoryMethod); } for (Iterator iter = element.getAttributes().iterator(); iter.hasNext();) { AttributeMapping attribute = (AttributeMapping) iter.next(); if( attribute.getPropertyEditor() !=null ) { out.println(element.getElementName() + "."+attribute.getPropertyName()+ ".propertyEditor = " + attribute.getPropertyEditor()); } } List flatProperties = element.getFlatProperties(); for (Iterator itr = flatProperties.iterator(); itr.hasNext();) { out.println(element.getElementName() + "." + itr.next() + ".flat"); } Map maps = element.getMapMappings(); for (Iterator itr = maps.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); MapMapping mm = (MapMapping) entry.getValue(); if (mm.getEntryName() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.entryName = " + mm.getEntryName()); } if (mm.getKeyName() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.keyName = " + mm.getKeyName()); } if (mm.isFlat()) { out.println(element.getElementName() + "." + entry.getKey() + ".map.flat = " + Boolean.toString(mm.isFlat())); } if (mm.getDupsMode() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.dups = " + mm.getDupsMode()); } if (mm.getDefaultKey() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.defaultKey = " + mm.getDefaultKey()); } } Map flatCollections = element.getFlatCollections(); for (Iterator itr = flatCollections.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String child = (String) entry.getValue(); out.println(element.getElementName() + "." + child + ".flatCollection = " + entry.getKey()); } } private void generatePropertiesFileConstructors(PrintWriter out, ElementMapping element) { List constructors = element.getConstructors(); for (Iterator iterator = constructors.iterator(); iterator.hasNext();) { List args = (List) iterator.next(); generatePropertiesFileConstructor(out, element, args); } } private void generatePropertiesFileConstructor(PrintWriter out, ElementMapping element, List args) { out.print(element.getClassName()); if (element.getFactoryMethod() != null) { out.print("." + element.getFactoryMethod()); } out.print("("); for (Iterator iterator = args.iterator(); iterator.hasNext();) { ParameterMapping parameterMapping = (ParameterMapping) iterator.next(); out.print(parameterMapping.getType().getName()); if (iterator.hasNext()) { out.print(","); } } out.print(").parameterNames ="); for (Iterator iterator = args.iterator(); iterator.hasNext();) { ParameterMapping parameterMapping = (ParameterMapping) iterator.next(); out.print(" "); out.print(parameterMapping.getName()); } out.println(); } private void generatePropertiesFilePropertyAliases(PrintWriter out, ElementMapping element) { for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); String propertyName = attributeMapping.getPropertyName(); String attributeName = attributeMapping.getAttributeName(); if (!propertyName.equals(attributeName)) { if (List.class.getName().equals(attributeMapping.getType().getName())) { out.println(element.getElementName() + ".list." + attributeName + " = " + propertyName); } else { out.println(element.getElementName() + ".alias." + attributeName + " = " + propertyName); } } } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/InvalidModelException.java0000644000175000017500000000204210473277125033101 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class InvalidModelException extends RuntimeException { public InvalidModelException(String message) { super(message); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/NamespaceMapping.java0000644000175000017500000000562110520255363032062 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class NamespaceMapping implements Comparable { private final String namespace; private final Set elements; private final Map elementsByName; private final ElementMapping rootElement; public NamespaceMapping(String namespace, Set elements, ElementMapping rootElement) { this.namespace = namespace; this.elements = Collections.unmodifiableSet(new TreeSet(elements)); this.rootElement = rootElement; Map elementsByName = new HashMap(); for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ElementMapping elementMapping = (ElementMapping) iterator.next(); elementsByName.put(elementMapping.getElementName(), elementMapping); } this.elementsByName = Collections.unmodifiableMap(elementsByName); } public String getNamespace() { return namespace; } public Set getElements() { return elements; } public ElementMapping getElement(String elementName) { return (ElementMapping) elementsByName.get(elementName); } public ElementMapping getRootElement() { return rootElement; } public int hashCode() { return namespace.hashCode(); } public boolean equals(Object obj) { if (obj instanceof NamespaceMapping) { return namespace.equals(((NamespaceMapping) obj).namespace); } return false; } public int compareTo(Object obj) { return namespace.compareTo(((NamespaceMapping) obj).namespace); } private final HashMap checkedTypes = new HashMap(); public boolean isSimpleType(Type type) { Boolean b = (Boolean) checkedTypes.get(type); if (b == null){ b = Utils.isSimpleType(type)? Boolean.TRUE: Boolean.FALSE; checkedTypes.put(type, b); } return b.booleanValue(); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/QdoxMappingLoader.java0000644000175000017500000006010210641026035032217 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.BeanProperty; import com.thoughtworks.qdox.model.DocletTag; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.Type; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class QdoxMappingLoader implements MappingLoader { public static final String XBEAN_ANNOTATION = "org.apache.xbean.XBean"; public static final String PROPERTY_ANNOTATION = "org.apache.xbean.Property"; public static final String INIT_METHOD_ANNOTATION = "org.apache.xbean.InitMethod"; public static final String DESTROY_METHOD_ANNOTATION = "org.apache.xbean.DestroyMethod"; public static final String FACTORY_METHOD_ANNOTATION = "org.apache.xbean.FactoryMethod"; public static final String MAP_ANNOTATION = "org.apache.xbean.Map"; public static final String FLAT_PROPERTY_ANNOTATION = "org.apache.xbean.Flat"; public static final String FLAT_COLLECTION_ANNOTATION = "org.apache.xbean.FlatCollection"; public static final String ELEMENT_ANNOTATION = "org.apache.xbean.Element"; private static final Log log = LogFactory.getLog(QdoxMappingLoader.class); private final String defaultNamespace; private final File[] srcDirs; private final String[] excludedClasses; private Type collectionType; public QdoxMappingLoader(String defaultNamespace, File[] srcDirs, String[] excludedClasses) { this.defaultNamespace = defaultNamespace; this.srcDirs = srcDirs; this.excludedClasses = excludedClasses; } public String getDefaultNamespace() { return defaultNamespace; } public File[] getSrcDirs() { return srcDirs; } public Set loadNamespaces() throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); log.debug("Source directories: "); for (File sourceDirectory : srcDirs) { if (!sourceDirectory.isDirectory() && !sourceDirectory.toString().endsWith(".jar")) { log.warn("Specified source directory isn't a directory or a jar file: '" + sourceDirectory.getAbsolutePath() + "'."); } log.debug(" - " + sourceDirectory.getAbsolutePath()); getSourceFiles(sourceDirectory, excludedClasses, builder); } collectionType = builder.getClassByName("java.util.Collection").asType(); return loadNamespaces(builder); } private Set loadNamespaces(JavaDocBuilder builder) { // load all of the elements List elements = loadElements(builder); // index the elements by namespace and find the root element of each namespace Map> elementsByNamespace = new HashMap>(); Map namespaceRoots = new HashMap(); for (ElementMapping element : elements) { String namespace = element.getNamespace(); Set namespaceElements = elementsByNamespace.get(namespace); if (namespaceElements == null) { namespaceElements = new HashSet(); elementsByNamespace.put(namespace, namespaceElements); } namespaceElements.add(element); if (element.isRootElement()) { if (namespaceRoots.containsKey(namespace)) { log.info("Multiple root elements found for namespace " + namespace); } namespaceRoots.put(namespace, element); } } // build the NamespaceMapping objects Set namespaces = new TreeSet(); for (Map.Entry> entry : elementsByNamespace.entrySet()) { String namespace = entry.getKey(); Set namespaceElements = entry.getValue(); ElementMapping rootElement = namespaceRoots.get(namespace); NamespaceMapping namespaceMapping = new NamespaceMapping(namespace, namespaceElements, rootElement); namespaces.add(namespaceMapping); } return Collections.unmodifiableSet(namespaces); } private List loadElements(JavaDocBuilder builder) { JavaSource[] javaSources = builder.getSources(); List elements = new ArrayList(); for (JavaSource javaSource : javaSources) { if (javaSource.getClasses().length == 0) { log.info("No Java Classes defined in: " + javaSource.getURL()); } else { JavaClass[] classes = javaSource.getClasses(); for (JavaClass javaClass : classes) { ElementMapping element = loadElement(builder, javaClass); if (element != null && !javaClass.isAbstract()) { elements.add(element); } else { log.debug("No XML annotation found for type: " + javaClass.getFullyQualifiedName()); } } } } return elements; } private ElementMapping loadElement(JavaDocBuilder builder, JavaClass javaClass) { DocletTag xbeanTag = javaClass.getTagByName(XBEAN_ANNOTATION); if (xbeanTag == null) { return null; } String element = getElementName(javaClass, xbeanTag); String description = getProperty(xbeanTag, "description"); if (description == null) { description = javaClass.getComment(); } String namespace = getProperty(xbeanTag, "namespace", defaultNamespace); boolean root = getBooleanProperty(xbeanTag, "rootElement"); String contentProperty = getProperty(xbeanTag, "contentProperty"); String factoryClass = getProperty(xbeanTag, "factoryClass"); Map mapsByPropertyName = new HashMap(); List flatProperties = new ArrayList(); Map flatCollections = new HashMap(); Set attributes = new HashSet(); Map attributesByPropertyName = new HashMap(); for (JavaClass jClass = javaClass; jClass != null; jClass = jClass.getSuperJavaClass()) { BeanProperty[] beanProperties = jClass.getBeanProperties(); for (BeanProperty beanProperty : beanProperties) { // we only care about properties with a setter if (beanProperty.getMutator() != null) { AttributeMapping attributeMapping = loadAttribute(beanProperty, ""); if (attributeMapping != null) { attributes.add(attributeMapping); attributesByPropertyName.put(attributeMapping.getPropertyName(), attributeMapping); } JavaMethod acc = beanProperty.getAccessor(); if (acc != null) { DocletTag mapTag = acc.getTagByName(MAP_ANNOTATION); if (mapTag != null) { MapMapping mm = new MapMapping( mapTag.getNamedParameter("entryName"), mapTag.getNamedParameter("keyName"), Boolean.valueOf(mapTag.getNamedParameter("flat")), mapTag.getNamedParameter("dups"), mapTag.getNamedParameter("defaultKey")); mapsByPropertyName.put(beanProperty.getName(), mm); } DocletTag flatColTag = acc.getTagByName(FLAT_COLLECTION_ANNOTATION); if (flatColTag != null) { String childName = flatColTag.getNamedParameter("childElement"); if (childName == null) throw new InvalidModelException("Flat collections must specify the childElement attribute."); flatCollections.put(beanProperty.getName(), childName); } DocletTag flatPropTag = acc.getTagByName(FLAT_PROPERTY_ANNOTATION); if (flatPropTag != null) { flatProperties.add(beanProperty.getName()); } } } } } String initMethod = null; String destroyMethod = null; String factoryMethod = null; for (JavaClass jClass = javaClass; jClass != null; jClass = jClass.getSuperJavaClass()) { JavaMethod[] methods = javaClass.getMethods(); for (JavaMethod method : methods) { if (method.isPublic() && !method.isConstructor()) { if (initMethod == null && method.getTagByName(INIT_METHOD_ANNOTATION) != null) { initMethod = method.getName(); } if (destroyMethod == null && method.getTagByName(DESTROY_METHOD_ANNOTATION) != null) { destroyMethod = method.getName(); } if (factoryMethod == null && method.getTagByName(FACTORY_METHOD_ANNOTATION) != null) { factoryMethod = method.getName(); } } } } List> constructorArgs = new ArrayList>(); JavaMethod[] methods = javaClass.getMethods(); for (JavaMethod method : methods) { JavaParameter[] parameters = method.getParameters(); if (isValidConstructor(factoryMethod, method, parameters)) { List args = new ArrayList(parameters.length); for (JavaParameter parameter : parameters) { AttributeMapping attributeMapping = attributesByPropertyName.get(parameter.getName()); if (attributeMapping == null) { attributeMapping = loadParameter(parameter); attributes.add(attributeMapping); attributesByPropertyName.put(attributeMapping.getPropertyName(), attributeMapping); } args.add(new ParameterMapping(attributeMapping.getPropertyName(), toMappingType(parameter.getType(), null))); } constructorArgs.add(Collections.unmodifiableList(args)); } } HashSet interfaces = new HashSet(); interfaces.addAll(getFullyQualifiedNames(javaClass.getImplementedInterfaces())); JavaClass actualClass = javaClass; if (factoryClass != null) { JavaClass clazz = builder.getClassByName(factoryClass); if (clazz != null) { log.info("Detected factory: using " + factoryClass + " instead of " + javaClass.getFullyQualifiedName()); actualClass = clazz; } else { log.info("Could not load class built by factory: " + factoryClass); } } ArrayList superClasses = new ArrayList(); JavaClass p = actualClass; if (actualClass != javaClass) { superClasses.add(actualClass.getFullyQualifiedName()); } while (true) { JavaClass s = p.getSuperJavaClass(); if (s == null || s.equals(p) || "java.lang.Object".equals(s.getFullyQualifiedName())) { break; } p = s; superClasses.add(p.getFullyQualifiedName()); interfaces.addAll(getFullyQualifiedNames(p.getImplementedInterfaces())); } return new ElementMapping(namespace, element, javaClass.getFullyQualifiedName(), description, root, initMethod, destroyMethod, factoryMethod, contentProperty, attributes, constructorArgs, flatProperties, mapsByPropertyName, flatCollections, superClasses, interfaces); } private List getFullyQualifiedNames(JavaClass[] implementedInterfaces) { ArrayList l = new ArrayList(); for (JavaClass implementedInterface : implementedInterfaces) { l.add(implementedInterface.getFullyQualifiedName()); } return l; } private String getElementName(JavaClass javaClass, DocletTag tag) { String elementName = getProperty(tag, "element"); if (elementName == null) { String className = javaClass.getFullyQualifiedName(); int index = className.lastIndexOf("."); if (index > 0) { className = className.substring(index + 1); } // strip off "Bean" from a spring factory bean if (className.endsWith("FactoryBean")) { className = className.substring(0, className.length() - 4); } elementName = Utils.decapitalise(className); } return elementName; } private AttributeMapping loadAttribute(BeanProperty beanProperty, String defaultDescription) { DocletTag propertyTag = getPropertyTag(beanProperty); if (getBooleanProperty(propertyTag, "hidden")) { return null; } String attribute = getProperty(propertyTag, "alias", beanProperty.getName()); String attributeDescription = getAttributeDescription(beanProperty, propertyTag, defaultDescription); String defaultValue = getProperty(propertyTag, "default"); boolean fixed = getBooleanProperty(propertyTag, "fixed"); boolean required = getBooleanProperty(propertyTag, "required"); String nestedType = getProperty(propertyTag, "nestedType"); String propertyEditor = getProperty(propertyTag, "propertyEditor"); return new AttributeMapping(attribute, beanProperty.getName(), attributeDescription, toMappingType(beanProperty.getType(), nestedType), defaultValue, fixed, required, propertyEditor); } private static DocletTag getPropertyTag(BeanProperty beanProperty) { JavaMethod accessor = beanProperty.getAccessor(); if (accessor != null) { DocletTag propertyTag = accessor.getTagByName(PROPERTY_ANNOTATION); if (propertyTag != null) { return propertyTag; } } JavaMethod mutator = beanProperty.getMutator(); if (mutator != null) { DocletTag propertyTag = mutator.getTagByName(PROPERTY_ANNOTATION); if (propertyTag != null) { return propertyTag; } } return null; } private String getAttributeDescription(BeanProperty beanProperty, DocletTag propertyTag, String defaultDescription) { String description = getProperty(propertyTag, "description"); if (description != null && description.trim().length() > 0) { return description.trim(); } JavaMethod accessor = beanProperty.getAccessor(); if (accessor != null) { description = accessor.getComment(); if (description != null && description.trim().length() > 0) { return description.trim(); } } JavaMethod mutator = beanProperty.getMutator(); if (mutator != null) { description = mutator.getComment(); if (description != null && description.trim().length() > 0) { return description.trim(); } } return defaultDescription; } private AttributeMapping loadParameter(JavaParameter parameter) { String parameterName = parameter.getName(); String parameterDescription = getParameterDescription(parameter); // first attempt to load the attribute from the java beans accessor methods JavaClass javaClass = parameter.getParentMethod().getParentClass(); BeanProperty beanProperty = javaClass.getBeanProperty(parameterName); if (beanProperty != null) { AttributeMapping attributeMapping = loadAttribute(beanProperty, parameterDescription); // if the attribute mapping is null, the property was tagged as hidden and this is an error if (attributeMapping == null) { throw new InvalidModelException("Hidden property usage: " + "The construction method " + toMethodLocator(parameter.getParentMethod()) + " can not use a hidded property " + parameterName); } return attributeMapping; } // create an attribute solely based on the parameter information return new AttributeMapping(parameterName, parameterName, parameterDescription, toMappingType(parameter.getType(), null), null, false, false, null); } private String getParameterDescription(JavaParameter parameter) { String parameterName = parameter.getName(); DocletTag[] tags = parameter.getParentMethod().getTagsByName("param"); for (DocletTag tag : tags) { if (tag.getParameters()[0].equals(parameterName)) { String parameterDescription = tag.getValue().trim(); if (parameterDescription.startsWith(parameterName)) { parameterDescription = parameterDescription.substring(parameterName.length()).trim(); } return parameterDescription; } } return null; } private boolean isValidConstructor(String factoryMethod, JavaMethod method, JavaParameter[] parameters) { if (!method.isPublic() || parameters.length == 0) { return false; } if (factoryMethod == null) { return method.isConstructor(); } else { return method.getName().equals(factoryMethod); } } private static String getProperty(DocletTag propertyTag, String propertyName) { return getProperty(propertyTag, propertyName, null); } private static String getProperty(DocletTag propertyTag, String propertyName, String defaultValue) { String value = null; if (propertyTag != null) { value = propertyTag.getNamedParameter(propertyName); } if (value == null) { return defaultValue; } return value; } private boolean getBooleanProperty(DocletTag propertyTag, String propertyName) { return toBoolean(getProperty(propertyTag, propertyName)); } private static boolean toBoolean(String value) { if (value != null) { return Boolean.valueOf(value); } return false; } private org.apache.xbean.spring.generator.Type toMappingType(Type type, String nestedType) { try { if (type.isArray()) { return org.apache.xbean.spring.generator.Type.newArrayType(type.getValue(), type.getDimensions()); } else if (type.isA(collectionType)) { if (nestedType == null) nestedType = "java.lang.Object"; return org.apache.xbean.spring.generator.Type.newCollectionType(type.getValue(), org.apache.xbean.spring.generator.Type.newSimpleType(nestedType)); } } catch (Throwable t) { log.debug("Could not load type mapping", t); } return org.apache.xbean.spring.generator.Type.newSimpleType(type.getValue()); } private static String toMethodLocator(JavaMethod method) { StringBuffer buf = new StringBuffer(); buf.append(method.getParentClass().getFullyQualifiedName()); if (!method.isConstructor()) { buf.append(".").append(method.getName()); } buf.append("("); JavaParameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { JavaParameter parameter = parameters[i]; if (i > 0) { buf.append(", "); } buf.append(parameter.getName()); } buf.append(") : ").append(method.getLineNumber()); return buf.toString(); } private static void getSourceFiles(File base, String[] excludedClasses, JavaDocBuilder builder) throws IOException { if (base.isDirectory()) { listAllFileNames(base, "", excludedClasses, builder); } else { listAllJarEntries(base, excludedClasses, builder); } } private static void listAllFileNames(File base, String prefix, String[] excludedClasses, JavaDocBuilder builder) throws IOException { if (!base.canRead() || !base.isDirectory()) { throw new IllegalArgumentException(base.getAbsolutePath()); } File[] hits = base.listFiles(); for (File hit : hits) { String name = prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName(); if (hit.canRead() && !isExcluded(name, excludedClasses)) { if (hit.isDirectory()) { listAllFileNames(hit, name, excludedClasses, builder); } else if (name.endsWith(".java")) { builder.addSource(hit); } } } } private static void listAllJarEntries(File base, String[] excludedClasses, JavaDocBuilder builder) throws IOException { JarFile jarFile = new JarFile(base); for (Enumeration entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (name.endsWith(".java") && !isExcluded(name, excludedClasses) && !name.endsWith("/package-info.java")) { builder.addSource(new URL("jar:" + base.toURL().toString() + "!/" + name)); } } } private static boolean isExcluded(String sourceName, String[] excludedClasses) { if (excludedClasses == null) { return false; } String className = sourceName; if (sourceName.endsWith(".java")) { className = className.substring(0, className.length() - ".java".length()); } className = className.replace('/', '.'); for (String excludedClass : excludedClasses) { if (className.equals(excludedClass)) { return true; } } return false; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/MappingGeneratorTask.java0000644000175000017500000001225010473277125032742 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import java.io.File; import java.util.Iterator; import java.util.Set; import java.util.List; import java.util.LinkedList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.beans.PropertyEditorManager; /** * An Ant task for executing generating mapping metadata. * * @version $Revision: 434369 $ */ public class MappingGeneratorTask extends MatchingTask implements LogFacade { private String namespace; private Path srcDir; private String excludedClasses = null; private File destFile = new File("target/classes/schema.xsd"); private String metaInfDir = "target/classes/"; private String propertyEditorPaths = "org.apache.xbean.spring.context.impl"; public File getDestFile() { return destFile; } public void setDestFile(File destFile) { this.destFile = destFile; } public String getMetaInfDir() { return metaInfDir; } public void setMetaInfDir(String metaInfDir) { this.metaInfDir = metaInfDir; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Path getSrcDir() { return srcDir; } public void setSrcDir(Path srcDir) { this.srcDir = srcDir; } public String getPropertyEditorPaths() { return propertyEditorPaths; } public void setPropertyEditorPaths(String propertyEditorPaths) { this.propertyEditorPaths = propertyEditorPaths; } public void execute() throws BuildException { if (namespace == null) { throw new BuildException("'namespace' must be specified"); } if (srcDir == null) { throw new BuildException("'srcDir' must be specified"); } if (destFile == null) { throw new BuildException("'destFile' must be specified"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); editorSearchPath.addAll(Collections.list(paths)); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } MappingLoader mappingLoader = new QdoxMappingLoader(namespace, getFiles(srcDir), excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(metaInfDir, destFile), new DocumentationGenerator(destFile), new XsdGenerator(destFile) }; // load the mappings Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.setLog(this); plugin.generate(namespaceMapping); } } log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } private File[] getFiles(Path path) { if (path == null) { return null; } String[] paths = path.list(); File[] files = new File[paths.length]; for (int i = 0; i < files.length; i++) { files[i] = new File(paths[i]).getAbsoluteFile(); } return files; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/DocumentationGenerator.java0000644000175000017500000002003311251237773033333 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class DocumentationGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public DocumentationGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); // TODO can only handle 1 schema document so far... File file = new File(destFile.getParentFile(), destFile.getName() + ".html"); log.log("Generating HTML documentation file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateDocumentation(out, namespaceMapping); } finally { out.close(); } } private void generateDocumentation(PrintWriter out, NamespaceMapping namespaceMapping) { String namespace = namespaceMapping.getNamespace(); out.println(""); out.println(""); out.println(""); out.println("Schema for namespace: " + namespace + ""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(); out.println(""); out.println(); generateRootElement(out, namespaceMapping); generateElementsSummary(out, namespaceMapping); out.println(); out.println(); generateElementsDetail(out, namespaceMapping); out.println(); out.println(""); out.println(""); } private void generateRootElement(PrintWriter out, NamespaceMapping namespaceMapping) { ElementMapping rootElement = namespaceMapping.getRootElement(); if (rootElement != null) { out.println("

Root Element

"); out.println(""); out.println(" "); generateElementSummary(out, rootElement); out.println("
ElementDescriptionClass
"); out.println(); } } private void generateElementsSummary(PrintWriter out, NamespaceMapping namespaceMapping) { out.println("

Element Summary

"); out.println(""); out.println(" "); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementSummary(out, element); } out.println("
ElementDescriptionClass
"); } private void generateElementSummary(PrintWriter out, ElementMapping element) { out.println(" " + "" + element.getElementName() + "" + "" + element.getDescription() + "" + "" + element.getClassName() + ""); } private void generateElementsDetail(PrintWriter out, NamespaceMapping namespaceMapping) { out.println("

Element Detail

"); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateHtmlElementDetail(out, namespaceMapping, element); } } private void generateHtmlElementDetail(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { out.println("

Element: " + element.getElementName() + "

"); boolean hasAttributes = false; boolean hasElements = false; for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext() && (!hasAttributes || !hasElements);) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getType(); if (namespaceMapping.isSimpleType(type)) { hasAttributes = true; } else { hasElements = true; } } if (hasAttributes) { out.println(""); out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getPropertyEditor() != null ? Type.newSimpleType(String.class.getName()) : attributeMapping.getType(); if (namespaceMapping.isSimpleType(type)) { out.println(" "); } } out.println("
AttributeTypeDescription
" + attributeMapping.getAttributeName() + "" + Utils.getXsdType(type) + "" + attributeMapping.getDescription() + "
"); } if (hasElements) { out.println(""); out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getType(); if (!namespaceMapping.isSimpleType(type)) { out.print(" "); } } out.println("
ElementTypeDescription
" + attributeMapping.getAttributeName() + ""); printComplexPropertyTypeDocumentation(out, namespaceMapping, type); out.println("" + attributeMapping.getDescription() + "
"); } } private void printComplexPropertyTypeDocumentation(PrintWriter out, NamespaceMapping namespaceMapping, Type type) { if (type.isCollection()) { out.print("("); } List types; if (type.isCollection()) { types = Utils.findImplementationsOf(namespaceMapping, type.getNestedType()); } else { types = Utils.findImplementationsOf(namespaceMapping, type); } for (Iterator iterator = types.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.print("" + element.getElementName() + ""); if (iterator.hasNext()) { out.print(" | "); } } if (types.size() == 0) { out.print("<spring:bean/>"); } if (type.isCollection()) { out.print(")*"); } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/generator/GeneratorPlugin.java0000644000175000017500000000212410473277125031761 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import java.io.IOException; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public interface GeneratorPlugin { void generate(NamespaceMapping namespaceMapping) throws IOException; LogFacade getLog(); void setLog(LogFacade log); } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/0000755000175000017500000000000011610661036025500 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/SpringXmlPreprocessor.java0000644000175000017500000000313710473277125032711 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.w3c.dom.Document; /** * SpringXmlPreprocessor preprocesses the xml Document before it is passed to Spring for processing. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public interface SpringXmlPreprocessor { /** * Preprocesses the xml document which is being loaded by the specified application context and is being read by the * specified xml reader. * @param applicationContext the application context which is being loaded * @param reader the xml reader that read the document * @param document the xml document to read */ public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/FileSystemXmlApplicationContext.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/FileSystemXmlApplicationContext0000644000175000017500000002165710473277125033744 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.xbean.spring.context.impl.XBeanHelper; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; /** * An XBean version of the regular Spring class to provide improved XML * handling. * * @author James Strachan * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class FileSystemXmlApplicationContext extends org.springframework.context.support.FileSystemXmlApplicationContext implements SpringApplicationContext { private final List xmlPreprocessors; /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified location on the file system. * @param configLocation the location of the configuration file on the class path * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String configLocation) throws BeansException { this(new String[] {configLocation}, true, null, Collections.EMPTY_LIST); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations) throws BeansException { this(configLocations, true, null, Collections.EMPTY_LIST); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException { this(configLocations, refresh, null, Collections.EMPTY_LIST); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param parent the parent of this application context * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException { this(configLocations, true, parent, Collections.EMPTY_LIST); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param parent the parent of this application context * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { this(configLocations, refresh, parent, Collections.EMPTY_LIST); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified location on the file system. * @param configLocation the location of the configuration file on the class path * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String configLocation, List xmlPreprocessors) throws BeansException { this(new String[] {configLocation}, true, null, xmlPreprocessors); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, List xmlPreprocessors) throws BeansException { this(configLocations, true, null, xmlPreprocessors); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, List xmlPreprocessors) throws BeansException { this(configLocations, refresh, null, xmlPreprocessors); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param parent the parent of this application context * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent, List xmlPreprocessors) throws BeansException { this(configLocations, true, parent, xmlPreprocessors); } /** * Creates a FileSystemXmlApplicationContext which loads the configuration at the specified locations on the file system. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param parent the parent of this application context * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent, List xmlPreprocessors) throws BeansException { super(configLocations, false, parent); this.xmlPreprocessors = xmlPreprocessors; if (refresh) { refresh(); } } /** * {@inheritDoc} */ protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = XBeanHelper.createBeanDefinitionReader(this, beanFactory, xmlPreprocessors); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/XmlWebApplicationContext.java0000644000175000017500000000600510473277125033303 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.xbean.spring.context.SpringApplicationContext; import org.apache.xbean.spring.context.impl.XBeanHelper; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; /** * An XBean version of the regular Spring class to provide improved XML * handling. * * @author James Strachan * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class XmlWebApplicationContext extends org.springframework.web.context.support.XmlWebApplicationContext implements SpringApplicationContext { private final List xmlPreprocessors; /** * Creates a XmlWebApplicationContext which loads the configuration from the a web application context. */ public XmlWebApplicationContext() { this.xmlPreprocessors = Collections.EMPTY_LIST; } /** * Creates a XmlWebApplicationContext which loads the configuration from the a web application context. * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing */ public XmlWebApplicationContext(List xmlPreprocessors) { this.xmlPreprocessors = xmlPreprocessors; } /** * {@inheritDoc} */ protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = XBeanHelper.createBeanDefinitionReader(this, beanFactory, xmlPreprocessors); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/0000755000175000017500000000000011610661036026027 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanXmlBeanFactory.java0000644000175000017500000000653010572763451032504 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.Resource; import java.util.Collections; import java.util.List; public class XBeanXmlBeanFactory extends DefaultListableBeanFactory { /** * Create a new XBeanXmlBeanFactory with the given resource, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource) throws BeansException { this(resource, null, Collections.EMPTY_LIST); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException { this(resource, parentBeanFactory, Collections.EMPTY_LIST); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param xmlPreprocessors the preprocessors to apply the DOM before passing to Spring for processing * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, List xmlPreprocessors) throws BeansException { this(resource, null, xmlPreprocessors); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @param xmlPreprocessors the preprocessors to apply the DOM before passing to Spring for processing * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, BeanFactory parentBeanFactory, List xmlPreprocessors) throws BeansException { super(parentBeanFactory); XBeanXmlBeanDefinitionReader reader = new XBeanXmlBeanDefinitionReader(null, this, xmlPreprocessors); reader.loadBeanDefinitions(resource); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanNamespaceHandler.java0000644000175000017500000000407110572763451033016 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * An enhanced XML parser capable of handling custom XML schemas. * * @author James Strachan * @version $Id$ * @since 2.0 */ public class XBeanNamespaceHandler implements NamespaceHandler { public static final String SPRING_SCHEMA = "http://xbean.apache.org/schemas/spring/1.0"; public static final String SPRING_SCHEMA_COMPAT = "http://xbean.org/schemas/spring/1.0"; private final NamespaceHandler delegate; public XBeanNamespaceHandler() { delegate = XBeanV2Helper.createNamespaceHandler(); } public void init() { delegate.init(); } public BeanDefinition parse(Element element, ParserContext parserContext) { return delegate.parse(element, parserContext); } public BeanDefinitionHolder decorate(Node element, BeanDefinitionHolder definition, ParserContext parserContext) { return delegate.decorate(element, definition, parserContext); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanV2Helper.java0000644000175000017500000000661210572763451031256 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import java.lang.reflect.Constructor; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.XmlReaderContext; import org.w3c.dom.Element; public class XBeanV2Helper { public static String version = null; public static BeanDefinitionParserDelegate createParser(XmlReaderContext readerContext) { try { String className = "org.apache.xbean.spring.context." + getVersion() + ".XBeanBeanDefinitionParserDelegate"; Class clParser = Class.forName(className); Constructor cns = clParser.getConstructor(new Class[] { XmlReaderContext.class }); return (BeanDefinitionParserDelegate) cns.newInstance(new Object[] { readerContext }); } catch (Throwable e) { throw (IllegalStateException) new IllegalStateException("Unable to create namespace handler for: " + version).initCause(e); } } public static NamespaceHandler createNamespaceHandler() { try { String className = "org.apache.xbean.spring.context." + getVersion() + ".XBeanNamespaceHandler"; Class clHandler = Class.forName(className); return (NamespaceHandler) clHandler.newInstance(); } catch (Throwable e) { throw (IllegalStateException) new IllegalStateException("Unable to create namespace handler for: " + version).initCause(e); } } private static String getVersion() { if (version == null) { try { try { Class.forName("org.springframework.beans.factory.parsing.BeanComponentDefinition"); version = "v2c"; } catch (ClassNotFoundException e) { Class cl = Class.forName("org.springframework.beans.factory.xml.BeanDefinitionParserDelegate"); try { cl.getMethod("parsePropertyElements", new Class[] { Element.class, BeanDefinition.class }); version = "v2b"; } catch (NoSuchMethodException e2) { version = "v2a"; } } } catch (Throwable e) { throw (IllegalStateException) new IllegalStateException("Could not create namespace handler for: " + version).initCause(e); } } return version; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanXmlBeanDefinitionReader.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanXmlBeanDefinitionReader0000644000175000017500000001031710572763451033366 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import java.util.Iterator; import java.util.List; import org.apache.xbean.spring.context.SpringApplicationContext; import org.apache.xbean.spring.context.SpringXmlPreprocessor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.xml.NamespaceHandlerResolver; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.w3c.dom.Document; /** * XBeanXmlBeanDefinitionReader extends XmlBeanDefinitionReader adds support for SpringXMLPreprocessors which can * modify the DOM before it is passed to Spring for reading. This allows for extra information to be added into the * Spring configuration file that is processed and removed before Spring sees the xml. * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class XBeanXmlBeanDefinitionReader extends XmlBeanDefinitionReader { private final SpringApplicationContext applicationContext; private final List xmlPreprocessors; /** * Creates a XBeanXmlBeanDefinitionReader for the specified applicationContext and beanFactory which will apply * the xmlPreprocessors before passing the DOM to Spring for processing. * @param applicationContext the application context for which the bean definitons will be loaded * @param beanFactory the beanFactory that services will be loaded * @param xmlPreprocessors the preprocessors to apply the DOM before passing to Spring for processing */ public XBeanXmlBeanDefinitionReader(SpringApplicationContext applicationContext, BeanDefinitionRegistry beanFactory, List xmlPreprocessors) { super(beanFactory); this.applicationContext = applicationContext; this.xmlPreprocessors = xmlPreprocessors; setNamespaceAware(true); setValidationMode(VALIDATION_NONE); if (applicationContext != null) { setResourceLoader(applicationContext); setEntityResolver(new ResourceEntityResolver(applicationContext)); } setDocumentReaderClass(XBeanBeanDefinitionDocumentReader.class); } /** * Gets the application context for which the bean definitons will be loaded. * @return the application context for which the bean definitons will be loaded */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * {@inheritDoc} */ public int registerBeanDefinitions(Document doc, Resource resource) throws BeansException { preprocess(doc); return super.registerBeanDefinitions(doc, resource); } protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() { ClassLoader classLoader = getBeanClassLoader(); if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } return new XBeanNamespaceHandlerResolver(classLoader); } private void preprocess(Document doc) { for (Iterator iterator = xmlPreprocessors.iterator(); iterator.hasNext();) { SpringXmlPreprocessor preprocessor = (SpringXmlPreprocessor) iterator.next(); preprocessor.preprocess(applicationContext, this, doc); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanNamespaceHandlerResolver.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanNamespaceHandlerResolve0000644000175000017500000000306610572763451033441 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; import org.springframework.beans.factory.xml.NamespaceHandler; public class XBeanNamespaceHandlerResolver extends DefaultNamespaceHandlerResolver { public XBeanNamespaceHandlerResolver(ClassLoader classLoader) { super(classLoader); } public NamespaceHandler resolve(String namespaceUri) { NamespaceHandler handler = null; try { handler = super.resolve(namespaceUri); } catch (IllegalArgumentException e) { // ignore } if (handler == null) { handler = new XBeanNamespaceHandler(); } return handler; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanBeanDefinitionDocumentReader.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2/XBeanBeanDefinitionDocumentR0000644000175000017500000002031610575640461033401 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.util.StringUtils; import org.springframework.util.SystemPropertyUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XBeanBeanDefinitionDocumentReader extends DefaultBeanDefinitionDocumentReader { protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) { BeanDefinitionParserDelegate delegate = XBeanV2Helper.createParser(readerContext); delegate.initDefaults(root); return delegate; } protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { String namespaceUri = root.getNamespaceURI(); if (!DomUtils.nodeNameEquals(root, "beans") && !delegate.isDefaultNamespace(namespaceUri)) { try { try { Method m = BeanDefinitionParserDelegate.class.getMethod("parseCustomElement", new Class[] { Element.class }); m.invoke(delegate, new Object[] { root }); } catch (NoSuchMethodException e) { try { Method m = BeanDefinitionParserDelegate.class.getMethod("parseCustomElement", new Class[] { Element.class, boolean.class }); m.invoke(delegate, new Object[] { root, Boolean.FALSE }); } catch (NoSuchMethodException e2) { throw new IllegalStateException(e); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); } } else if (DomUtils.nodeNameEquals(root, "beans")) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; String childNamespaceUri = ele.getNamespaceURI(); if (delegate.isDefaultNamespace(childNamespaceUri)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { super.parseBeanDefinitions(root, delegate); } } private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) { importBeanDefinitionResource(ele); } else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) { processAliasRegistration(ele); } else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) { processBeanDefinition(ele, delegate); } } /** * Parse an "import" element and load the bean definitions * from the given resource into the bean factory. */ protected void importBeanDefinitionResource(Element ele) { String location = ele.getAttribute(RESOURCE_ATTRIBUTE); if (!StringUtils.hasText(location)) { getReaderContext().error("Resource location must not be empty", ele); return; } // Resolve system properties: e.g. "${user.dir}" location = SystemPropertyUtils.resolvePlaceholders(location); if (ResourcePatternUtils.isUrl(location)) { int importCount = getReaderContext().getReader().loadBeanDefinitions(location); if (logger.isDebugEnabled()) { logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]"); } } else { // No URL -> considering resource location as relative to the current file. try { Resource relativeResource = getReaderContext().getResource().createRelative(location); int importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource); if (logger.isDebugEnabled()) { logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]"); } } catch (IOException ex) { getReaderContext().error( "Invalid relative resource location [" + location + "] to import bean definitions from", ele, null, ex); } } getReaderContext().fireImportProcessed(location, extractSource(ele)); } /** * Process the given alias element, registering the alias with the registry. */ protected void processAliasRegistration(Element ele) { String name = ele.getAttribute(NAME_ATTRIBUTE); String alias = ele.getAttribute(ALIAS_ATTRIBUTE); boolean valid = true; if (!StringUtils.hasText(name)) { getReaderContext().error("Name must not be empty", ele); valid = false; } if (!StringUtils.hasText(alias)) { getReaderContext().error("Alias must not be empty", ele); valid = false; } if (valid) { try { getReaderContext().getRegistry().registerAlias(name, alias); } catch (BeanDefinitionStoreException ex) { getReaderContext().error(ex.getMessage(), ele); } getReaderContext().fireAliasRegistered(name, alias, extractSource(ele)); } } /** * Process the given bean element, parsing the bean definition * and registering it with the registry. */ protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/0000755000175000017500000000000011610661036026172 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/PropertyEditorFactory.java0000644000175000017500000000325110741146234033363 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2c; import java.beans.PropertyEditor; import org.springframework.beans.factory.FactoryBean; public class PropertyEditorFactory implements FactoryBean { PropertyEditor propertyEditor; String value; Class type = Object.class; public Object getObject() throws Exception { propertyEditor.setAsText(value); return propertyEditor.getValue(); } public Class getObjectType() { return type; } public boolean isSingleton() { return true; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public PropertyEditor getPropertyEditor() { return propertyEditor; } public void setPropertyEditor(PropertyEditor propertyEditor) { this.propertyEditor = propertyEditor; } public Class getType() { return type; } public void setType(Class type) { this.type = type; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/XBeanQNameHelper.java0000644000175000017500000001110610572763451032125 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2c; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import org.apache.xbean.spring.context.impl.PropertyEditorHelper; import org.apache.xbean.spring.context.impl.QNameReflectionHelper; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.xml.XmlReaderContext; import org.w3c.dom.Element; public class XBeanQNameHelper { private XmlReaderContext readerContext; private boolean qnameIsOnClassPath; private boolean initQNameOnClassPath; public XBeanQNameHelper(XmlReaderContext readerContext) { this.readerContext = readerContext; } /** * Any namespace aware property values (such as QNames) need to be coerced * while we still have access to the XML Element from which its value comes - * so lets do that now before we trash the DOM and just have the bean * definition. */ public void coerceNamespaceAwarePropertyValues(BeanDefinition definition, Element element) { if (definition instanceof AbstractBeanDefinition && isQnameIsOnClassPath()) { AbstractBeanDefinition bd = (AbstractBeanDefinition) definition; // lets check for any QName types BeanInfo beanInfo = getBeanInfo(bd.getBeanClassName()); if (beanInfo != null) { PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { QNameReflectionHelper.coerceNamespaceAwarePropertyValues(bd, element, descriptors, i); } } } } public BeanInfo getBeanInfo(String className) throws BeanDefinitionStoreException { if (className == null) { return null; } BeanInfo info = null; Class type = null; try { type = loadClass(className); } catch (ClassNotFoundException e) { throw new BeanDefinitionStoreException("Failed to load type: " + className + ". Reason: " + e, e); } try { info = Introspector.getBeanInfo(type); } catch (IntrospectionException e) { throw new BeanDefinitionStoreException("Failed to introspect type: " + className + ". Reason: " + e, e); } return info; } /** * Attempts to load the class on the current thread context class loader or * the class loader which loaded us */ protected Class loadClass(String name) throws ClassNotFoundException { ClassLoader beanClassLoader = readerContext.getReader().getBeanClassLoader(); if (beanClassLoader != null) { try { return beanClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { return contextClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } } return getClass().getClassLoader().loadClass(name); } protected boolean isQnameIsOnClassPath() { if (initQNameOnClassPath == false) { qnameIsOnClassPath = PropertyEditorHelper.loadClass("javax.xml.namespace.QName") != null; initQNameOnClassPath = true; } return qnameIsOnClassPath; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/XBeanNamespaceHandler.java0000644000175000017500000012611511250132672033152 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2c; import java.beans.BeanInfo; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.xml.XMLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xbean.spring.context.impl.MappingMetaData; import org.apache.xbean.spring.context.impl.NamedConstructorArgs; import org.apache.xbean.spring.context.impl.NamespaceHelper; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.util.StringUtils; import org.springframework.core.io.ResourceLoader; 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; import org.w3c.dom.Text; /** * An enhanced XML parser capable of handling custom XML schemas. * * @author James Strachan * @version $Id$ * @since 2.0 */ public class XBeanNamespaceHandler implements NamespaceHandler { public static final String SPRING_SCHEMA = "http://xbean.apache.org/schemas/spring/1.0"; public static final String SPRING_SCHEMA_COMPAT = "http://xbean.org/schemas/spring/1.0"; private static final Log log = LogFactory.getLog(XBeanNamespaceHandler.class); private static final String QNAME_ELEMENT = "qname"; private static final String DESCRIPTION_ELEMENT = "description"; /** * All the reserved Spring XML element names which cannot be overloaded by * an XML extension */ protected static final String[] RESERVED_ELEMENT_NAMES = { "beans", DESCRIPTION_ELEMENT, DefaultBeanDefinitionDocumentReader.IMPORT_ELEMENT, DefaultBeanDefinitionDocumentReader.ALIAS_ELEMENT, DefaultBeanDefinitionDocumentReader.BEAN_ELEMENT, BeanDefinitionParserDelegate.CONSTRUCTOR_ARG_ELEMENT, BeanDefinitionParserDelegate.PROPERTY_ELEMENT, BeanDefinitionParserDelegate.LOOKUP_METHOD_ELEMENT, BeanDefinitionParserDelegate.REPLACED_METHOD_ELEMENT, BeanDefinitionParserDelegate.ARG_TYPE_ELEMENT, BeanDefinitionParserDelegate.REF_ELEMENT, BeanDefinitionParserDelegate.IDREF_ELEMENT, BeanDefinitionParserDelegate.VALUE_ELEMENT, BeanDefinitionParserDelegate.NULL_ELEMENT, BeanDefinitionParserDelegate.LIST_ELEMENT, BeanDefinitionParserDelegate.SET_ELEMENT, BeanDefinitionParserDelegate.MAP_ELEMENT, BeanDefinitionParserDelegate.ENTRY_ELEMENT, BeanDefinitionParserDelegate.KEY_ELEMENT, BeanDefinitionParserDelegate.PROPS_ELEMENT, BeanDefinitionParserDelegate.PROP_ELEMENT, QNAME_ELEMENT }; protected static final String[] RESERVED_BEAN_ATTRIBUTE_NAMES = { AbstractBeanDefinitionParser.ID_ATTRIBUTE, BeanDefinitionParserDelegate.NAME_ATTRIBUTE, BeanDefinitionParserDelegate.CLASS_ATTRIBUTE, BeanDefinitionParserDelegate.PARENT_ATTRIBUTE, BeanDefinitionParserDelegate.DEPENDS_ON_ATTRIBUTE, BeanDefinitionParserDelegate.FACTORY_METHOD_ATTRIBUTE, BeanDefinitionParserDelegate.FACTORY_BEAN_ATTRIBUTE, BeanDefinitionParserDelegate.DEPENDENCY_CHECK_ATTRIBUTE, BeanDefinitionParserDelegate.AUTOWIRE_ATTRIBUTE, BeanDefinitionParserDelegate.INIT_METHOD_ATTRIBUTE, BeanDefinitionParserDelegate.DESTROY_METHOD_ATTRIBUTE, BeanDefinitionParserDelegate.ABSTRACT_ATTRIBUTE, BeanDefinitionParserDelegate.SINGLETON_ATTRIBUTE, BeanDefinitionParserDelegate.LAZY_INIT_ATTRIBUTE }; private static final String JAVA_PACKAGE_PREFIX = "java://"; private static final String BEAN_REFERENCE_PREFIX = "#"; private static final String NULL_REFERENCE = "#null"; private Set reservedElementNames = new HashSet(Arrays.asList(RESERVED_ELEMENT_NAMES)); private Set reservedBeanAttributeNames = new HashSet(Arrays.asList(RESERVED_BEAN_ATTRIBUTE_NAMES)); protected final NamedConstructorArgs namedConstructorArgs = new NamedConstructorArgs(); private ParserContext parserContext; private XBeanQNameHelper qnameHelper; public void init() { } public BeanDefinition parse(Element element, ParserContext parserContext) { this.parserContext = parserContext; this.qnameHelper = new XBeanQNameHelper(parserContext.getReaderContext()); BeanDefinitionHolder holder = parseBeanFromExtensionElement(element); // Only register components: i.e. first level beans (or root element if no element if (element.getParentNode() == element.getOwnerDocument() || element.getParentNode().getParentNode() == element.getOwnerDocument()) { BeanDefinitionReaderUtils.registerBeanDefinition(holder, parserContext.getRegistry()); BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder); parserContext.getReaderContext().fireComponentRegistered(componentDefinition); } return holder.getBeanDefinition(); } public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { if (node instanceof org.w3c.dom.Attr && XMLConstants.XMLNS_ATTRIBUTE.equals(node.getLocalName())) { return definition; // Ignore xmlns="xxx" attributes } throw new IllegalArgumentException("Cannot locate BeanDefinitionDecorator for " + (node instanceof Element ? "element" : "attribute") + " [" + node.getLocalName() + "]."); } /** * Configures the XmlBeanDefinitionReader to work nicely with extensible XML * using this reader implementation. */ public static void configure(AbstractApplicationContext context, XmlBeanDefinitionReader reader) { reader.setNamespaceAware(true); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); } /** * Registers whatever custom editors we need */ public static void registerCustomEditors(DefaultListableBeanFactory beanFactory) { PropertyEditorRegistrar registrar = new PropertyEditorRegistrar() { public void registerCustomEditors(PropertyEditorRegistry registry) { registry.registerCustomEditor(java.io.File.class, new org.apache.xbean.spring.context.impl.FileEditor()); registry.registerCustomEditor(java.net.URI.class, new org.apache.xbean.spring.context.impl.URIEditor()); registry.registerCustomEditor(java.util.Date.class, new org.apache.xbean.spring.context.impl.DateEditor()); registry.registerCustomEditor(javax.management.ObjectName.class, new org.apache.xbean.spring.context.impl.ObjectNameEditor()); } }; beanFactory.addPropertyEditorRegistrar(registrar); } /** * Parses the non-standard XML element as a Spring bean definition */ protected BeanDefinitionHolder parseBeanFromExtensionElement(Element element, String parentClass, String property) { String uri = element.getNamespaceURI(); String localName = getLocalName(element); MappingMetaData metadata = findNamespaceProperties(uri, localName); if (metadata != null) { // lets see if we configured the localName to a bean class String className = getPropertyDescriptor(parentClass, property).getPropertyType().getName(); if (className != null) { return parseBeanFromExtensionElement(element, metadata, className); } } return null; } private BeanDefinitionHolder parseBeanFromExtensionElement(Element element, MappingMetaData metadata, String className) { Element original = cloneElement(element); // lets assume the class name == the package name plus the element.setAttributeNS(null, "class", className); addSpringAttributeValues(className, element); BeanDefinitionHolder definition = parserContext.getDelegate().parseBeanDefinitionElement(element, null); addAttributeProperties(definition, metadata, className, original); addContentProperty(definition, metadata, element); addNestedPropertyElements(definition, metadata, className, element); qnameHelper.coerceNamespaceAwarePropertyValues(definition.getBeanDefinition(), element); declareLifecycleMethods(definition, metadata, element); resolveBeanClass((AbstractBeanDefinition) definition.getBeanDefinition(), definition.getBeanName()); namedConstructorArgs.processParameters(definition, metadata); return definition; } protected Class resolveBeanClass(AbstractBeanDefinition bd, String beanName) { if (bd.hasBeanClass()) { return bd.getBeanClass(); } try { ResourceLoader rl = parserContext.getReaderContext().getResourceLoader(); ClassLoader cl = rl != null ? rl.getClassLoader() : null; if (cl == null) { cl = parserContext.getReaderContext().getReader().getBeanClassLoader(); } if (cl == null) { cl = Thread.currentThread().getContextClassLoader(); } if (cl == null) { cl = getClass().getClassLoader(); } return bd.resolveBeanClass(cl); } catch (ClassNotFoundException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Bean class [" + bd.getBeanClassName() + "] not found", ex); } catch (NoClassDefFoundError err) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Class that bean class [" + bd.getBeanClassName() + "] depends on not found", err); } } /** * Parses the non-standard XML element as a Spring bean definition */ protected BeanDefinitionHolder parseBeanFromExtensionElement(Element element) { String uri = element.getNamespaceURI(); String localName = getLocalName(element); MappingMetaData metadata = findNamespaceProperties(uri, localName); if (metadata != null) { // lets see if we configured the localName to a bean class String className = metadata.getClassName(localName); if (className != null) { return parseBeanFromExtensionElement(element, metadata, className); } else { throw new BeanDefinitionStoreException("Unrecognized xbean element mapping: " + localName + " in namespace " + uri); } } else { if (uri == null) throw new BeanDefinitionStoreException("Unrecognized Spring element: " + localName); else throw new BeanDefinitionStoreException("Unrecognized xbean namespace mapping: " + uri); } } protected void addSpringAttributeValues(String className, Element element) { NamedNodeMap attributes = element.getAttributes(); for (int i = 0, size = attributes.getLength(); i < size; i++) { Attr attribute = (Attr) attributes.item(i); String uri = attribute.getNamespaceURI(); String localName = attribute.getLocalName(); if (uri != null && (uri.equals(SPRING_SCHEMA) || uri.equals(SPRING_SCHEMA_COMPAT))) { element.setAttributeNS(null, localName, attribute.getNodeValue()); } } } /** * Creates a clone of the element and its attribute (though not its content) */ protected Element cloneElement(Element element) { Element answer = element.getOwnerDocument().createElementNS(element.getNamespaceURI(), element.getNodeName()); NamedNodeMap attributes = element.getAttributes(); for (int i = 0, size = attributes.getLength(); i < size; i++) { Attr attribute = (Attr) attributes.item(i); String uri = attribute.getNamespaceURI(); answer.setAttributeNS(uri, attribute.getName(), attribute.getNodeValue()); } return answer; } /** * Parses attribute names and values as being bean property expressions */ protected void addAttributeProperties(BeanDefinitionHolder definition, MappingMetaData metadata, String className, Element element) { NamedNodeMap attributes = element.getAttributes(); // First pass on attributes with no namespaces for (int i = 0, size = attributes.getLength(); i < size; i++) { Attr attribute = (Attr) attributes.item(i); String uri = attribute.getNamespaceURI(); String localName = attribute.getLocalName(); // Skip namespaces if (localName == null || localName.equals("xmlns") || localName.startsWith("xmlns:")) { continue; } // Add attributes with no namespaces if (isEmpty(uri) && !localName.equals("class")) { boolean addProperty = true; if (reservedBeanAttributeNames.contains(localName)) { // should we allow the property to shine through? PropertyDescriptor descriptor = getPropertyDescriptor(className, localName); addProperty = descriptor != null; } if (addProperty) { addAttributeProperty(definition, metadata, element, attribute); } } } // Second pass on attributes with namespaces for (int i = 0, size = attributes.getLength(); i < size; i++) { Attr attribute = (Attr) attributes.item(i); String uri = attribute.getNamespaceURI(); String localName = attribute.getLocalName(); // Skip namespaces if (localName == null || localName.equals("xmlns") || localName.startsWith("xmlns:")) { continue; } // Add attributs with namespaces matching the element ns if (!isEmpty(uri) && uri.equals(element.getNamespaceURI())) { boolean addProperty = true; if (reservedBeanAttributeNames.contains(localName)) { // should we allow the property to shine through? PropertyDescriptor descriptor = getPropertyDescriptor(className, localName); addProperty = descriptor != null; } if (addProperty) { addAttributeProperty(definition, metadata, element, attribute); } } } } protected void addContentProperty(BeanDefinitionHolder definition, MappingMetaData metadata, Element element) { String name = metadata.getContentProperty(getLocalName(element)); if (name != null) { String value = getElementText(element); addProperty(definition, metadata, element, name, value); } else { StringBuffer buffer = new StringBuffer(); NodeList childNodes = element.getChildNodes(); for (int i = 0, size = childNodes.getLength(); i < size; i++) { Node node = childNodes.item(i); if (node instanceof Text) { buffer.append(((Text) node).getData()); } } ByteArrayInputStream in = new ByteArrayInputStream(buffer.toString().getBytes()); Properties properties = new Properties(); try { properties.load(in); } catch (IOException e) { return; } Enumeration enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String propertyName = (String) enumeration.nextElement(); String propertyEditor = metadata.getPropertyEditor(getLocalName(element), propertyName); Object value = getValue(properties.getProperty(propertyName), propertyEditor); definition.getBeanDefinition().getPropertyValues().addPropertyValue(propertyName, value); } } } protected void addAttributeProperty(BeanDefinitionHolder definition, MappingMetaData metadata, Element element, Attr attribute) { String localName = attribute.getLocalName(); String value = attribute.getValue(); addProperty(definition, metadata, element, localName, value); } /** * Add a property onto the current BeanDefinition. */ protected void addProperty(BeanDefinitionHolder definition, MappingMetaData metadata, Element element, String localName, String value) { String propertyName = metadata.getPropertyName(getLocalName(element), localName); String propertyEditor = metadata.getPropertyEditor(getLocalName(element), propertyName); if (propertyName != null) { definition.getBeanDefinition().getPropertyValues().addPropertyValue( propertyName, getValue(value,propertyEditor)); } } protected Object getValue(String value, String propertyEditor) { if (value == null) return null; // // If value is #null then we are explicitly setting the value null instead of an empty string // if (NULL_REFERENCE.equals(value)) { return null; } // // If value starts with # then we have a ref // if (value.startsWith(BEAN_REFERENCE_PREFIX)) { // strip off the # value = value.substring(BEAN_REFERENCE_PREFIX.length()); // if the new value starts with a #, then we had an excaped value (e.g. ##value) if (!value.startsWith(BEAN_REFERENCE_PREFIX)) { return new RuntimeBeanReference(value); } } if( propertyEditor!=null ) { PropertyEditor p = createPropertyEditor(propertyEditor); RootBeanDefinition def = new RootBeanDefinition(); def.setBeanClass(PropertyEditorFactory.class); def.getPropertyValues().addPropertyValue("propertyEditor", p); def.getPropertyValues().addPropertyValue("value", value); return def; } // // Neither null nor a reference // return value; } protected PropertyEditor createPropertyEditor(String propertyEditor) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if( cl==null ) { cl = XBeanNamespaceHandler.class.getClassLoader(); } try { return (PropertyEditor)cl.loadClass(propertyEditor).newInstance(); } catch (Throwable e){ throw (IllegalArgumentException)new IllegalArgumentException("Could not load property editor: "+propertyEditor).initCause(e); } } protected String getLocalName(Element element) { String localName = element.getLocalName(); if (localName == null) { localName = element.getNodeName(); } return localName; } /** * Lets iterate through the children of this element and create any nested * child properties */ protected void addNestedPropertyElements(BeanDefinitionHolder definition, MappingMetaData metadata, String className, Element element) { NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element childElement = (Element) node; String uri = childElement.getNamespaceURI(); String localName = childElement.getLocalName(); if (!isDefaultNamespace(uri) || !reservedElementNames.contains(localName)) { // we could be one of the following // * the child element maps to a tag with inner // tags being the bean // * the child element maps to a tag with // inner tags being the contents of the list // * the child element maps to a tag and is the // bean tag too // * the child element maps to a tag and is a simple // type (String, Class, int, etc). Object value = null; String propertyName = metadata.getNestedListProperty(getLocalName(element), localName); if (propertyName != null) { value = parseListElement(childElement, propertyName); } else { propertyName = metadata.getFlatCollectionProperty(getLocalName(element), localName); if (propertyName != null) { Object def = parserContext.getDelegate().parseCustomElement(childElement); PropertyValue pv = definition.getBeanDefinition().getPropertyValues().getPropertyValue(propertyName); if (pv != null) { Collection l = (Collection) pv.getValue(); l.add(def); continue; } else { ManagedList l = new ManagedList(); l.add(def); value = l; } } else { propertyName = metadata.getNestedProperty(getLocalName(element), localName); if (propertyName != null) { // lets find the first child bean that parses fine value = parseChildExtensionBean(childElement); } } } if (propertyName == null && metadata.isFlatProperty(getLocalName(element), localName)) { value = parseBeanFromExtensionElement(childElement, className, localName); propertyName = localName; } if (propertyName == null) { value = tryParseNestedPropertyViaIntrospection(metadata, className, childElement); propertyName = localName; } if (value != null) { definition.getBeanDefinition().getPropertyValues().addPropertyValue(propertyName, value); } else { /** * In this case there is no nested property, so just do a normal * addProperty like we do with attributes. */ String text = getElementText(childElement); if (text != null) { addProperty(definition, metadata, element, localName, text); } } } } } } /** * Attempts to use introspection to parse the nested property element. */ protected Object tryParseNestedPropertyViaIntrospection(MappingMetaData metadata, String className, Element element) { String localName = getLocalName(element); PropertyDescriptor descriptor = getPropertyDescriptor(className, localName); if (descriptor != null) { return parseNestedPropertyViaIntrospection(metadata, element, descriptor.getName(), descriptor.getPropertyType()); } else { return parseNestedPropertyViaIntrospection(metadata, element, localName, Object.class); } } /** * Looks up the property decriptor for the given class and property name */ protected PropertyDescriptor getPropertyDescriptor(String className, String localName) { BeanInfo beanInfo = qnameHelper.getBeanInfo(className); if (beanInfo != null) { PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { PropertyDescriptor descriptor = descriptors[i]; String name = descriptor.getName(); if (name.equals(localName)) { return descriptor; } } } return null; } /** * Attempts to use introspection to parse the nested property element. */ private Object parseNestedPropertyViaIntrospection(MappingMetaData metadata, Element element, String propertyName, Class propertyType) { if (isMap(propertyType)) { return parseCustomMapElement(metadata, element, propertyName); } else if (isCollection(propertyType)) { return parseListElement(element, propertyName); } else { return parseChildExtensionBean(element); } } protected Object parseListElement(Element element, String name) { return parserContext.getDelegate().parseListElement(element, null); } protected Object parseCustomMapElement(MappingMetaData metadata, Element element, String name) { Map map = new ManagedMap(); Element parent = (Element) element.getParentNode(); String entryName = metadata.getMapEntryName(getLocalName(parent), name); String keyName = metadata.getMapKeyName(getLocalName(parent), name); String dups = metadata.getMapDupsMode(getLocalName(parent), name); boolean flat = metadata.isFlatMap(getLocalName(parent), name); String defaultKey = metadata.getMapDefaultKey(getLocalName(parent), name); if (entryName == null) entryName = "property"; if (keyName == null) keyName = "key"; if (dups == null) dups = "replace"; // TODO : support further customizations //String valueName = "value"; //boolean keyIsAttr = true; //boolean valueIsAttr = false; NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element childElement = (Element) node; String localName = childElement.getLocalName(); String uri = childElement.getNamespaceURI(); if (localName == null || localName.equals("xmlns") || localName.startsWith("xmlns:")) { continue; } // we could use namespaced attributes to differentiate real spring // attributes from namespace-specific attributes if (!flat && !isEmpty(uri) && localName.equals(entryName)) { String key = childElement.getAttribute(keyName); if (key == null || key.length() == 0) { key = defaultKey; } if (key == null) { throw new RuntimeException("No key defined for map " + entryName); } Object keyValue = getValue(key, null); Element valueElement = getFirstChildElement(childElement); Object value; if (valueElement != null) { String valueElUri = valueElement.getNamespaceURI(); String valueElLocalName = valueElement.getLocalName(); if (valueElUri == null || valueElUri.equals(SPRING_SCHEMA) || valueElUri.equals(SPRING_SCHEMA_COMPAT) || valueElUri.equals(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI)) { if (BeanDefinitionParserDelegate.BEAN_ELEMENT.equals(valueElLocalName)) { value = parserContext.getDelegate().parseBeanDefinitionElement(valueElement, null); } else { value = parserContext.getDelegate().parsePropertySubElement(valueElement, null); } } else { value = parserContext.getDelegate().parseCustomElement(valueElement); } } else { value = getElementText(childElement); } addValueToMap(map, keyValue, value, dups); } else if (flat && !isEmpty(uri)) { String key = childElement.getAttribute(keyName); if (key == null || key.length() == 0) { key = defaultKey; } if (key == null) { throw new RuntimeException("No key defined for map entry " + entryName); } Object keyValue = getValue(key, null); childElement.removeAttribute(keyName); BeanDefinitionHolder bdh = parseBeanFromExtensionElement(childElement); addValueToMap(map, keyValue, bdh, dups); } } } return map; } protected void addValueToMap(Map map, Object keyValue, Object value, String dups) { if (map.containsKey(keyValue)) { if ("discard".equalsIgnoreCase(dups)) { // Do nothing } else if ("replace".equalsIgnoreCase(dups)) { map.put(keyValue, value); } else if ("allow".equalsIgnoreCase(dups)) { List l = new ManagedList(); l.add(map.get(keyValue)); l.add(value); map.put(keyValue, l); } else if ("always".equalsIgnoreCase(dups)) { List l = (List) map.get(keyValue); l.add(value); } } else { if ("always".equalsIgnoreCase(dups)) { List l = (List) map.get(keyValue); if (l == null) { l = new ManagedList(); map.put(keyValue, l); } l.add(value); } else { map.put(keyValue, value); } } } protected Element getFirstChildElement(Element element) { NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { return (Element) node; } } return null; } protected boolean isMap(Class type) { return Map.class.isAssignableFrom(type); } /** * Returns true if the given type is a collection type or an array */ protected boolean isCollection(Class type) { return type.isArray() || Collection.class.isAssignableFrom(type); } /** * Iterates the children of this element to find the first nested bean */ protected Object parseChildExtensionBean(Element element) { NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element childElement = (Element) node; String uri = childElement.getNamespaceURI(); String localName = childElement.getLocalName(); if (uri == null || uri.equals(SPRING_SCHEMA) || uri.equals(SPRING_SCHEMA_COMPAT) || uri.equals(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI)) { if (BeanDefinitionParserDelegate.BEAN_ELEMENT.equals(localName)) { return parserContext.getDelegate().parseBeanDefinitionElement(childElement, null); } else { return parserContext.getDelegate().parsePropertySubElement(childElement, null); } } else { Object value = parserContext.getDelegate().parseCustomElement(childElement); if (value != null) { return value; } } } } return null; } /** * Uses META-INF/services discovery to find a Properties file with the XML * marshaling configuration * * @param namespaceURI * the namespace URI of the element * @param localName * the local name of the element * @return the properties configuration of the namespace or null if none * could be found */ protected MappingMetaData findNamespaceProperties(String namespaceURI, String localName) { // lets look for the magic prefix if (namespaceURI != null && namespaceURI.startsWith(JAVA_PACKAGE_PREFIX)) { String packageName = namespaceURI.substring(JAVA_PACKAGE_PREFIX.length()); return new MappingMetaData(packageName); } String uri = NamespaceHelper.createDiscoveryPathName(namespaceURI, localName); InputStream in = loadResource(uri); if (in == null) { if (namespaceURI != null && namespaceURI.length() > 0) { uri = NamespaceHelper.createDiscoveryPathName(namespaceURI); in = loadResource(uri); if (in == null) { uri = NamespaceHelper.createDiscoveryOldPathName(namespaceURI); in = loadResource(uri); } } } if (in != null) { try { Properties properties = new Properties(); properties.load(in); return new MappingMetaData(properties); } catch (IOException e) { log.warn("Failed to load resource from uri: " + uri, e); } } return null; } /** * Loads the resource from the given URI */ protected InputStream loadResource(String uri) { if (System.getProperty("xbean.dir") != null) { File f = new File(System.getProperty("xbean.dir") + uri); try { return new FileInputStream(f); } catch (FileNotFoundException e) { // Ignore } } // lets try the thread context class loader first InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(uri); if (in == null) { ClassLoader cl = parserContext.getReaderContext().getReader().getBeanClassLoader(); if (cl != null) { in = cl.getResourceAsStream(uri); } if (in == null) { in = getClass().getClassLoader().getResourceAsStream(uri); if (in == null) { log.debug("Could not find resource: " + uri); } } } return in; } protected boolean isEmpty(String uri) { return uri == null || uri.length() == 0; } protected boolean isDefaultNamespace(String namespaceUri) { return (!StringUtils.hasLength(namespaceUri) || BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI.equals(namespaceUri)) || SPRING_SCHEMA.equals(namespaceUri) || SPRING_SCHEMA_COMPAT.equals(namespaceUri); } protected void declareLifecycleMethods(BeanDefinitionHolder definitionHolder, MappingMetaData metaData, Element element) { BeanDefinition definition = definitionHolder.getBeanDefinition(); if (definition instanceof AbstractBeanDefinition) { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) definition; if (beanDefinition.getInitMethodName() == null) { beanDefinition.setInitMethodName(metaData.getInitMethodName(getLocalName(element))); } if (beanDefinition.getDestroyMethodName() == null) { beanDefinition.setDestroyMethodName(metaData.getDestroyMethodName(getLocalName(element))); } if (beanDefinition.getFactoryMethodName() == null) { beanDefinition.setFactoryMethodName(metaData.getFactoryMethodName(getLocalName(element))); } } } // ------------------------------------------------------------------------- // // TODO we could apply the following patches into the Spring code - // though who knows if it'll ever make it into a release! :) // // ------------------------------------------------------------------------- /* protected int parseBeanDefinitions(Element root) throws BeanDefinitionStoreException { int beanDefinitionCount = 0; if (isEmpty(root.getNamespaceURI()) || root.getLocalName().equals("beans")) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (IMPORT_ELEMENT.equals(node.getNodeName())) { importBeanDefinitionResource(ele); } else if (ALIAS_ELEMENT.equals(node.getNodeName())) { String name = ele.getAttribute(NAME_ATTRIBUTE); String alias = ele.getAttribute(ALIAS_ATTRIBUTE); getBeanDefinitionReader().getBeanFactory().registerAlias(name, alias); } else if (BEAN_ELEMENT.equals(node.getNodeName())) { beanDefinitionCount++; BeanDefinitionHolder bdHolder = parseBeanDefinitionElement(ele, false); BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getBeanDefinitionReader() .getBeanFactory()); } else { BeanDefinitionHolder bdHolder = parseBeanFromExtensionElement(ele); if (bdHolder != null) { beanDefinitionCount++; BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getBeanDefinitionReader() .getBeanFactory()); } else { log.debug("Ignoring unknown element namespace: " + ele.getNamespaceURI() + " localName: " + ele.getLocalName()); } } } } } else { BeanDefinitionHolder bdHolder = parseBeanFromExtensionElement(root); if (bdHolder != null) { beanDefinitionCount++; BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getBeanDefinitionReader() .getBeanFactory()); } else { log.debug("Ignoring unknown element namespace: " + root.getNamespaceURI() + " localName: " + root.getLocalName()); } } return beanDefinitionCount; } protected BeanDefinitionHolder parseBeanDefinitionElement(Element ele, boolean isInnerBean) throws BeanDefinitionStoreException { BeanDefinitionHolder bdh = super.parseBeanDefinitionElement(ele, isInnerBean); coerceNamespaceAwarePropertyValues(bdh, ele); return bdh; } protected Object parsePropertySubElement(Element element, String beanName) throws BeanDefinitionStoreException { String uri = element.getNamespaceURI(); String localName = getLocalName(element); if ((!isEmpty(uri) && !(uri.equals(SPRING_SCHEMA) || uri.equals(SPRING_SCHEMA_COMPAT))) || !reservedElementNames.contains(localName)) { Object answer = parseBeanFromExtensionElement(element); if (answer != null) { return answer; } } if (QNAME_ELEMENT.equals(localName) && isQnameIsOnClassPath()) { Object answer = parseQNameElement(element); if (answer != null) { return answer; } } return super.parsePropertySubElement(element, beanName); } protected Object parseQNameElement(Element element) { return QNameReflectionHelper.createQName(element, getElementText(element)); } */ /** * Returns the text of the element */ protected String getElementText(Element element) { StringBuffer buffer = new StringBuffer(); NodeList nodeList = element.getChildNodes(); for (int i = 0, size = nodeList.getLength(); i < size; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) { buffer.append(node.getNodeValue()); } } return buffer.toString(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/XBeanBeanDefinitionParserDelegate.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/XBeanBeanDefinitionParserDe0000644000175000017500000001062211030663323033335 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.v2c; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.xbean.spring.context.impl.PropertyEditorHelper; import org.apache.xbean.spring.context.impl.QNameReflectionHelper; import org.apache.xbean.spring.context.v2.XBeanNamespaceHandler; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XBeanBeanDefinitionParserDelegate extends BeanDefinitionParserDelegate { public static final String QNAME_ELEMENT = "qname"; private XBeanQNameHelper qnameHelper; public XBeanBeanDefinitionParserDelegate(XmlReaderContext readerContext) { super(readerContext); qnameHelper = new XBeanQNameHelper(readerContext); } public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultTypeClassName) { if (!isDefaultNamespace(ele.getNamespaceURI())) { return internalParseNestedCustomElement(ele, bd); } else if (ele.getTagName().equals(QNAME_ELEMENT)) { return parseQNameElement(ele); } else { return super.parsePropertySubElement(ele, bd, defaultTypeClassName); } } public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) { AbstractBeanDefinition bd = super.parseBeanDefinitionElement(ele, beanName, containingBean); qnameHelper.coerceNamespaceAwarePropertyValues(bd, ele); return bd; } public boolean isDefaultNamespace(String namespaceUri) { return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri)) || XBeanNamespaceHandler.SPRING_SCHEMA.equals(namespaceUri) || XBeanNamespaceHandler.SPRING_SCHEMA_COMPAT.equals(namespaceUri); } protected Object parseQNameElement(Element element) { return QNameReflectionHelper.createQName(element, getElementText(element)); } protected String getElementText(Element element) { StringBuffer buffer = new StringBuffer(); NodeList nodeList = element.getChildNodes(); for (int i = 0, size = nodeList.getLength(); i < size; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { buffer.append(node.getNodeValue()); } } return buffer.toString(); } private Object internalParseNestedCustomElement(Element candidateEle, BeanDefinition containingBeanDefinition) { try { Method mth = getClass().getSuperclass().getDeclaredMethod("parseNestedCustomElement", new Class[] { Element.class, BeanDefinition.class }); mth.setAccessible(true); return mth.invoke(this, new Object[] { candidateEle, containingBeanDefinition }); } catch (Exception e) { if (e instanceof InvocationTargetException && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw (IllegalStateException) new IllegalStateException("Unable to invoke parseNestedCustomElement method").initCause(e); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/0000755000175000017500000000000011610661036026441 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/MappingMetaData.java0000644000175000017500000002027410575233120032303 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.util.StringTokenizer; /** * A helper class which understands how to map an XML namespaced element to * Spring bean configurations * * @author James Strachan * @version $Id$ * @since 2.0 */ public class MappingMetaData { private Properties properties; private String packageName; /** * Creates an empty MappingMetaData for the specified Java package. * @param packageName the Java package to map */ public MappingMetaData(String packageName) { this.packageName = packageName; this.properties = new Properties(); } /** * Creates MappingMetaData using the specified properties which contan the package name. * @param properties */ public MappingMetaData(Properties properties) { this.properties = properties; } /** * Returns the Java class name for the given XML element name */ public String getClassName(String localName) { String className = properties.getProperty(localName); if (className == null && packageName != null) { if (packageName.length() > 0) { className = packageName + "." + localName; } else { className = localName; } } return className; } /** * Returns the property name for the given element and attribute name * * @param elementName the XML local name of the element * @param attributeName the XML local name of the attribute * @return the property name to use or null if the attribute is not a valid property */ public String getPropertyName(String elementName, String attributeName) { return properties.getProperty(elementName + ".alias." + attributeName, attributeName); } /** * Returns a valid property name if the childElementName maps to a nested list property * * @param elementName the owner element * @param childElementName is the child element name which maps to the nested list property * @return the property name if available or null if it is not applicable */ public String getNestedListProperty(String elementName, String childElementName) { return properties.getProperty(elementName + ".list." + childElementName); } /** * Returns a valid property name if the childElementName maps to a nested bean property * * @param elementName the owner element * @param childElementName is the child element name which maps to the nested bean property * @return the property name if available or null if it is not applicable */ public String getNestedProperty(String elementName, String childElementName) { return properties.getProperty(elementName + ".alias." + childElementName); } public boolean isDefaultConstructor(Constructor constructor) { String property = properties.getProperty(constructorToPropertyName(constructor) + ".default"); if (property != null) { return Boolean.valueOf(property).booleanValue(); } return false; } public boolean isDefaultFactoryMethod(Class beanClass, Method factoryMethod) { String property = properties.getProperty(methodToPropertyName(beanClass, factoryMethod) + ".default"); if (property != null) { return Boolean.valueOf(property).booleanValue(); } return false; } public String[] getParameterNames(Constructor constructor) { String property = properties.getProperty(constructorToPropertyName(constructor) + ".parameterNames"); if (property != null) { ArrayList names = Collections.list(new StringTokenizer(property, ", ")); return (String[]) names.toArray(new String[0]); } return null; } public String[] getParameterNames(Class beanClass, Method factoryMethod) { String property = properties.getProperty(methodToPropertyName(beanClass, factoryMethod) + ".parameterNames"); if (property != null) { ArrayList names = Collections.list(new StringTokenizer(property, ", ")); return (String[]) names.toArray(new String[0]); } return null; } public static String constructorToPropertyName(Constructor constructor) { StringBuffer buf = new StringBuffer(); buf.append(constructor.getName()).append("("); Class[] parameterTypes = constructor.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Class parameterType = parameterTypes[i]; buf.append(parameterType.getName()); if (i < parameterTypes.length - 1) { buf.append(","); } } buf.append(")"); return buf.toString(); } public static String methodToPropertyName(Class beanClass, Method method) { StringBuffer buf = new StringBuffer(); buf.append(beanClass.getName()).append("."); buf.append(method.getName()).append("("); Class[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Class parameterType = parameterTypes[i]; buf.append(parameterType.getName()); if (i < parameterTypes.length - 1) { buf.append(","); } } buf.append(")"); return buf.toString(); } public String getInitMethodName(String elementName) { return properties.getProperty(elementName + ".initMethod"); } public String getDestroyMethodName(String elementName) { return properties.getProperty(elementName + ".destroyMethod"); } public String getFactoryMethodName(String elementName) { return properties.getProperty(elementName + ".factoryMethod"); } public String getContentProperty(String elementName) { return properties.getProperty(elementName + ".contentProperty"); } public String getMapEntryName(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.entryName"); } public String getMapKeyName(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.keyName"); } public boolean isFlatMap(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.flat") != null; } public String getMapDupsMode(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.dups"); } public String getMapDefaultKey(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.defaultKey"); } public String getFlatCollectionProperty(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".flatCollection"); } public boolean isFlatProperty(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".flat") != null; } public String getPropertyEditor(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".propertyEditor"); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/FileEditor.java0000644000175000017500000000236610473277125031351 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.beans.PropertyEditorSupport; import java.io.File; /** * Editor for java.io.File */ public class FileEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { setValue(new File(text)); } public String getAsText() { File value = (File) getValue(); return (value != null ? value.toString() : ""); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/DefaultProperty.java0000644000175000017500000000522410473277125032450 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; /** * DefaultProperty contains the default value assigned to a property with a specific name and type. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class DefaultProperty { private String name; private Class type; private Object value; /** * Creates a new empty default property. This instance is unusable until the name, type and values are assigned. */ public DefaultProperty() { } /** * Creates new default property value for a property with the specified name and type. * @param name the name of the property * @param type the type of the property * @param value the default value */ public DefaultProperty(String name, Class type, Object value) { this.name = name; this.type = type; this.value = value; } /** * Gets the property name. * @return the property name */ public String getName() { return name; } /** * Sets the property name. * @param name the property name */ public void setName(String name) { this.name = name; } /** * Gets the property type. * @return the property type */ public Class getType() { return type; } /** * Sets the property type. * @param type the property type */ public void setType(Class type) { this.type = type; } /** * Gets the default value. * @return the default value */ public Object getValue() { return value; } /** * Sets the default value. * @param value the default value */ public void setValue(Object value) { this.value = value; } /** * {@inheritDoc} */ public String toString() { return "[" + name + ", " + type + ", " + value + "]"; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/XBeanXmlBeanFactory.java0000644000175000017500000000664210473277125033120 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.util.Collections; import java.util.List; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; public class XBeanXmlBeanFactory extends DefaultListableBeanFactory { /** * Create a new XBeanXmlBeanFactory with the given resource, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource) throws BeansException { this(resource, null, Collections.EMPTY_LIST); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException { this(resource, parentBeanFactory, Collections.EMPTY_LIST); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param xmlPreprocessors the preprocessors to apply the DOM before passing to Spring for processing * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, List xmlPreprocessors) throws BeansException { this(resource, null, xmlPreprocessors); } /** * Create a new XBeanXmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @param xmlPreprocessors the preprocessors to apply the DOM before passing to Spring for processing * @throws BeansException in case of loading or parsing errors */ public XBeanXmlBeanFactory(Resource resource, BeanFactory parentBeanFactory, List xmlPreprocessors) throws BeansException { super(parentBeanFactory); XmlBeanDefinitionReader reader = XBeanHelper.createBeanDefinitionReader(null, this, xmlPreprocessors); reader.loadBeanDefinitions(resource); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/URIEditor.java0000644000175000017500000000270110473277125031122 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.beans.PropertyEditorSupport; import java.net.URI; import java.net.URISyntaxException; /** * Editor for java.net.URI */ public class URIEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(new URI(text)); } catch (URISyntaxException e) { throw new IllegalArgumentException( "Could not convert URI for " + text + ": " + e.getMessage()); } } public String getAsText() { URI value = (URI) getValue(); return (value != null ? value.toString() : ""); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/NamespaceHelper.java0000644000175000017500000000450510473277125032354 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; /** * A helper class for turning namespaces into META-INF/services URIs * * @version $Revision: 1.1 $ */ public class NamespaceHelper { public static final String META_INF_PREFIX = "META-INF/services/org/apache/xbean/spring/"; public static final String OLD_META_INF_PREFIX = "META-INF/services/org/xbean/spring/"; /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri, String localName) { if (isEmpty(uri)) { return localName; } return createDiscoveryPathName(uri) + "/" + localName; } /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri) { // TODO proper encoding required // lets replace any dodgy characters return META_INF_PREFIX + uri.replaceAll("://", "/").replace(':', '/').replace(' ', '_'); } /** * Creates the old URI for backwards compatibility */ public static String createDiscoveryOldPathName(String uri) { // TODO proper encoding required // lets replace any dodgy characters return OLD_META_INF_PREFIX + uri.replaceAll("://", "/").replace(':', '/').replace(' ', '_'); } public static boolean isEmpty(String uri) { return uri == null || uri.length() == 0; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/QNameHelper.java0000644000175000017500000001470510576177725031475 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.ManagedList; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.namespace.QName; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; /** * * @version $Revision: 1.1 $ */ public class QNameHelper { private static final Log log = LogFactory.getLog(QNameHelper.class); public static QName createQName(Element element, String qualifiedName) { int index = qualifiedName.indexOf(':'); if (index >= 0) { String prefix = qualifiedName.substring(0, index); String localName = qualifiedName.substring(index + 1); String uri = recursiveGetAttributeValue(element, "xmlns:" + prefix); return new QName(uri, localName, prefix); } else { String uri = recursiveGetAttributeValue(element, "xmlns"); if (uri != null) { return new QName(uri, qualifiedName); } return new QName(qualifiedName); } } /** * Recursive method to find a given attribute value */ public static String recursiveGetAttributeValue(Element element, String attributeName) { String answer = null; try { answer = element.getAttribute(attributeName); } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element + ". Cause: " + e, e); } } if (answer == null || answer.length() == 0) { Node parentNode = element.getParentNode(); if (parentNode instanceof Element) { return recursiveGetAttributeValue((Element) parentNode, attributeName); } } return answer; } public static void coerceQNamePropertyValues(QNameReflectionParams params) { coerceNamespaceAwarePropertyValues(params.getBeanDefinition(), params.getElement(), params.getDescriptors(), params.getIndex()); } public static void coerceNamespaceAwarePropertyValues(AbstractBeanDefinition bd, Element element, PropertyDescriptor[] descriptors, int i) { PropertyDescriptor descriptor = descriptors[i]; // When the property is an indexed property, the getPropertyType can return null. if (descriptor.getPropertyType() == null) { return; } if (descriptor.getPropertyType().isAssignableFrom(QName.class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof String) { propertyValues.removePropertyValue(propertyValue); addPropertyValue(propertyValues, name, createQName(element, (String) value)); } else if (value instanceof TypedStringValue) { propertyValues.removePropertyValue(propertyValue); addPropertyValue(propertyValues, name, createQName(element, ((TypedStringValue) value).getValue())); } } } else if (descriptor.getPropertyType().isAssignableFrom(QName[].class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof List) { List values = (List) value; List newValues = new ManagedList(); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { newValues.add(createQName(element, (String) v)); } else { newValues.add(v); } } propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, newValues); } } } } // Fix Spring 1.2.6 to 1.2.7 binary incompatibility. // The addPropertyValueMethod has changed to return a // value instead of void. // So use reflectiom to handle both cases. private static final Method addPropertyValueMethod; static { try { addPropertyValueMethod = MutablePropertyValues.class.getMethod( "addPropertyValue", new Class[] { String.class, Object.class }); } catch (Exception e) { throw new RuntimeException("Unable to find MutablePropertyValues:addPropertyValue", e); } } public static void addPropertyValue(MutablePropertyValues values, String name, Object value) { try { addPropertyValueMethod.invoke(values, new Object[] { name, value }); } catch (Exception e) { throw new RuntimeException("Error adding property definition", e); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/XBeanHelper.java0000644000175000017500000000446710473277125031464 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.lang.reflect.Constructor; import java.util.List; import org.apache.xbean.spring.context.SpringApplicationContext; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; public class XBeanHelper { public static XmlBeanDefinitionReader createBeanDefinitionReader( SpringApplicationContext applicationContext, BeanDefinitionRegistry registry, List xmlPreprocessors) { String version = "2.0"; try { Class spring20Clazz = Class.forName("org.springframework.core.AttributeAccessorSupport"); version = "2.0"; } catch(ClassNotFoundException e) { version = "1.2.8"; } String className = "org.apache.xbean.spring.context.v" + version.charAt(0) + ".XBeanXmlBeanDefinitionReader"; try { Class cl = Class.forName(className); Constructor cstr = cl.getConstructor(new Class[] { SpringApplicationContext.class, BeanDefinitionRegistry.class, List.class }); return (XmlBeanDefinitionReader) cstr.newInstance(new Object[] { applicationContext, registry, xmlPreprocessors }); } catch (Exception e) { throw (IllegalStateException) new IllegalStateException("Could not find valid implementation for: " + version).initCause(e); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/DateEditor.java0000644000175000017500000000307110473600341031327 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.beans.PropertyEditorSupport; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; /** * Editor for java.util.Date */ public class DateEditor extends PropertyEditorSupport { private DateFormat dateFormat = DateFormat.getInstance(); public void setAsText(String text) throws IllegalArgumentException { try { setValue(dateFormat.parse(text)); } catch (ParseException e) { throw new IllegalArgumentException( "Could not convert Date for " + text + ": " + e.getMessage()); } } public String getAsText() { Date value = (Date) getValue(); return (value != null ? dateFormat.format(value) : ""); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/QNameReflectionParams.java0000644000175000017500000000347210473277125033502 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.w3c.dom.Element; import java.beans.PropertyDescriptor; /** * * @version $Revision: 1.1 $ */ public class QNameReflectionParams { private final AbstractBeanDefinition beanDefinition; private final Element element; private final PropertyDescriptor[] descriptors; private final int index; public QNameReflectionParams(AbstractBeanDefinition beanDefinition, Element element, PropertyDescriptor[] descriptors, int index) { this.beanDefinition = beanDefinition; this.element = element; this.descriptors = descriptors; this.index = index; } public AbstractBeanDefinition getBeanDefinition() { return beanDefinition; } public PropertyDescriptor[] getDescriptors() { return descriptors; } public Element getElement() { return element; } public int getIndex() { return index; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/ObjectNameEditor.java0000644000175000017500000000303710473277125032475 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import java.beans.PropertyEditorSupport; /** * Editor for java.net.URI */ public class ObjectNameEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(new ObjectName(text)); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("Could not convert ObjectName for " + text + ": " + e.getMessage()); } } public String getAsText() { ObjectName value = (ObjectName) getValue(); return (value != null ? value.toString() : ""); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/QNameReflectionHelper.java0000644000175000017500000000643210473277125033475 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.w3c.dom.Element; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; /** * To avoid a runtime dependency on the QName class lets use reflection to * process QName instances. * * @version $Revision: 1.1 $ */ public class QNameReflectionHelper { protected static Method coerceMethod; protected static Method createMethod; public static void coerceNamespaceAwarePropertyValues(AbstractBeanDefinition beanDefinition, Element element, PropertyDescriptor[] descriptors, int index) { QNameReflectionParams params = new QNameReflectionParams(beanDefinition, element, descriptors, index); if (coerceMethod == null) { coerceMethod = findMethod("coerceQNamePropertyValues"); } if (coerceMethod != null) { try { coerceMethod.invoke(null, new Object[] { params }); } catch (Exception e) { throw new BeanDefinitionStoreException("Failed to invoke method: " + coerceMethod + " via reflection: " + e, e); } } } public static Object createQName(Element element, String text) { if (createMethod == null) { createMethod = findMethod("createQName"); } if (createMethod != null) { try { return createMethod.invoke(null, new Object[] { element, text }); } catch (Exception e) { throw new BeanDefinitionStoreException("Failed to invoke method: " + createMethod + " via reflection: " + e, e); } } return null; } protected static Method findMethod(String name) { try { Class type = PropertyEditorHelper.loadClass("org.apache.xbean.spring.context.impl.QNameHelper"); if (type != null) { Method[] methods = type.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals(name)) { return method; } } } } catch (Throwable t) { // Ignore, this is usually because QName method is not in the classpath } return null; } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/NamedConstructorArgs.java0000644000175000017500000003524610473277125033435 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.AbstractBeanDefinition; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * NamedConstructorArgs is a BeanFactoryPostProcessor that converts property declarations into indexed constructor args * based on the the constructor parameter names annotation. This process first selects a constructor and then fills in * the constructor arguments from the properties defined in the bean definition. If a property is not defined in the * bean definition, first the defaultValues map is checked for a value and if a value is not present a Java default * value is provided for the constructor argument (e.g. numbers are assigned 0 and objects are assigned null). * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class NamedConstructorArgs { private Map defaultValues = new HashMap(); /** * Gets the default values that are assigned to constructor arguments without a defined value. * @return the default values that are assigned to constructor arguments without a defined value */ public List getDefaultValues() { List values = new LinkedList(); for (Iterator iterator = defaultValues.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); PropertyKey key = (PropertyKey) entry.getKey(); Object value = entry.getValue(); values.add(new DefaultProperty(key.name, key.type, value)); } return values; } /** * Sets the default values that are assigned to constructor arguments without a defined value. * @param defaultValues the values that are assigned to constructor arguments without a defined value */ public void setDefaultValues(List defaultValues) { this.defaultValues.clear(); for (Iterator iterator = defaultValues.iterator(); iterator.hasNext();) { addDefaultValue((DefaultProperty) iterator.next()); } } /** * Adds a default value for a property with the specified name and type. * @param name the name of the property * @param type the type of the property * @param value the default value for a property with the specified name and type */ public void addDefaultValue(String name, Class type, Object value) { defaultValues.put(new PropertyKey(name, type), value); } /** * Adds a defautl value for a property. * @param defaultProperty the default property information */ private void addDefaultValue(DefaultProperty defaultProperty) { defaultValues.put(new PropertyKey(defaultProperty.getName(), defaultProperty.getType()), defaultProperty.getValue()); } public void processParameters(BeanDefinitionHolder definitionHolder, MappingMetaData metadata) throws BeansException { // this only works if we have an abstsract bean definition if (!(definitionHolder.getBeanDefinition() instanceof AbstractBeanDefinition)) { return; } AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) definitionHolder.getBeanDefinition(); ConstructorArgumentValues constructorArgumentValues = beanDefinition.getConstructorArgumentValues(); // if this bean already has constructor arguments defined, don't mess with them if (constructorArgumentValues.getArgumentCount() > 0) { return; } // try to get a list of constructor arg names to use ConstructionInfo constructionInfo = selectConstructionMethod(beanDefinition, metadata); if (constructionInfo == null) { return; } // remove each named property and add an indexed constructor arg MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); String[] parameterNames = constructionInfo.parameterNames; Class[] parameterTypes = constructionInfo.parameterTypes; for (int i = 0; i < parameterNames.length; i++) { String parameterName = parameterNames[i]; Class parameterType = parameterTypes[i]; PropertyValue propertyValue = propertyValues.getPropertyValue(parameterName); if (propertyValue != null) { propertyValues.removePropertyValue(parameterName); constructorArgumentValues.addIndexedArgumentValue(i, propertyValue.getValue(), parameterType.getName()); } else { Object defaultValue = defaultValues.get(new PropertyKey(parameterName, parameterType)); if (defaultValue == null) { defaultValue = DEFAULT_VALUE.get(parameterType); } if (defaultValue instanceof FactoryBean) { try { defaultValue = ((FactoryBean)defaultValue).getObject(); } catch (Exception e) { throw new FatalBeanException("Unable to get object value from bean factory", e); } } constructorArgumentValues.addIndexedArgumentValue(i, defaultValue, parameterType.getName()); } } // todo set any usable default values on the bean definition } private ConstructionInfo selectConstructionMethod(AbstractBeanDefinition beanDefinition, MappingMetaData metadata) { Class beanClass = beanDefinition.getBeanClass(); // get a set containing the names of the defined properties Set definedProperties = new HashSet(); PropertyValue[] values = beanDefinition.getPropertyValues().getPropertyValues(); for (int i = 0; i < values.length; i++) { definedProperties.add(values[i].getName()); } // first check for a factory method if (beanDefinition.getFactoryMethodName() != null) { return selectFactory(beanClass, beanDefinition, metadata, definedProperties); } else { return selectConstructor(beanClass, metadata, definedProperties); } } private ConstructionInfo selectFactory(Class beanClass, AbstractBeanDefinition beanDefinition, MappingMetaData metadata, Set definedProperties) { String factoryMethodName = beanDefinition.getFactoryMethodName(); // get the factory methods sorted by longest arg length first Method[] methods = beanClass.getMethods(); List factoryMethods = new ArrayList(methods.length); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals(factoryMethodName)) { factoryMethods.add(method); } } Collections.sort(factoryMethods, new ArgLengthComparator()); // if a factory method has been annotated as the default constructor we always use that constructor for (Iterator iterator = factoryMethods.iterator(); iterator.hasNext();) { Method factoryMethod = (Method) iterator.next(); if (metadata.isDefaultFactoryMethod(beanClass, factoryMethod)) { return new ConstructionInfo(beanClass, factoryMethod, metadata); } } // try to find a constructor for which we have all of the properties defined for (Iterator iterator = factoryMethods.iterator(); iterator.hasNext();) { Method factoryMethod = (Method) iterator.next(); ConstructionInfo constructionInfo = new ConstructionInfo(beanClass, factoryMethod, metadata); if (isUsableConstructor(constructionInfo, definedProperties)) { return constructionInfo; } } return null; } private ConstructionInfo selectConstructor(Class beanClass, MappingMetaData metadata, Set definedProperties) { // get the constructors sorted by longest arg length first List constructors = new ArrayList(Arrays.asList(beanClass.getConstructors())); Collections.sort(constructors, new ArgLengthComparator()); // if a constructor has been annotated as the default constructor we always use that constructor for (Iterator iterator = constructors.iterator(); iterator.hasNext();) { Constructor constructor = (Constructor) iterator.next(); if (metadata.isDefaultConstructor(constructor)) { return new ConstructionInfo(constructor, metadata); } } // try to find a constructor for which we have all of the properties defined for (Iterator iterator = constructors.iterator(); iterator.hasNext();) { Constructor constructor = (Constructor) iterator.next(); ConstructionInfo constructionInfo = new ConstructionInfo(constructor, metadata); if (isUsableConstructor(constructionInfo, definedProperties)) { return constructionInfo; } } return null; } private boolean isUsableConstructor(ConstructionInfo constructionInfo, Set definedProperties) { // if we don't have parameter names this is not the constructor we are looking for String[] parameterNames = constructionInfo.parameterNames; if (parameterNames == null) { return false; } Class[] parameterTypes = constructionInfo.parameterTypes; for (int i = 0; i < parameterNames.length; i++) { String parameterName = parameterNames[i]; Class parameterType = parameterTypes[i]; // can we satify this property using a defined property or default property if (!definedProperties.contains(parameterName) && !defaultValues.containsKey(new PropertyKey(parameterName, parameterType))) { return false; } } return true; } private class ConstructionInfo { private final Class[] parameterTypes; private final String[] parameterNames; public ConstructionInfo(Constructor constructor, MappingMetaData metadata) { this.parameterTypes = constructor.getParameterTypes(); String[] names = metadata.getParameterNames(constructor); // verify that we have enough parameter names int expectedParameterCount = parameterTypes.length; if (names != null && names.length != expectedParameterCount) { throw new FatalBeanException("Excpected " + expectedParameterCount + " parameter names for constructor but only got " + names.length + ": " + constructor.toString()); } if (expectedParameterCount == 0) { names = new String[0]; } this.parameterNames = names; } public ConstructionInfo(Class beanClass, Method factoryMethod, MappingMetaData metadata) { this.parameterTypes = factoryMethod.getParameterTypes(); String[] names = metadata.getParameterNames(beanClass, factoryMethod); // verify that we have enough parameter names int expectedParameterCount = parameterTypes.length; if (names != null && names.length != expectedParameterCount) { throw new FatalBeanException("Excpected " + expectedParameterCount + " parameter names for factory method but only got " + names.length + ": " + factoryMethod.toString()); } if (expectedParameterCount == 0) { names = new String[0]; } this.parameterNames = names; } } private static class ArgLengthComparator implements Comparator { public int compare(Object o1, Object o2) { return getArgLength(o2) - getArgLength(o1); } private int getArgLength(Object object) { if (object instanceof Method) { return ((Method) object).getParameterTypes().length; } else { return ((Constructor) object).getParameterTypes().length; } } } private static class PropertyKey { private final String name; private final Class type; public PropertyKey(String name, Class type) { this.name = name; this.type = type; } public boolean equals(Object object) { if (!(object instanceof PropertyKey)) { return false; } PropertyKey defaultProperty = (PropertyKey) object; return name.equals(defaultProperty.name) && type.equals(type); } public int hashCode() { int result = 17; result = 37 * result + name.hashCode(); result = 37 * result + type.hashCode(); return result; } public String toString() { return "[" + name + " " + type + "]"; } } private static final Map DEFAULT_VALUE; static { Map temp = new HashMap(); temp.put(Boolean.TYPE, Boolean.FALSE); temp.put(Byte.TYPE, new Byte((byte) 0)); temp.put(Character.TYPE, new Character((char) 0)); temp.put(Short.TYPE, new Short((short) 0)); temp.put(Integer.TYPE, new Integer(0)); temp.put(Long.TYPE, new Long(0)); temp.put(Float.TYPE, new Float(0)); temp.put(Double.TYPE, new Double(0)); DEFAULT_VALUE = Collections.unmodifiableMap(temp); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/PropertyEditorHelper.java0000644000175000017500000000622610761616442033454 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.beans.PropertyEditorManager; /** * A helper method to register some custom editors * * @version $Revision: 1.1 $ */ public class PropertyEditorHelper { private static final Log log = LogFactory.getLog(PropertyEditorHelper.class); public static void registerCustomEditors() { registerEditor("java.io.File", "org.apache.xbean.spring.context.impl.FileEditor"); registerEditor("java.net.URI", "org.apache.xbean.spring.context.impl.URIEditor"); registerEditor("java.util.Date", "org.apache.xbean.spring.context.impl.DateEditor"); registerEditor("javax.management.ObjectName", "org.apache.xbean.spring.context.impl.ObjectNameEditor"); } protected static void registerEditor(String typeName, String editorName) { Class type = loadClass(typeName); Class editor = loadClass(editorName); if (type != null && editor != null) { PropertyEditorManager.registerEditor(type, editor); } } public static void unregisterCustomEditors() { unregisterEditor("java.io.File"); unregisterEditor("java.net.URI"); unregisterEditor("java.util.Date"); unregisterEditor("javax.management.ObjectName"); } protected static void unregisterEditor(String typeName) { Class type = loadClass(typeName); if (type != null) { PropertyEditorManager.registerEditor(type, null); } } public static Class loadClass(String name) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { return contextClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } catch (NoClassDefFoundError e) { } } try { return PropertyEditorHelper.class.getClassLoader().loadClass(name); } catch (ClassNotFoundException e) { log.debug("Could not find class: " + name + " on the classpath"); return null; } catch (NoClassDefFoundError e) { log.debug("Could not load class: " + name + " on the classpath. " + e.getMessage()); return null; } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/ResourceXmlApplicationContext.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/ResourceXmlApplicationContext.j0000644000175000017500000001167410477627651033704 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.xbean.spring.context.impl.XBeanHelper; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.core.io.Resource; /** * An XBean version of a regular Spring ApplicationContext which takes a * {@link Resource} as a parameter to load the application context * * @author James Strachan * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class ResourceXmlApplicationContext extends AbstractXmlApplicationContext implements SpringApplicationContext { private final List xmlPreprocessors; private final Resource resource; /** * Creates a ResourceXmlApplicationContext which loads the configuration from the specified Resource. * @param resource the resource from which the configuration is loaded */ public ResourceXmlApplicationContext(Resource resource) { this(resource, Collections.EMPTY_LIST); } /** * Creates a ResourceXmlApplicationContext which loads the configuration from the specified Resource. * @param resource the resource from which the configuration is loaded * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing */ public ResourceXmlApplicationContext(Resource resource, List xmlPreprocessors) { super(); this.xmlPreprocessors = xmlPreprocessors; this.resource = resource; refresh(); } public ResourceXmlApplicationContext(Resource resource, ApplicationContext parent) { this(resource, Collections.EMPTY_LIST, parent); } public ResourceXmlApplicationContext(Resource resource, List xmlPreprocessors, ApplicationContext parent) { this(resource, xmlPreprocessors, parent, Collections.EMPTY_LIST); } public ResourceXmlApplicationContext(Resource resource, List xmlPreprocessors, ApplicationContext parent, List beanPostProcessors) { this(resource, xmlPreprocessors, parent, beanPostProcessors, true); } public ResourceXmlApplicationContext(Resource resource, List xmlPreprocessors, ApplicationContext parent, List beanPostProcessors, boolean refresh) { super(parent); this.xmlPreprocessors = xmlPreprocessors; this.resource = resource; for (Iterator iter = beanPostProcessors.iterator(); iter.hasNext();) { BeanFactoryPostProcessor processor = (BeanFactoryPostProcessor) iter.next(); addBeanFactoryPostProcessor(processor); } if (refresh) { refresh(); } } protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = XBeanHelper.createBeanDefinitionReader(this, beanFactory, xmlPreprocessors); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } /** * {@inheritDoc} */ protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { reader.loadBeanDefinitions(resource); } /** * {@inheritDoc} */ protected String[] getConfigLocations() { return null; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/ClassPathXmlApplicationContext.javaxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/ClassPathXmlApplicationContext.0000644000175000017500000002215710473277125033614 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.Collections; import java.util.List; import org.apache.xbean.spring.context.impl.XBeanHelper; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.core.SpringVersion; /** * An XBean version of the regular Spring class to provide improved XML handling. * * @author James Strachan * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class ClassPathXmlApplicationContext extends org.springframework.context.support.ClassPathXmlApplicationContext implements SpringApplicationContext { private final List xmlPreprocessors; /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified location on the class * path. * @param configLocation the location of the configuration file on the class path * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String configLocation) throws BeansException { this(new String[] {configLocation}, true, null, Collections.EMPTY_LIST); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations) throws BeansException { this(configLocations, true, null, Collections.EMPTY_LIST); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException { this(configLocations, refresh, null, Collections.EMPTY_LIST); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param parent the parent of this application context * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException { this(configLocations, true, parent, Collections.EMPTY_LIST); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param parent the parent of this application context * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { this(configLocations, refresh, parent, Collections.EMPTY_LIST); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified location on the class * path. * @param configLocation the location of the configuration file on the classpath * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String configLocation, List xmlPreprocessors) throws BeansException { this(new String[] {configLocation}, true, null, xmlPreprocessors); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, List xmlPreprocessors) throws BeansException { this(configLocations, true, null, xmlPreprocessors); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, List xmlPreprocessors) throws BeansException { this(configLocations, refresh, null, xmlPreprocessors); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param parent the parent of this application context * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, ApplicationContext parent, List xmlPreprocessors) throws BeansException { this(configLocations, true, parent, xmlPreprocessors); } /** * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class * path. * @param configLocations the locations of the configuration files on the class path * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loaded * until refresh() is called * @param parent the parent of this application context * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing * @throws BeansException if a problem occurs while reading the configuration */ public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent, List xmlPreprocessors) throws BeansException { super(configLocations, false, parent); this.xmlPreprocessors = xmlPreprocessors; if (refresh) { refresh(); } } /** * {@inheritDoc} */ protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = XBeanHelper.createBeanDefinitionReader(this, beanFactory, xmlPreprocessors); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/context/SpringApplicationContext.java0000644000175000017500000000603110473277125033346 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ResourceLoader; import java.util.List; /** * SpringApplicationContext is an interface that defines the actual interface exposed by the application contexts * provided by Spring. This interface should be in Spring and the Spring application contexts should implement this * interface. * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public interface SpringApplicationContext extends ConfigurableApplicationContext, DisposableBean, ResourceLoader{ /** * Set a friendly name for this context. * Typically done during initialization of concrete context implementations. * @param displayName the display name for the context */ void setDisplayName(String displayName); /** * Gets the list of BeanPostProcessors that will get applied * to beans created with this factory. * @return the list of BeanPostProcessors that will get applied * to beans created with this factory */ List getBeanFactoryPostProcessors(); /** * Specify the ClassLoader to load class path resources with, * or null if using the thread context class loader on actual access * (applying to the thread that does ClassPathResource calls). *

The default is that ClassLoader access will happen via the thread * context class loader on actual access (applying to the thread that * does ClassPathResource calls). * @param classLoader the ClassLoader to load class path resources */ void setClassLoader(ClassLoader classLoader); /** * Return the ClassLoader to load class path resources with, * or null if using the thread context class loader on actual access * (applying to the thread that does ClassPathResource calls). *

Will get passed to ClassPathResource's constructor for all * ClassPathResource objects created by this resource loader. * * @return the ClassLoader to load class path resources * @see ClassPathResource */ ClassLoader getClassLoader(); } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/util/0000755000175000017500000000000011610661036024771 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/util/AbstractSpringVisitor.java0000644000175000017500000001441510473277125032157 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.util; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Default do nothing implementation of SpringVisitor. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public abstract class AbstractSpringVisitor implements SpringVisitor { public void visitBeanFactory(ConfigurableListableBeanFactory beanRegistry, Object data) throws BeansException { String[] beanNames = beanRegistry.getBeanDefinitionNames(); for (int i = 0; i < beanNames.length; i++) { String beanName = beanNames[i]; visitBeanDefinition(beanName, beanRegistry.getBeanDefinition(beanName), data); } } public void visitBeanDefinitionHolder(BeanDefinitionHolder beanDefinitionHolder, Object data) throws BeansException { visitBeanDefinition(beanDefinitionHolder.getBeanName(), beanDefinitionHolder.getBeanDefinition(), data); } public void visitBeanDefinition(String beanName, BeanDefinition beanDefinition, Object data) throws BeansException { visitBeanDefinition(beanDefinition, data); } public void visitBeanDefinition(BeanDefinition beanDefinition, Object data) throws BeansException { visitConstructorArgumentValues(beanDefinition.getConstructorArgumentValues(), data); visitMutablePropertyValues(beanDefinition.getPropertyValues(), data); } public void visitMutablePropertyValues(MutablePropertyValues propertyValues, Object data) throws BeansException { PropertyValue[] values = propertyValues.getPropertyValues(); for (int i = 0; i < values.length; i++) { visitPropertyValue(values[i], data); } } public void visitConstructorArgumentValues(ConstructorArgumentValues constructorArgumentValues, Object data) throws BeansException { Map indexedArgumentValues = constructorArgumentValues.getIndexedArgumentValues(); for (Iterator iterator = indexedArgumentValues.values().iterator(); iterator.hasNext();) { visitConstructorArgumentValue((ConstructorArgumentValues.ValueHolder) iterator.next(), data); } List genericArgumentValues = constructorArgumentValues.getGenericArgumentValues(); for (Iterator iterator = genericArgumentValues.iterator(); iterator.hasNext();) { visitConstructorArgumentValue((ConstructorArgumentValues.ValueHolder) iterator.next(), data); } } public void visitConstructorArgumentValue(ConstructorArgumentValues.ValueHolder valueHolder, Object data) throws BeansException { visitNext(valueHolder.getValue(), data); } public void visitPropertyValue(PropertyValue propertyValue, Object data) throws BeansException { visitNext(propertyValue.getValue(), data); } public void visitRuntimeBeanReference(RuntimeBeanReference beanReference, Object data) throws BeansException { } public void visitCollection(Collection collection, Object data) throws BeansException { for (Iterator iterator = collection.iterator(); iterator.hasNext();) { visitNext(iterator.next(), data); } } public void visitMap(Map map, Object data) throws BeansException { for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); visitNext(entry.getKey(), data); visitNext(entry.getValue(), data); } } public void visitObject(Object value, Object data) throws BeansException { } protected void visitNext(Object value, Object data) throws BeansException { if (value == null) { return; } if (value instanceof ConfigurableListableBeanFactory) { visitBeanFactory((ConfigurableListableBeanFactory) value, data); } else if (value instanceof BeanDefinitionHolder) { visitBeanDefinitionHolder((BeanDefinitionHolder) value, data); } else if (value instanceof BeanDefinition) { visitBeanDefinition((BeanDefinition) value, data); } else if (value instanceof ConstructorArgumentValues) { visitConstructorArgumentValues((ConstructorArgumentValues) value, data); } else if (value instanceof ConstructorArgumentValues.ValueHolder) { visitConstructorArgumentValue((ConstructorArgumentValues.ValueHolder) value, data); } else if (value instanceof MutablePropertyValues) { visitMutablePropertyValues((MutablePropertyValues) value, data); } else if (value instanceof PropertyValue) { visitPropertyValue((PropertyValue) value, data); } else if (value instanceof RuntimeBeanReference) { visitRuntimeBeanReference((RuntimeBeanReference) value, data); } else if (value instanceof Map) { visitMap((Map) value, data); } else if (value instanceof Collection) { visitCollection((Collection) value, data); } else { visitObject(value, data); } } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/util/SpringVisitor.java0000644000175000017500000000532510473277125030473 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.util; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import java.util.Collection; import java.util.Map; /** * Walks a spring bean factory tree. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public interface SpringVisitor { void visitBeanFactory(ConfigurableListableBeanFactory beanRegistry, Object data) throws BeansException; void visitBeanDefinition(String beanName, BeanDefinition beanDefinition, Object data) throws BeansException; void visitBeanDefinition(BeanDefinition beanDefinition, Object data) throws BeansException; void visitMutablePropertyValues(MutablePropertyValues propertyValues, Object data) throws BeansException; void visitConstructorArgumentValues(ConstructorArgumentValues constructorArgumentValues, Object data) throws BeansException; void visitConstructorArgumentValue(ConstructorArgumentValues.ValueHolder valueHolder, Object data) throws BeansException; void visitPropertyValue(PropertyValue propertyValue, Object data) throws BeansException; void visitRuntimeBeanReference(RuntimeBeanReference beanReference, Object data) throws BeansException; void visitCollection(Collection collection, Object data) throws BeansException; void visitMap(Map map, Object data) throws BeansException; void visitObject(Object value, Object data) throws BeansException; void visitBeanDefinitionHolder(BeanDefinitionHolder beanDefinitionHolder, Object data) throws BeansException; } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/jndi/0000755000175000017500000000000011610661036024740 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/jndi/SpringInitialContextFactory.java0000644000175000017500000001003710601307603033251 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.jndi; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceEditor; import org.apache.xbean.spring.context.impl.XBeanXmlBeanFactory; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * A simple JNDI initial context which loads the JNDI namespace from a spring.xml configuration file. * The spring.xml configuration file can be specified by the {@link Context#PROVIDER_URL} property * which can be any spring resource string (classpath://foo.xml, or file://foo/bar.xml or a URL) * otherwise the jndi.xml file is found on the classpath. * * @version $Revision: 657 $ */ public class SpringInitialContextFactory implements InitialContextFactory { private static final transient Log log = LogFactory.getLog(SpringInitialContextFactory.class); private static Map cache = new HashMap(); private static Context singleton; /** * A factory method which can be used to initialise a singleton JNDI context from inside a Spring.xml * such that future calls to new InitialContext() will reuse it */ public static Context makeInitialContext() { singleton = new DefaultContext(); return singleton; } public Context getInitialContext(Hashtable environment) throws NamingException { if (singleton != null) { return singleton; } Resource resource = null; Object value = environment.get(Context.PROVIDER_URL); String key = "jndi.xml"; if (value == null) { resource = new ClassPathResource(key); } else { if (value instanceof Resource) { resource = (Resource) value; } else { ResourceEditor editor = new ResourceEditor(); key = value.toString(); editor.setAsText(key); resource = (Resource) editor.getValue(); } } BeanFactory context = loadContext(resource, key); Context answer = (Context) context.getBean("jndi"); if (answer == null) { log.warn("No JNDI context available in JNDI resource: " + resource); answer = new DefaultContext(environment, new ConcurrentHashMap()); } return answer; } protected BeanFactory loadContext(Resource resource, String key) { synchronized (cache) { BeanFactory answer = (BeanFactory) cache.get(key); if (answer == null) { answer = createContext(resource); cache.put(key, answer); } return answer; } } protected BeanFactory createContext(Resource resource) { log.info("Loading JNDI context from: " + resource); return new XBeanXmlBeanFactory(resource); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/jndi/NameParserImpl.java0000644000175000017500000000231110473277125030467 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.jndi; import javax.naming.CompositeName; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; /** * A default implementation of {@link NameParser} * * @version $Revision: 1.2 $ */ public class NameParserImpl implements NameParser { public Name parse(String name) throws NamingException { return new CompositeName(name); } } xbean-3.7/xbean-spring/src/main/java/org/apache/xbean/spring/jndi/DefaultContext.java0000644000175000017500000003631110473277125030550 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.jndi; import javax.naming.Binding; import javax.naming.CompositeName; import javax.naming.Context; import javax.naming.LinkRef; import javax.naming.Name; import javax.naming.NameClassPair; import javax.naming.NameNotFoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.NotContextException; import javax.naming.OperationNotSupportedException; import javax.naming.Reference; import javax.naming.spi.NamingManager; import java.io.Serializable; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; /** * A simple spring based JNDI context which is mutable * * @version $Revision: 657 $ */ public class DefaultContext implements Context, Serializable { private static final long serialVersionUID = -5754338187296859149L; protected static final NameParser nameParser = new NameParserImpl(); private boolean freeze = false; protected final Hashtable environment; // environment for this context protected final Map bindings; // bindings at my level protected final Map treeBindings; // all bindings under me private boolean frozen = false; private String nameInNamespace = ""; public static final String SEPARATOR = "/"; public DefaultContext() { environment = new Hashtable(); bindings = new HashMap(); treeBindings = new HashMap(); } public DefaultContext(Hashtable env) { if (env == null) { this.environment = new Hashtable(); } else { this.environment = new Hashtable(env); } this.bindings = new HashMap(); this.treeBindings = new HashMap(); } public DefaultContext(Hashtable environment, Map bindings) { if (environment == null) { this.environment = new Hashtable(); } else { this.environment = new Hashtable(environment); } this.bindings = bindings; treeBindings = new HashMap(); frozen = true; } public DefaultContext(Hashtable environment, Map bindings, String nameInNamespace) { this(environment, bindings); this.nameInNamespace = nameInNamespace; } protected DefaultContext(DefaultContext clone, Hashtable env) { this.bindings = clone.bindings; this.treeBindings = clone.treeBindings; this.environment = new Hashtable(env); } protected DefaultContext(DefaultContext clone, Hashtable env, String nameInNamespace) { this(clone, env); this.nameInNamespace = nameInNamespace; } public Object addToEnvironment(String propName, Object propVal) throws NamingException { return environment.put(propName, propVal); } public Hashtable getEnvironment() throws NamingException { return (Hashtable) environment.clone(); } public Object removeFromEnvironment(String propName) throws NamingException { return environment.remove(propName); } public Object lookup(String name) throws NamingException { if (name.length() == 0) { return this; } Object result = treeBindings.get(name); if (result == null) { result = bindings.get(name); } if (result == null) { int pos = name.indexOf(':'); if (pos > 0) { String scheme = name.substring(0, pos); Context ctx = NamingManager.getURLContext(scheme, environment); if (ctx == null) { throw new NamingException("scheme " + scheme + " not recognized"); } return ctx.lookup(name); } else { // Split out the first name of the path // and look for it in the bindings map. CompositeName path = new CompositeName(name); if (path.size() == 0) { return this; } else { String first = path.get(0); Object obj = bindings.get(first); if (obj == null) { throw new NameNotFoundException(name); } else if (obj instanceof Context && path.size() > 1) { Context subContext = (Context) obj; obj = subContext.lookup(path.getSuffix(1)); } return obj; } } } if (result instanceof LinkRef) { LinkRef ref = (LinkRef) result; result = lookup(ref.getLinkName()); } if (result instanceof Reference) { try { result = NamingManager.getObjectInstance(result, null, null, this.environment); } catch (NamingException e) { throw e; } catch (Exception e) { throw (NamingException) new NamingException("could not look up : " + name).initCause(e); } } if (result instanceof DefaultContext) { String prefix = getNameInNamespace(); if (prefix.length() > 0) { prefix = prefix + SEPARATOR; } result = new DefaultContext((DefaultContext) result, environment, prefix + name); } return result; } public Object lookup(Name name) throws NamingException { return lookup(name.toString()); } public Object lookupLink(String name) throws NamingException { return lookup(name); } public Name composeName(Name name, Name prefix) throws NamingException { Name result = (Name) prefix.clone(); result.addAll(name); return result; } public String composeName(String name, String prefix) throws NamingException { CompositeName result = new CompositeName(prefix); result.addAll(new CompositeName(name)); return result.toString(); } public NamingEnumeration list(String name) throws NamingException { Object o = lookup(name); if (o == this) { return new DefaultContext.ListEnumeration(); } else if (o instanceof Context) { return ((Context) o).list(""); } else { throw new NotContextException(); } } public NamingEnumeration listBindings(String name) throws NamingException { Object o = lookup(name); if (o == this) { return new DefaultContext.ListBindingEnumeration(); } else if (o instanceof Context) { return ((Context) o).listBindings(""); } else { throw new NotContextException(); } } public Object lookupLink(Name name) throws NamingException { return lookupLink(name.toString()); } public NamingEnumeration list(Name name) throws NamingException { return list(name.toString()); } public NamingEnumeration listBindings(Name name) throws NamingException { return listBindings(name.toString()); } public void bind(Name name, Object value) throws NamingException { bind(name.toString(), value); } public void bind(String name, Object value) throws NamingException { checkFrozen(); internalBind(name, value); } public void close() throws NamingException { // ignore } public Context createSubcontext(Name name) throws NamingException { throw new OperationNotSupportedException(); } public Context createSubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); } public void destroySubcontext(Name name) throws NamingException { throw new OperationNotSupportedException(); } public void destroySubcontext(String name) throws NamingException { throw new OperationNotSupportedException(); } public String getNameInNamespace() throws NamingException { return nameInNamespace; } public NameParser getNameParser(Name name) throws NamingException { return nameParser; } public NameParser getNameParser(String name) throws NamingException { return nameParser; } public void rebind(Name name, Object value) throws NamingException { rebind(name.toString(), value); } public void rebind(String name, Object value) throws NamingException { checkFrozen(); internalBind(name, value, true); } public void rename(Name oldName, Name newName) throws NamingException { checkFrozen(); Object value = lookup(oldName); unbind(oldName); bind(newName, value); } public void rename(String oldName, String newName) throws NamingException { Object value = lookup(oldName); unbind(oldName); bind(newName, value); } public void unbind(Name name) throws NamingException { unbind(name.toString()); } public void unbind(String name) throws NamingException { checkFrozen(); internalBind(name, null, true); } private abstract class LocalNamingEnumeration implements NamingEnumeration { private Iterator i = bindings.entrySet().iterator(); public boolean hasMore() throws NamingException { return i.hasNext(); } public boolean hasMoreElements() { return i.hasNext(); } protected Map.Entry getNext() { return (Map.Entry) i.next(); } public void close() throws NamingException { } } private class ListEnumeration extends DefaultContext.LocalNamingEnumeration { public Object next() throws NamingException { return nextElement(); } public Object nextElement() { Map.Entry entry = getNext(); return new NameClassPair((String) entry.getKey(), entry.getValue().getClass().getName()); } } private class ListBindingEnumeration extends DefaultContext.LocalNamingEnumeration { public Object next() throws NamingException { return nextElement(); } public Object nextElement() { Map.Entry entry = getNext(); return new Binding((String) entry.getKey(), entry.getValue()); } } public Map getEntries() { return new HashMap(bindings); } public void setEntries(Map entries) throws NamingException { if (entries != null) { for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); internalBind(name, value); } } } public boolean isFreeze() { return freeze; } public void setFreeze(boolean freeze) { this.freeze = freeze; } /** * internalBind is intended for use only during setup or possibly by suitably synchronized superclasses. * It binds every possible lookup into a map in each context. To do this, each context * strips off one name segment and if necessary creates a new context for it. Then it asks that context * to bind the remaining name. It returns a map containing all the bindings from the next context, plus * the context it just created (if it in fact created it). (the names are suitably extended by the segment * originally lopped off). * * @param name * @param value * @return * @throws javax.naming.NamingException */ protected Map internalBind(String name, Object value) throws NamingException { return internalBind(name, value, false); } protected Map internalBind(String name, Object value, boolean allowRebind) throws NamingException { if (name == null || name.length() == 0){ throw new NamingException("Invalid Name " + name); } if (frozen){ throw new NamingException("Read only"); } Map newBindings = new HashMap(); int pos = name.indexOf('/'); if (pos == -1) { Object oldValue = treeBindings.put(name, value); if (!allowRebind && oldValue != null) { throw new NamingException("Something already bound at " + name); } bindings.put(name, value); newBindings.put(name, value); } else { String segment = name.substring(0, pos); if (segment == null || segment.length()==0){ throw new NamingException("Invalid segment " + segment); } Object o = treeBindings.get(segment); if (o == null) { o = newContext(); treeBindings.put(segment, o); bindings.put(segment, o); newBindings.put(segment, o); } else if (!(o instanceof DefaultContext)) { throw new NamingException("Something already bound where a subcontext should go"); } DefaultContext defaultContext = (DefaultContext) o; String remainder = name.substring(pos + 1); Map subBindings = defaultContext.internalBind(remainder, value, allowRebind); for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String subName = segment + "/" + (String) entry.getKey(); Object bound = entry.getValue(); treeBindings.put(subName, bound); newBindings.put(subName, bound); } } return newBindings; } protected void checkFrozen() throws OperationNotSupportedException { if (isFreeze()) { throw new OperationNotSupportedException("JNDI context is frozen!"); } } protected DefaultContext newContext() { return new DefaultContext(); } } xbean-3.7/xbean-spring/src/test/0000755000175000017500000000000011610661035016516 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/0000755000175000017500000000000011610661035020530 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/0000755000175000017500000000000011610661035021670 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/0000755000175000017500000000000011610661035023513 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/0000755000175000017500000000000011610661035024302 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/0000755000175000017500000000000011610661035025523 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/0000755000175000017500000000000011610661035026620 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/0000755000175000017500000000000011610661035030122 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/0000755000175000017500000000000011610661035031101 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/xbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000755000175000017500000000000011610661035033172 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/xbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000755000175000017500000000000011610661035033172 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/componentxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000644000175000017500000000164110541574201033176 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # container=org.apache.xbean.spring.example.ContainerBean inner=org.apache.xbean.spring.example.InnerBean ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/soupxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000644000175000017500000000237310541574201033201 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes soup = org.apache.xbean.spring.example.SoupService # Mapping of life-cycle methods soup.initMethod = make soup.destroyMethod = eat soup.factoryMethod = newSoup # Mapping of constructor argument names org.apache.xbean.spring.example.SoupService.newSoup(java.lang.String).parameterNames=type # END SNIPPET: config ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/pizza-simplexbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000644000175000017500000000211310541574201033171 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes pizza = org.apache.xbean.spring.example.PizzaService restaurant = org.apache.xbean.spring.example.RestaurantService # END SNIPPET: config ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/restaurantxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000644000175000017500000000241010541574201033171 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes pizza = org.apache.xbean.spring.example.PizzaService restaurant = org.apache.xbean.spring.example.RestaurantService # Mapping of XML Attributes to property names pizza.alias.myTopping = topping # Mapping of nested bean properties restaurant.dinnerMenu.list = dinnerMenu restaurant.favourite = favourite # END SNIPPET: config ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apache.org/schemas/saladxbean-3.7/xbean-spring/src/test/resources/META-INF/services/org/apache/xbean/spring/http/xbean.apach0000644000175000017500000000240310541574201033173 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes salad = org.apache.xbean.spring.example.SaladService # Mapping of XML Attributes to property names salad.alias.addCroutons = crouton # Mapping of constructor argument names org.apache.xbean.spring.example.SaladService(java.lang.String,java.lang.String,boolean).parameterNames=dressing size crouton # END SNIPPET: config xbean-3.7/xbean-spring/src/test/resources/org/0000755000175000017500000000000011610661035021317 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/0000755000175000017500000000000011610661035022540 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/0000755000175000017500000000000011610661035023635 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/0000755000175000017500000000000011610661036025140 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/generator/0000755000175000017500000000000011610661036027126 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/generator/model-test-xsd-validation.xmlxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/generator/model-test-xsd-validatio0000644000175000017500000000401011252465671033700 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/0000755000175000017500000000000011610661036026624 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/spring-extension.xml0000644000175000017500000000214510512740134032661 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/bad-attribute.xml0000644000175000017500000000173210512740134032075 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/flatmap-xbean.xml0000644000175000017500000000243410575233210032066 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/keg-xbean.xml0000644000175000017500000000216410512740134031207 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/qname-xbean.xml0000644000175000017500000000222010512740134031533 0ustar drazzibdrazzib foo:test foo:bar foo:list xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/favorite-xbean.xml0000644000175000017500000000302210575220641032257 0ustar drazzibdrazzib Grey Goose Malbec xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/gin.xml0000644000175000017500000000201310512740134030114 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/component-spring.xml0000644000175000017500000000215610512740134032651 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/bad-element.xml0000644000175000017500000000172610512740134031526 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/beer-xbean-ns.xml0000644000175000017500000000222110512740134031766 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/favorite-normal.xml0000644000175000017500000000316210575220641032457 0ustar drazzibdrazzib Grey Goose Malbec xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/wine-xbean.xml0000644000175000017500000000177210512740134031407 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/recipe-normal.xml0000644000175000017500000000342710512740134032106 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/beer-xbean-null.xml0000644000175000017500000000224010512740134032321 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/bad-namespace.xml0000644000175000017500000000167110512740134032030 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/recipe-xbean.xml0000644000175000017500000000261610512740134031712 0ustar drazzibdrazzib Mash together Food Mash together Food Mash together Food xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/pizza-xbean-java.xml0000644000175000017500000000204010512740134032506 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/salad-normal.xml0000644000175000017500000000232210512740134031714 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/beer-normal.xml0000644000175000017500000000217210512740134031550 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-xbean-simple.xmlxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-xbean-simple.xm0000644000175000017500000000276210635623317033761 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/vodka-normal.xml0000644000175000017500000000234110512740134031735 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/beer-xbean-system-prop.xml0000644000175000017500000000223210512740134033652 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/pizza-xbean-bean-ref.xml0000644000175000017500000000224110512740134033247 0ustar drazzibdrazzib Salami xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-xbean-root.xml0000644000175000017500000000304310635623317033620 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/socket-address-normal.xml0000644000175000017500000000337511055155653033565 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/keg-xbean-properties.propertiesxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/keg-xbean-properties.prope0000644000175000017500000000154211373033431033726 0ustar drazzibdrazzib# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. ml1000=1000 ml pints5=5 pints liter20=20 liter empty=0xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/keg-xbean-properties.xml0000644000175000017500000000251710741146234033410 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/qname-normal.xml0000644000175000017500000000320710512740134031734 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/soup-xbean.xml0000644000175000017500000000247410512740134031433 0ustar drazzibdrazzib French Onion xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-normal.xml0000644000175000017500000000565010635623317033040 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/wine-normal.xml0000644000175000017500000000217310512740134031576 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/pizza-xbean-properties.xml0000644000175000017500000000222010512740134033761 0ustar drazzibdrazzib cheese Edam Salami size 17 xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/socket-address.xml0000644000175000017500000000241411055155653032270 0ustar drazzibdrazzib localhost localhost localhost xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/component-xbean.xml0000644000175000017500000000205110512740134032436 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/soup-normal.xml0000644000175000017500000000235510512740134031624 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-xbean.xml0000644000175000017500000000313210635623317032636 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/pizza-normal.xml0000644000175000017500000000225110512740134031766 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-spring-extended.xmlxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-spring-extended0000644000175000017500000000530610635623317034047 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/pizza-xbean.xml0000644000175000017500000000203210512740134031570 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/restaurant-xbean-mixed.xml0000644000175000017500000000427010635623317033746 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/recipe-xbean-mixed.xml0000644000175000017500000000301011030653002032774 0ustar drazzibdrazzib Mash together Food Mash together Food xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/vodka-xbean.xml0000644000175000017500000000214710512740134031546 0ustar drazzibdrazzib Grey Goose org.apache.xbean.spring.example.VodkaService xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/favorite-xbean-mixed.xml0000644000175000017500000000324311030663323033363 0ustar drazzibdrazzib Malbec xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/salad-xbean.xml0000644000175000017500000000207310512740134031524 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/context/beer-xbean.xml0000644000175000017500000000207110512740134031353 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/jndi/0000755000175000017500000000000011610661036026064 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/jndi/jndi.xml0000644000175000017500000000332410512740134027531 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/resources/org/apache/xbean/spring/jndi/spring.xml0000644000175000017500000000332010512740134030103 0ustar drazzibdrazzib xbean-3.7/xbean-spring/src/test/java/0000755000175000017500000000000011610661034017436 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/0000755000175000017500000000000011610661034020225 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/0000755000175000017500000000000011610661034021446 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661034022543 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/0000755000175000017500000000000011610661035024046 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/generator/0000755000175000017500000000000011610661035026034 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/generator/CheeseService.java0000644000175000017500000000316311251237773031430 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; /** * Cheezy goodness * * @org.apache.xbean.XBean element="cheese" * * @author Dain Sundstrom * @version $Id$ */ public class CheeseService { private String id; private String name; private long volume; public CheeseService(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public long getVolumeWithPropertyEditor() { return volume; } /** * @org.apache.xbean.Property propertyEditor="org.apache.xbean.spring.example.MilliLittersPropertyEditor" */ public void setVolumeWithPropertyEditor(long volume) { this.volume = volume; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/generator/ModelTest.java0000644000175000017500000002244411252465671030617 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.generator; import junit.framework.TestCase; import org.apache.xbean.spring.example.BeerService; import org.springframework.beans.factory.xml.PluggableSchemaResolver; import org.xml.sax.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.beans.PropertyEditorManager; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class ModelTest extends TestCase { private static final String DEFAULT_NAMESPACE = "http://xbean.apache.org/test"; public void testQdox() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, null); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNotNull(element); AttributeMapping attribute = element.getAttribute("myTopping"); assertNotNull(attribute); assertEquals("topping", attribute.getPropertyName()); ElementMapping beer = defaultNamespace.getElement("beer"); assertNotNull(beer); AttributeMapping beerId = beer.getAttribute("id"); assertNotNull(beerId); AttributeMapping beerName = beer.getAttribute("name"); assertNotNull(beerName); ElementMapping recipeService = defaultNamespace.getElement("recipe-service"); assertNotNull(recipeService); Map flatCollections = recipeService.getFlatCollections(); assertNotNull(flatCollections); assertEquals(1, flatCollections.size()); ElementMapping cheese = defaultNamespace.getElement("cheese"); assertNotNull(cheese); AttributeMapping volume = cheese.getAttribute("volumeWithPropertyEditor"); assertNotNull(volume); assertNotNull(volume.getPropertyEditor()); assertEquals(volume.getType().getName(), "long"); // validate xsd has string for attribute VolumeWithPropertyEditor final AtomicBoolean gotExpected = new AtomicBoolean(false); XsdGenerator generator = new XsdGenerator(null); generator.generateSchema(new PrintWriter("dummy") { @Override public void println(String x) { if (x.indexOf("volumeWithPropertyEditor") != -1) { if (x.indexOf("xs:string") != -1) { gotExpected.set(true); } } } }, defaultNamespace); assertTrue("xsd with string got genereated", gotExpected.get()); } public void testQdoxExcludeClass() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, new String[] { BeerService.class.getName() } ); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNotNull(element); ElementMapping beer = defaultNamespace.getElement("beer"); assertNull(beer); } public void testQdoxExcludePackage() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, new String[] { "org.apache.xbean.spring.example" } ); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNull(element); ElementMapping beer = defaultNamespace.getElement("beer"); assertNull(beer); ElementMapping cheese = defaultNamespace.getElement("cheese"); assertNotNull(cheese); } private NamespaceMapping getDefaultNamespace(QdoxMappingLoader mappingLoader) throws IOException { Set namespaces = mappingLoader.loadNamespaces(); assertFalse(namespaces.isEmpty()); NamespaceMapping defaultNamespace = null; for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); if (namespaceMapping.getNamespace().equals(DEFAULT_NAMESPACE)) { defaultNamespace = namespaceMapping; break; } } return defaultNamespace; } public void testPropertyEditor() { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); editorSearchPath.add("org.apache.xbean.spring.context.impl"); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); assertTrue(Utils.isSimpleType(Type.newSimpleType("java.net.URI"))); } public void testXSDValidation() throws Exception{ InputStream xmlFile = ModelTest.class.getResourceAsStream("model-test-xsd-validation.xml"); File xsd = generateXSD(); validate(xmlFile, xsd); } private File generateXSD() throws IOException { String basedir = System.getProperties().getProperty("basedir", "."); final File targetXSD = new File(basedir, "target/test-data/model-test.xsd"); targetXSD.getParentFile().mkdirs(); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, null); NamespaceMapping namespaceMapping = getDefaultNamespace(mappingLoader); XsdGenerator generator = new XsdGenerator(targetXSD); generator.setLog(new LogFacade() { public void log(String message) { } public void log(String message, int level) { } }); generator.generate(namespaceMapping); return targetXSD; } private void validate(InputStream xml, final File xsd) throws ParserConfigurationException, SAXException, IOException { assertNotNull(xml); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); final AtomicReference error = new AtomicReference(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { error.set(exception); } public void error(SAXParseException exception) throws SAXException { error.set(exception); } public void fatalError(SAXParseException exception) throws SAXException { error.set(exception); } }); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { PluggableSchemaResolver springResolver = new PluggableSchemaResolver(getClass().getClassLoader()); InputSource source = springResolver.resolveEntity(publicId, systemId); if (source == null && "http://xbean.apache.org/test.xsd".equals(systemId)) { source = new InputSource(new FileInputStream(xsd)); source.setPublicId(publicId); source.setSystemId(systemId); } return source; } }); builder.parse(xml); if (error.get() != null) { error.get().printStackTrace(); fail("Validateion failed: " + error.get().getMessage()); } } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/0000755000175000017500000000000011610661035025501 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/SocketAddressFactory.java0000644000175000017500000000226611055155653032447 0ustar drazzibdrazzib/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.net.SocketAddress; import java.net.InetSocketAddress; /** * @org.apache.xbean.XBean element="socketAddress" contentProperty="value" */ public class SocketAddressFactory { /** * @org.apache.xbean.FactoryMethod */ public static SocketAddress create(String value) { return new InetSocketAddress(value, 42); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/SaladService.java0000644000175000017500000000335710512740134030717 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * Basic salad. * @org.apache.xbean.XBean * * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ // START SNIPPET: bean public class SaladService { private final String dressing; private final String size; private final boolean crouton; public SaladService(String dressing, String size, boolean crouton) { this.dressing = dressing; this.size = size; this.crouton = crouton; } /** * Dressing What type of dressing do you want? */ public String getDressing() { return dressing; } /** * What size do you want? */ public String getSize() { return size; } /** * Do you want crutons on that? * @org.apache.xbean.Property alias="addCroutons" */ public boolean isCrouton() { return crouton; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/ContainerBean.java0000644000175000017500000000223710512740134031056 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; public class ContainerBean { InnerBean[] beans; /** * @return the beans */ public InnerBean[] getBeans() { return beans; } /** * @param beans the beans to set */ public void setBeans(InnerBean[] beans) { this.beans = beans; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/InnerBean.java0000644000175000017500000000222310512740134030202 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; public class InnerBean { public static InnerBean INSTANCE = null; public InnerBean() { Thread.dumpStack(); if (INSTANCE == null) { INSTANCE = this; } else { throw new IllegalStateException("Already instanciated"); } } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/RecipeService.java0000644000175000017500000000303510512740134031073 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.util.List; /** * @org.apache.xbean.XBean element="recipe-service" * @author Dan Diephouse */ public class RecipeService { private List recipes; private Recipe topRecipe; /** * @org.apache.xbean.FlatCollection childElement="recipe" * @return */ public List getRecipes() { return recipes; } public void setRecipes(List recipes) { this.recipes = recipes; } /** * @org.apache.xbean.Flat * @return */ public Recipe getTopRecipe() { return topRecipe; } public void setTopRecipe(Recipe topRecipe) { this.topRecipe = topRecipe; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/QNameService.java0000644000175000017500000000256710512740134030676 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.util.List; import javax.xml.namespace.QName; /** * @org.apache.xbean.XBean element="qname-service" * @author gnodet */ public class QNameService { private QName[] services; private List list; public QName[] getServices() { return services; } public void setServices(QName[] services) { this.services = services; } public List getList() { return list; } public void setList(List list) { this.list = list; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/DummyBean.java0000644000175000017500000000235410512740134030227 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * @org.apache.xbean.XBean element="dummy" * @author gnodet * @since 2.7 */ public class DummyBean { private Object inner; /** * @return the inner */ public Object getInner() { return inner; } /** * @param inner the inner to set */ public void setInner(Object inner) { this.inner = inner; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/KegService.java0000644000175000017500000000311710512740134030373 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; //START SNIPPET: java /** * @org.apache.xbean.XBean element="keg" * * Used to verify that property PropertyEditors work correctly. * * @author chirino */ public class KegService { private long remaining; /** * Gets the amount of beer remaining in the keg (in ml) * * @param remaining */ public long getRemaining() { return remaining; } /** * Sets the amount of beer remaining in the keg (in ml) * * @org.apache.xbean.Property propertyEditor="org.apache.xbean.spring.example.MilliLittersPropertyEditor" * @param remaining */ public void setRemaining(long remaining) { this.remaining = remaining; } public long dispense( long amount ) { this.remaining -= amount; return this.remaining; } } // END SNIPPET: java xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/VodkaService.java0000644000175000017500000000330110512740134030724 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * It comes from a potatoe, it must be good. * * @org.apache.xbean.XBean element="vodka" * * @author Dan Diephouse * @version $Id: VodkaService.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 2.0 */ // START SNIPPET: bean public class VodkaService { private String id; private String name; private Class vodkaClass; public VodkaService() { } public String getId() { return id; } public String getName() { return name; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public Class getVodkaClass() { return vodkaClass; } public void setVodkaClass(Class vodkaClass) { this.vodkaClass = vodkaClass; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/RestaurantService.java0000644000175000017500000000473010635623317032030 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import javax.xml.namespace.QName; import java.net.URI; import java.util.List; import java.util.Set; /** * An owner POJO used for testing out nested properties * * @org.apache.xbean.XBean namespace="http://xbean.apache.org/schemas/pizza" element="restaurant" * description="A Restaurant thingy" * * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantService { private PizzaService favourite; private List dinnerMenu; private PizzaService[] lunchMenu; private Set snackMenu; private QName serviceName; private URI uri; /** * @org.apache.xbean.Property nestedType="org.apache.xbean.spring.example.PizzaService" */ public List getDinnerMenu() { return dinnerMenu; } public void setDinnerMenu(List dinnerMenu) { this.dinnerMenu = dinnerMenu; } public PizzaService[] getLunchMenu() { return lunchMenu; } public void setLunchMenu(PizzaService[] lunchMenu) { this.lunchMenu = lunchMenu; } public Set getSnackMenu() { return snackMenu; } public void setSnackMenu(Set snackMenu) { this.snackMenu = snackMenu; } public PizzaService getFavourite() { return favourite; } public void setFavourite(PizzaService favourite) { this.favourite = favourite; } public QName getServiceName() { return serviceName; } public void setServiceName(QName name) { this.serviceName = name; } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/WineService.java0000644000175000017500000000244610512740134030573 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * A drop of nice * * @org.apache.xbean.XBean element="wine" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class WineService { private String id; private String name; public WineService(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/MilliLittersPropertyEditor.java0000644000175000017500000000403010512740134033670 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.beans.PropertyEditorSupport; import java.util.regex.Matcher; import java.util.regex.Pattern; //START SNIPPET: java /** * * Used to verify that per property PropertyEditors work correctly. * * @author chirino */ public class MilliLittersPropertyEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { Pattern p = Pattern.compile("^(\\d+)\\s*(l(iter)?)?$", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(text); if( m.matches() ) { setValue(new Long(Long.parseLong(m.group(1))*1000)); return; } p = Pattern.compile("^(\\d+)\\s*(ml)?$", Pattern.CASE_INSENSITIVE); m = p.matcher(text); if( m.matches() ) { setValue(new Long(Long.parseLong(m.group(1)))); return; } p = Pattern.compile("^(\\d+)\\s*pints?$", Pattern.CASE_INSENSITIVE); m = p.matcher(text); if( m.matches() ) { long pints = Long.parseLong(m.group(1)); setValue(new Long( (long)(pints * 1750) )); return; } throw new IllegalArgumentException("Could convert not to long (in ml) for "+ text); } public String getAsText() { Long value = (Long) getValue(); return (value != null ? value.toString() : ""); } } //END SNIPPET: java xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/FavoriteService.java0000644000175000017500000000247010512740134031445 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.util.Map; /** * @org.apache.xbean.XBean element="favorite" * * @author Dan Diephouse * @version $Id$ */ // START SNIPPET: bean public class FavoriteService { private Map favorites; /** * @org.apache.xbean.Map entryName="favorite-item" keyName="person" * @return */ public Map getFavorites() { return favorites; } public void setFavorites(Map favorites) { this.favorites = favorites; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/FlatMapService.java0000644000175000017500000000234410575233210031213 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.util.Map; /** * @org.apache.xbean.XBean element="flat-map" * @author gnodet */ public class FlatMapService { private Map services; /** * @org.apache.xbean.Map flat="true" dups="always" keyName="id" defaultKey="others" */ public Map getServices() { return services; } public void setServices(Map services) { this.services = services; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/SocketService.java0000644000175000017500000000231311055155653031123 0ustar drazzibdrazzib/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import java.net.SocketAddress; import java.util.List; /** * @org.apache.xbean.XBean element="socketService" */ public class SocketService { private List addresses; public List getAddresses() { return addresses; } public void setAddresses(List addresses) { this.addresses = addresses; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/PizzaService.java0000644000175000017500000000407210512740134030763 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @org.apache.xbean.XBean element="pizza" * description="This is a tasty Pizza" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class PizzaService { private static final Log log = LogFactory.getLog(PizzaService.class); private String topping; private String cheese; private int size; private double price; public void makePizza() { log.info("Making a pizza with topping: " + topping + " cheese: " + cheese + " with size: " + size); } public String getCheese() { return cheese; } public void setCheese(String cheese) { this.cheese = cheese; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } /** * @org.apache.xbean.Property alias="myTopping" */ public String getTopping() { return topping; } public void setTopping(String topping) { this.topping = topping; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/GinService.java0000644000175000017500000000230310512740134030376 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * Gin is made from the distillation of white grain spirit and juniper berries. * @org.apache.xbean.XBean element="gin" contentProperty="name" * * @version $Revision: 1.1 $ */ public class GinService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/SoupService.java0000644000175000017500000000436010512740134030614 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @org.apache.xbean.XBean element="soup" * description="This is a tasty soup" * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class SoupService { private static final Log log = LogFactory.getLog(SoupService.class); /** * @org.apache.xbean.FactoryMethod */ public static SoupService newSoup(String type) { return new SoupService(type, System.currentTimeMillis()); } private final String type; private final long createTime; private boolean exists = false; private SoupService(String type, long createTime) { this.type = type; this.createTime = createTime; } /** * @org.apache.xbean.InitMethod */ public void make() { log.info("Making " + type + "soup"); exists = true; } /** * @org.apache.xbean.DestroyMethod */ public void eat() { log.info("Mummmm " + type + "soup is yummie!"); exists = false; } public boolean exists() { return exists; } /** * What type of soup would you like? */ public String getSoupType() { return type; } public long getCreateTime() { return createTime; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/BeerService.java0000644000175000017500000000277310512740134030551 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * @org.apache.xbean.XBean element="beer" description="Mmmmm beer" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class BeerService { private String id; private String name; private String source = "tap"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } } // END SNIPPET: bean xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/example/Recipe.java0000644000175000017500000000262710512740134027560 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.example; /** * @org.apache.xbean.XBean element="recipe" * @author Dan Diephouse */ public class Recipe { private String ingredients; private String instructions; public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/0000755000175000017500000000000011610661035025532 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanTest.java0000644000175000017500000000441110512740134033307 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.RestaurantService; import javax.xml.namespace.QName; import java.net.URI; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanTest extends RestaurantUsingSpringTest { private static final Log log = LogFactory.getLog(RestaurantUsingXBeanTest.class); public void testPizza() throws Exception { super.testPizza(); RestaurantService restaurant = (RestaurantService) getBean("restaurant"); QName name = restaurant.getServiceName(); assertNotNull("Name is null", name); assertEquals("Namespace URI", "http://acme.com", name.getNamespaceURI()); assertEquals("localName", "xyz", name.getLocalPart()); assertEquals("prefix", "foo", name.getPrefix()); log.info("Successfully converted the property to a QName: " + name); URI uri = restaurant.getUri(); assertNotNull("URI is null", uri); assertEquals("URI", new URI("http://cheese.com"), uri); log.info("Successfully converted the property to a URI: " + uri); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/VodkaUsingXBeanTest.java0000644000175000017500000000246110512740134032226 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id: VodkaUsingXBeanTest.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 2.0 */ public class VodkaUsingXBeanTest extends VodkaUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/vodka-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/QNameUsingXBeanTest.java0000644000175000017500000000225510512740134032164 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; public class QNameUsingXBeanTest extends QNameUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/qname-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerUsingXBeanNSTest.java0000644000175000017500000000232610512740134032300 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author Guillaume Nodet * @version $Id$ * @since 2.2 */ public class BeerUsingXBeanNSTest extends BeerUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/beer-xbean-ns.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerUsingXBeanTest.java0000644000175000017500000000232010512740134032031 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class BeerUsingXBeanTest extends BeerUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/beer-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SocketAddressSpringTest.java0000644000175000017500000000473011055155653033171 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Arrays; import java.util.List; import org.apache.xbean.spring.example.SocketService; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SocketAddressSpringTest extends SpringTestSupport { public void testSocketService() throws Exception { SocketService socketService = (SocketService) getBean("socketService"); // System.out.println(); // System.out.println("==========================="); // System.out.println(socketService.getAddresses()); // System.out.println("==========================="); // System.out.println(); List expected = Arrays.asList(new InetSocketAddress("localhost", 42), new InetSocketAddress("localhost", 42)); assertEquals(expected, socketService.getAddresses()); } public void testSocketAddress() throws Exception { SocketAddress socketAddress = (SocketAddress) getBean("socketAddress"); // System.out.println(); // System.out.println("==========================="); // System.out.println(socketAddress); // System.out.println("==========================="); // System.out.println(); assertEquals(new InetSocketAddress("localhost", 42), socketAddress); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/socket-address-normal.xml"); } }xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SocketAddressXBeanTest.java0000644000175000017500000000273411055155653032726 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.net.SocketAddress; import java.net.InetSocketAddress; import java.util.List; import java.util.Arrays; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.SoupService; import org.apache.xbean.spring.example.SocketService; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SocketAddressXBeanTest extends SocketAddressSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/socket-address.xml"); } }././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanWithSimplerConfigTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanWithSimpler0000644000175000017500000000236210512740134033722 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanWithSimplerConfigTest extends RestaurantUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/FavoriteUsingSpringTest.java0000644000175000017500000000441310575220641033212 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.util.List; import java.util.Map; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.FavoriteService; import org.apache.xbean.spring.example.GinService; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class FavoriteUsingSpringTest extends SpringTestSupport { public void testFavs() throws Exception { FavoriteService fs = (FavoriteService) getBean("favoriteService"); Map favorites = fs.getFavorites(); assertNotNull(favorites); assertEquals(3, favorites.size()); assertEquals("Grey Goose", favorites.get("Dan")); Object object = favorites.get("IndecisiveDan"); System.out.println(object.getClass()); assertTrue(object instanceof List); List l = (List) object; assertEquals(2, l.size()); object = l.get(0); System.out.println(object.getClass()); assertTrue(object instanceof String); object = l.get(1); System.out.println(object.getClass()); assertTrue(object instanceof Integer); object = favorites.get("WithInnerBean"); System.out.println(object.getClass()); assertTrue(object instanceof GinService); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/favorite-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/GinUsingSpringTest.java0000644000175000017500000000267010512740134032146 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.GinService; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class GinUsingSpringTest extends SpringTestSupport { public void testWine() throws Exception { GinService service = (GinService) getBean("ginService"); assertEquals("name", "Bombay Sapphire", service.getName()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/gin.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/KegXBeanAndPropertiesTest.java0000644000175000017500000000261310741146234033366 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.apache.xbean.spring.example.KegService; import org.springframework.context.support.AbstractXmlApplicationContext; /** * Used to verify that per Property Editors work correctly with * a PropertyPlaceholderConfigurer used to configure the values. * * @author chirino * @version $Id$ * @since 2.2 */ public class KegXBeanAndPropertiesTest extends KegXBeanTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/keg-xbean-properties.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerNullTest.java0000644000175000017500000000345510512740134030752 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.BeerService; /** * @author Dain Sundstrom * @version $Id$ * @since 2.6 */ public class BeerNullTest extends SpringTestSupport { public void testBeer() throws Exception { BeerService beer = (BeerService) getBean("beerService"); assertEquals("name", "Stella", beer.getName()); assertEquals("id", "123", beer.getId()); assertEquals("source", "tap", beer.getSource()); BeerService beer2 = (BeerService) getBean("beerService2"); assertEquals("name", "Blue Moon", beer2.getName()); assertEquals("id", "123", beer2.getId()); assertNull("source", beer2.getSource()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/beer-xbean-null.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SaladUsingSpringTest.java0000644000175000017500000000313210512740134032447 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.SaladService; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SaladUsingSpringTest extends SpringTestSupport { public void testSalad() throws Exception { SaladService salad = (SaladService) getBean("saladService"); assertEquals("dressing", "Cesar", salad.getDressing()); assertEquals("size", "Small", salad.getSize()); assertEquals("crouton", true, salad.isCrouton()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/salad-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/WineUsingSpringTest.java0000644000175000017500000000276010512740134032333 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.WineService; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class WineUsingSpringTest extends SpringTestSupport { public void testWine() throws Exception { WineService soup = (WineService) getBean("wineService"); assertEquals("name", "Amarone", soup.getName()); assertEquals("id", "wineService", soup.getId()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/wine-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/QNameUsingSpringTest.java0000644000175000017500000000352410512740134032431 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.util.List; import javax.xml.namespace.QName; import org.apache.xbean.spring.example.QNameService; import org.springframework.context.support.AbstractXmlApplicationContext; public class QNameUsingSpringTest extends SpringTestSupport { public void testQName() throws Exception { QNameService svc = (QNameService) getBean("qnameService"); QName[] services = svc.getServices(); assertNotNull(services); assertEquals(2, services.length); assertEquals(new QName("urn:foo", "test"), services[0]); assertEquals(new QName("urn:foo", "bar"), services[1]); List list = svc.getList(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(new QName("urn:foo", "list"), list.get(0)); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/qname-normal.xml"); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWithPropertiesTextNodeTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWithPropertiesTe0000644000175000017500000000233310512740134033677 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * * @version $Revision: 1.1 $ */ public class PizzaUsingXBeanWithPropertiesTextNodeTest extends PizzaUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/pizza-xbean-properties.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/WineUsingXBeanTest.java0000644000175000017500000000232010512740134032056 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class WineUsingXBeanTest extends WineUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/wine-xbean.xml"); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWinBeanRefTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWinBeanRefTest.j0000644000175000017500000000311310512740134033463 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.PizzaService; /** * * @version $Revision: 1.1 $ */ public class PizzaUsingXBeanWinBeanRefTest extends PizzaUsingSpringTest { public void testPizza() throws Exception { PizzaService pizza = (PizzaService) getBean("pizzaService"); pizza.makePizza(); assertEquals("topping", "Salami", pizza.getTopping()); assertEquals("cheese", "#Edam", pizza.getCheese()); assertEquals("size", 17, pizza.getSize()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/pizza-xbean-bean-ref.xml"); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/FavoriteUsingXBeanMixedTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/FavoriteUsingXBeanMixedTest.jav0000644000175000017500000000234611030663323033571 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class FavoriteUsingXBeanMixedTest extends FavoriteUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/favorite-xbean-mixed.xml"); } }xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BadAttributeTest.java0000644000175000017500000000246110512740134031610 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadAttributeTest extends TestCase { public void testBadNs() throws Exception { try { new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/bad-attribute.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingSpringTest.java0000644000175000017500000000311210512740134032516 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.PizzaService; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingSpringTest extends SpringTestSupport { public void testPizza() throws Exception { PizzaService pizza = (PizzaService) getBean("pizzaService"); pizza.makePizza(); assertEquals("topping", "Salami", pizza.getTopping()); assertEquals("cheese", "Edam", pizza.getCheese()); assertEquals("size", 17, pizza.getSize()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/pizza-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingSpringTest.java0000644000175000017500000000743510635623317033576 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import org.apache.xbean.spring.example.PizzaService; import org.apache.xbean.spring.example.RestaurantService; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingSpringTest extends SpringTestSupport { public void testPizza() throws Exception { RestaurantService restaurant = (RestaurantService) getBean("restaurant"); QName service = restaurant.getServiceName(); assertEquals(new QName("http://acme.com", "xyz"), service); // dinners (1-many using list) List dinners = restaurant.getDinnerMenu(); assertNotNull("dinners is null!", dinners); assertEquals("dinners size: " + dinners, 2, dinners.size()); PizzaService pizza = (PizzaService) dinners.get(0); assertEquals("topping", "Ham", pizza.getTopping()); assertEquals("cheese", "Mozzarella", pizza.getCheese()); assertEquals("size", 15, pizza.getSize()); pizza = (PizzaService) dinners.get(1); assertEquals("topping", "Eggs", pizza.getTopping()); assertEquals("cheese", "Mozzarella", pizza.getCheese()); assertEquals("size", 16, pizza.getSize()); // dinners (1-many using Set) Set snacks = restaurant.getSnackMenu(); assertNotNull("dinners is null!", snacks); assertEquals("dinners size: " + snacks, 2, snacks.size()); for (PizzaService snack : snacks) { String topping = snack.getTopping(); if ("Tofu".equals(topping)) { assertEquals("cheese", "Parmesan", snack.getCheese()); assertEquals("size", 6, snack.getSize()); } else if ("Prosciutto".equals(topping)) { assertEquals("cheese", "Blue", snack.getCheese()); assertEquals("size", 8, snack.getSize()); } else { fail("wrong topping: " + snack); } } // lunches (1-many using array) PizzaService[] lunches = restaurant.getLunchMenu(); assertNotNull("lunches is null!", lunches); assertEquals("lunches size: " + lunches, 1, lunches.length); pizza = lunches[0]; assertEquals("topping", "Chicken", pizza.getTopping()); assertEquals("cheese", "Brie", pizza.getCheese()); assertEquals("size", 17, pizza.getSize()); // favourite (1-1) pizza = restaurant.getFavourite(); assertNotNull("Pizza is null!", pizza); pizza.makePizza(); assertEquals("topping", "Salami", pizza.getTopping()); assertEquals("cheese", "Edam", pizza.getCheese()); assertEquals("size", 17, pizza.getSize()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-normal.xml"); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanAsRootTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanAsRootTest.0000644000175000017500000000230510512740134033575 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; public class RestaurantUsingXBeanAsRootTest extends RestaurantUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-xbean-root.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BadElementTest.java0000644000175000017500000000245510512740134031241 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadElementTest extends TestCase { public void testBadNs() throws Exception { try { new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/bad-element.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerUsingSpringTest.java0000644000175000017500000000274710512740134032313 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.BeerService; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class BeerUsingSpringTest extends SpringTestSupport { public void testBeer() throws Exception { BeerService soup = (BeerService) getBean("beerService"); assertEquals("name", "Stella", soup.getName()); assertEquals("id", "123", soup.getId()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/beer-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/KegXBeanTest.java0000644000175000017500000000352410512740134030663 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.apache.xbean.spring.example.KegService; import org.springframework.context.support.AbstractXmlApplicationContext; /** * Used to verify that per propety Property Editors work correctly. * * @author chirino * @version $Id$ * @since 2.2 */ public class KegXBeanTest extends SpringTestSupport { public void testBeer() throws Exception { KegService ml1000 = (KegService) getBean("ml1000"); KegService empty = (KegService) getBean("empty"); KegService pints5 = (KegService) getBean("pints5"); KegService liter20 = (KegService) getBean("liter20"); assertEquals(1000, ml1000.getRemaining()); assertEquals(0, empty.getRemaining()); assertEquals(8750, pints5.getRemaining()); assertEquals(20000, liter20.getRemaining()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/keg-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RecipeUsingXBeanMixedTest.java0000644000175000017500000000224011030653002033344 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; public class RecipeUsingXBeanMixedTest extends RecipeUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/recipe-xbean-mixed.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SpringTestSupport.java0000644000175000017500000000370610512740134032100 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.AbstractXmlApplicationContext; import junit.framework.TestCase; /** * A useful base class for testing spring based utilities. * * @author James Strachan * @version $Id$ * @since 2.0 */ public abstract class SpringTestSupport extends TestCase { protected transient Log log = LogFactory.getLog(getClass()); protected AbstractXmlApplicationContext context; protected void setUp() throws Exception { context = createApplicationContext(); assertNotNull("ApplicationContext is null!", context); } protected void tearDown() throws Exception { if (context != null) { log.info("Closing down the spring context"); context.destroy(); } } protected Object getBean(String name) { Object answer = answer = context.getBean(name); assertNotNull("Could not find object in Spring for key: " + name, answer); return answer; } protected abstract AbstractXmlApplicationContext createApplicationContext(); } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/ComponentTest.java0000644000175000017500000000344510512740134031203 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import junit.framework.TestCase; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.springframework.beans.factory.BeanFactory; import org.apache.xbean.spring.example.ContainerBean; import org.apache.xbean.spring.example.InnerBean; public class ComponentTest extends TestCase { protected void setUp() throws Exception { InnerBean.INSTANCE = null; } public void test1() { test("org/apache/xbean/spring/context/component-spring.xml"); } public void test2() { test("org/apache/xbean/spring/context/component-xbean.xml"); } protected void test(String file) { BeanFactory f = new ClassPathXmlApplicationContext(file); ContainerBean container = (ContainerBean) f.getBean("container"); assertNotNull(container); assertNotNull(container.getBeans()); assertEquals(1, container.getBeans().length); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingResourceXmlApplicationContextTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingResourceXmlAppli0000644000175000017500000000250510512740134033772 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.core.io.ClassPathResource; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingResourceXmlApplicationContextTest extends RestaurantUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ResourceXmlApplicationContext(new ClassPathResource("org/apache/xbean/spring/context/restaurant-xbean.xml")); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SoupUsingXBeanTest.java0000644000175000017500000000236010512740134032106 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class SoupUsingXBeanTest extends SoupUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/soup-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SoupUsingSpringTest.java0000644000175000017500000000412310512740134032352 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.SoupService; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SoupUsingSpringTest extends SpringTestSupport { private static final long time = System.currentTimeMillis(); public void testSoup() throws Exception { SoupService soup = (SoupService) getBean("soupService"); SoupService nestedBean = (SoupService) getBean("nestedBean"); SoupService nestedValue = (SoupService) getBean("nestedValue"); asssertValidSoup(soup); asssertValidSoup(nestedBean); asssertValidSoup(nestedValue); context.close(); assertFalse(soup.exists()); assertFalse(nestedBean.exists()); assertFalse(nestedValue.exists()); } private void asssertValidSoup(SoupService soup) { assertEquals("type", "French Onion", soup.getSoupType()); assertTrue(soup.getCreateTime() >= time); assertTrue(soup.exists()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/soup-normal.xml"); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWithJavaNamespaceTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanWithJavaNamespac0000644000175000017500000000235110512740134033603 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingXBeanWithJavaNamespaceTest extends PizzaUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/pizza-xbean-java.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SaladUsingXBeanTest.java0000644000175000017500000000236310512740134032207 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class SaladUsingXBeanTest extends SaladUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/salad-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RecipeUsingSpringTest.java0000644000175000017500000000372010512740134032635 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.util.List; import org.apache.xbean.spring.example.Recipe; import org.apache.xbean.spring.example.RecipeService; import org.springframework.context.support.AbstractXmlApplicationContext; public class RecipeUsingSpringTest extends SpringTestSupport { public void testRecipes() throws Exception { RecipeService svc = (RecipeService) getBean("recipeService"); List list = svc.getRecipes(); assertNotNull(list); assertEquals(2, list.size()); Recipe r = (Recipe) list.get(0); assertEquals("Food", r.getIngredients()); assertEquals("Mash together", r.getInstructions()); r = (Recipe) list.get(1); assertEquals("Food", r.getIngredients()); assertEquals("Mash together", r.getInstructions()); assertNotNull(svc.getTopRecipe()); assertEquals("Food", svc.getTopRecipe().getIngredients()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/recipe-normal.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BadNamespaceTest.java0000644000175000017500000000246110512740134031541 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadNamespaceTest extends TestCase { public void testBadNs() throws Exception { try { new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/bad-namespace.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RecipeUsingXBeanTest.java0000644000175000017500000000226010512740134032366 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; public class RecipeUsingXBeanTest extends RecipeUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/recipe-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/VodkaUsingSpringTest.java0000644000175000017500000000333010512740134032467 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import org.apache.xbean.spring.example.VodkaService; /** * @author Dan Diephouse * @version $Id: VodkaUsingSpringTest.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 1.0 */ public class VodkaUsingSpringTest extends SpringTestSupport { public void testWine() throws Exception { VodkaService vodka = (VodkaService) getBean("vodkaService"); assertEquals("name", "Grey Goose", vodka.getName()); assertEquals("id", "vodkaService", vodka.getId()); // Test more complex classes assertEquals("class", VodkaService.class, vodka.getClass()); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/vodka-normal.xml"); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingSpringExtendedTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingSpringExtendedTe0000644000175000017500000000241410512740134033747 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; import java.util.List; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingSpringExtendedTest extends RestaurantUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-spring-extended.xml"); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanMixedTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/RestaurantUsingXBeanMixedTest.j0000644000175000017500000000235410512740134033612 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanMixedTest extends RestaurantUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/restaurant-xbean-mixed.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/impl/0000755000175000017500000000000011610661035026473 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/impl/NamedConstructorArgsTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/impl/NamedConstructorArgsTest.j0000644000175000017500000001054010512740134033613 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context.impl; import java.io.ByteArrayInputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Properties; import junit.framework.TestCase; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class NamedConstructorArgsTest extends TestCase { private Properties properties = new Properties(); public void testPropertyParsing() { assertEquals("bar", properties.getProperty("foo")); assertEquals("blah", properties.getProperty("foo,chese")); assertEquals("StringBuffer", properties.getProperty("java.lang.String(java.lang.StringBuffer)")); assertEquals("char[]", properties.getProperty("java.lang.String([C)")); assertEquals("byte[],int,int", properties.getProperty("java.lang.String([B,int,int)")); assertEquals("URL[],ClassLoader", properties.getProperty("java.net.URLClassLoader([Ljava.net.URL;,java.lang.ClassLoader)")); } public void testMappingMetaData() throws Exception { MappingMetaData mappingMetaData = new MappingMetaData(properties); Constructor constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); assertTrue(mappingMetaData.isDefaultConstructor(constructor)); assertEquals(Arrays.asList(new String[] { "urls", "parent" }), Arrays.asList(mappingMetaData.getParameterNames(constructor))); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); assertFalse(mappingMetaData.isDefaultConstructor(constructor)); assertEquals(Arrays.asList(new String[] { "bytes", "offset", "length" }), Arrays.asList(mappingMetaData.getParameterNames(constructor))); } protected void setUp() throws Exception { StringBuffer buf = new StringBuffer(); buf.append("# test properties\n"); buf.append("foo=bar\n"); buf.append("foo,chese=blah\n"); Constructor constructor = String.class.getConstructor(new Class[] { StringBuffer.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=StringBuffer\n"); constructor = String.class.getConstructor(new Class[] { char[].class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=char[]\n"); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=byte[],int,int\n"); constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=URL[],ClassLoader\n"); properties.load(new ByteArrayInputStream(buf.toString().getBytes())); constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".default", "true"); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".parameterNames", "urls,parent"); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".default", "false"); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".parameterNames", "bytes,offset,length"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/FavoriteUsingXBeanTest.java0000644000175000017500000000233410512740134032740 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class FavoriteUsingXBeanTest extends FavoriteUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/favorite-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/PizzaUsingXBeanTest.java0000644000175000017500000000232310512740134032254 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingXBeanTest extends PizzaUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/pizza-xbean.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/FlatMapTest.java0000644000175000017500000000442610575233210030566 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import java.util.List; import org.apache.xbean.spring.example.FlatMapService; import org.apache.xbean.spring.example.KegService; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author gnodet */ public class FlatMapTest extends SpringTestSupport { public void testFlatMap() { FlatMapService fm = (FlatMapService) getBean("flat-map"); assertEquals(3, fm.getServices().size()); Object obj = fm.getServices().get("key1"); assertTrue(obj instanceof List); List l = (List) obj; assertEquals(2, l.size()); System.out.println(l.get(0).getClass()); assertTrue(l.get(0) instanceof KegService); System.out.println(l.get(1).getClass()); assertTrue(l.get(1) instanceof KegService); obj = fm.getServices().get("key2"); assertTrue(obj instanceof List); l = (List) obj; assertEquals(1, l.size()); System.out.println(l.get(0).getClass()); assertTrue(l.get(0) instanceof KegService); obj = fm.getServices().get("others"); assertTrue(obj instanceof List); l = (List) obj; assertEquals(1, l.size()); System.out.println(l.get(0).getClass()); assertTrue(l.get(0) instanceof KegService); } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/flatmap-xbean.xml"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerUsingXBeanSystemPropTest.javaxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/BeerUsingXBeanSystemPropTest.ja0000644000175000017500000000322010512740134033550 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.support.AbstractXmlApplicationContext; /** * @author Hiram Chirino * @version $Id$ * @since 2.0 */ public class BeerUsingXBeanSystemPropTest extends BeerUsingSpringTest { protected AbstractXmlApplicationContext createApplicationContext() { ClassPathXmlApplicationContext rc = new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/beer-xbean-system-prop.xml"); // // PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); // cfg.postProcessBeanFactory(rc.getBeanFactory()); // return rc; } protected void setUp() throws Exception { System.setProperty("beerType", "Stella"); super.setUp(); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/context/SpringExtensionTest.java0000644000175000017500000000242110512740134032371 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.context; import org.springframework.context.support.AbstractXmlApplicationContext; /** * * @author gnodet * @since 2.7 */ public class SpringExtensionTest extends SpringTestSupport { public void test() { } protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/xbean/spring/context/spring-extension.xml"); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/jndi/0000755000175000017500000000000011610661035024772 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/jndi/DefaultContextTest.java0000644000175000017500000000432410512740134031427 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.jndi; import javax.naming.Context; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import java.util.Hashtable; import junit.framework.TestCase; /** * @version $Revision: 657 $ */ public class DefaultContextTest extends TestCase { Context context = new DefaultContext(new Hashtable()); public void testSimpleName() throws Exception { assertContextNamed("name"); } public void testNestedName() throws Exception { assertContextNamed("jdbc/name"); } public void testDoubleNestedName() throws Exception { assertContextNamed("jdbc/foo/name"); } protected void assertContextNamed(String name) throws NamingException { context.bind(name, "James"); assertJNDILookup(name, "James"); context.rebind(name, "Rob"); assertJNDILookup(name, "Rob"); context.unbind(name); try { context.lookup(name); fail("Should ave thrown NameNotFoundException!"); } catch (NameNotFoundException e) { System.out.println("Caught expected exception: " + e); } } protected void assertJNDILookup(String name, String expected) throws NamingException { Object value = context.lookup(name); assertEquals("Lookup failed for: " + name, expected, value); } } xbean-3.7/xbean-spring/src/test/java/org/apache/xbean/spring/jndi/JndiTest.java0000644000175000017500000000543610512740134027367 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.spring.jndi; import org.springframework.beans.factory.BeanFactory; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Hashtable; import junit.framework.TestCase; public class JndiTest extends TestCase { protected InitialContext createInitialContext() throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, SpringInitialContextFactory.class.getName()); env.put(Context.PROVIDER_URL, "classpath:org/apache/xbean/spring/jndi/jndi.xml"); return new InitialContext(env); } public void testSpringJNDILookup() throws Exception { InitialContext context = createInitialContext(); assertEntryExists(context, "test"); assertEntryExists(context, "test/restaurant"); } public void testConfigureJndiInsideSpringXml() throws Exception { // lets load a spring context BeanFactory factory = new ClassPathXmlApplicationContext("org/apache/xbean/spring/jndi/spring.xml"); Object test = factory.getBean("restaurant"); assertNotNull("Should have found the test object", test); Object jndi = factory.getBean("jndi"); assertNotNull("Should have found the jndi object", jndi); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, SpringInitialContextFactory.class.getName()); InitialContext context = new InitialContext(env); assertEntryExists(context, "test"); assertEntryExists(context, "test/restaurant"); assertSame(test, context.lookup("test/restaurant")); } protected void assertEntryExists(InitialContext context, String name) throws NamingException { Object value = context.lookup(name); assertNotNull(name + " should not be null", value); } } xbean-3.7/xbean-spring/src/site/0000755000175000017500000000000011610661036016504 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/site/apt/0000755000175000017500000000000011610661036017270 5ustar drazzibdrazzibxbean-3.7/xbean-spring/src/site/site.xml0000644000175000017500000000210010473277125020173 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/pom.xml0000644000175000017500000003524611373256143013710 0ustar drazzibdrazzib 4.0.0 org.apache.geronimo.genesis genesis-java5-flava 2.0 org.apache.xbean xbean Apache XBean pom 2005 3.7 XBean is a plugin based server architecture. scm:svn:http://svn.apache.org/repos/asf/geronimo/xbean/tags/xbean-3.7 scm:svn:https://svn.apache.org/repos/asf/geronimo/xbean/tags/xbean-3.7 http://svn.apache.org/viewvc/geronimo/xbean/tags/xbean-3.7 http://geronimo.apache.org/maven/${siteId}/${version} xbean-website ${staging.siteURL}/${siteId}/${version} xbean UTF-8 jira http://issues.apache.org/jira/browse/XBEAN xbean developers mailto:xbean-dev-subscribe@geronimo.apache.org mailto:xbean-dev-unsubscribe@xbean.org xbean users mailto:xbean-user-subscribe@geronimo.apache.org mailto:xbean-user-unsubscribe@geronimo.apache.org xbean scm mailto:xbean-scm-subscribe@geronimo.apache.org mailto:xbean-scm-unsubscribe@geronimo.apache.org chirino Hiram Chirino Committer -5 dain Dain Sundstrom dain@iq80.com Committer -8 dblevins David Blevins dblevins@visi.com Committer -8 jstrachan James Strachan Committer -8 jvanzyl Jason van Zyl Committer -8 maguro Alan D. Cabrera Committer -8 gnodet Guillaume Nodet Committer +1 jlaskowski Jacek Laskowski jacek@laskowski.net.pl Committer +1 djencks David Jencks Committer -8 org.apache.xbean xbean-classloader ${version} org.apache.xbean xbean-classpath ${version} org.apache.xbean xbean-bundleutils ${version} org.apache.xbean xbean-finder ${version} org.apache.xbean xbean-naming ${version} org.apache.xbean xbean-reflect ${version} org.apache.xbean xbean-blueprint ${version} org.apache.xbean xbean-spring ${version} org.apache.xbean xbean-telnet ${version} org.apache.xbean xbean-asm-shaded ${version} org.apache.xbean xbean-finder-shaded ${version} ant ant 1.6.5 cglib cglib-nodep 2.1_2 commons-beanutils commons-beanutils 1.7.0 commons-logging commons-logging 1.0.3 groovy groovy 1.0-jsr-03 mx4j mx4j 3.0.1 org.springframework spring-beans 2.5.6 org.springframework spring-context 2.5.6 org.springframework spring-web 2.5.6 com.thoughtworks.qdox qdox 1.6.3 org.slf4j slf4j-api 1.5.11 junit junit 3.8.2 test install org.apache.maven.plugins maven-shade-plugin 1.3.1 org.apache.xbean maven-xbean-plugin ${pom.version} org.apache.felix maven-bundle-plugin 2.0.0 true ${project.url} org.apache.xbean.*;version=${pom.version} org.apache.felix maven-bundle-plugin xbean-classloader xbean-classpath xbean-bundleutils xbean-finder xbean-naming xbean-reflect xbean-blueprint xbean-spring xbean-telnet maven-xbean-plugin xbean-asm-shaded xbean-finder-shaded org.apache.maven.plugins maven-javadoc-plugin 2.5 128m 512 true true false 1.5 true http://java.sun.com/j2se/1.5.0/docs/api/ http://java.sun.com/j2se/1.4.2/docs/api/ http://java.sun.com/j2se/1.3/docs/api/ http://java.sun.com/j2ee/1.4/docs/api/ http://java.sun.com/j2ee/sdk_1.3/techdocs/api/ http://jakarta.apache.org/commons/collections/apidocs http://jakarta.apache.org/commons/logging/apidocs/ http://logging.apache.org/log4j/docs/api/ http://jakarta.apache.org/regexp/apidocs/ http://jakarta.apache.org/velocity/api/ org.apache.maven.plugins maven-pmd-plugin 2.4 1.5 org.codehaus.mojo jxr-maven-plugin org.codehaus.mojo surefire-report-maven-plugin xbean-3.7/xbean-asm-shaded/0000755000175000017500000000000011610661037015456 5ustar drazzibdrazzibxbean-3.7/xbean-asm-shaded/pom.xml0000755000175000017500000001152211373256143017003 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-asm-shaded bundle Apache XBean :: ASM shaded (repackaged) Repackaged and shaded asm jars http://asm.ow2.org/license.html http://www.apache.org/licenses/LICENSE-2.0.txt org.apache.xbean.asm;version=3.1,org.apache.xbean.asm.signature;version=3.1,org.apache.xbean.asm.commons;version=3.1,org.apache.xbean.asm.tree;version=3.1 org.apache.maven.plugins maven-shade-plugin package shade org.objectweb.asm org.apache.xbean.asm http://asm.ow2.org/license.html org.apache.xbean.asm-shaded ${xbean.osgi.export} ${xbean.osgi.export} org.apache.maven.plugins maven-antrun-plugin package run asm asm 3.1 asm asm-commons 3.1 xbean-3.7/xbean-asm-shaded/src/0000755000175000017500000000000011610661037016245 5ustar drazzibdrazzibxbean-3.7/xbean-asm-shaded/src/main/0000755000175000017500000000000011610661037017171 5ustar drazzibdrazzibxbean-3.7/xbean-asm-shaded/src/main/appended-resources/0000755000175000017500000000000011610661037022761 5ustar drazzibdrazzibxbean-3.7/xbean-asm-shaded/src/main/appended-resources/META-INF/0000755000175000017500000000000011610661037024121 5ustar drazzibdrazzibxbean-3.7/xbean-asm-shaded/src/main/appended-resources/META-INF/LICENSE.vm0000644000175000017500000000451311373033431025547 0ustar drazzibdrazzib-------------------------------------- ## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## ## $Rev$ $Date$ ## Copyright (c) 2000-2005 INRIA, France Telecom 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. Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. xbean-3.7/LICENSE0000644000175000017500000002613711251241140013361 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. xbean-3.7/xbean-naming/0000755000175000017500000000000011610661040014713 5ustar drazzibdrazzibxbean-3.7/xbean-naming/pom.xml0000644000175000017500000000307011373256143016242 0ustar drazzibdrazzib xbean org.apache.xbean 3.7 4.0.0 xbean-naming bundle Apache XBean :: Naming xbean-naming implements a flexible non-persistent jndi provider xbean-3.7/xbean-naming/src/0000755000175000017500000000000011610661040015502 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/0000755000175000017500000000000011610661040016426 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/0000755000175000017500000000000011610661040017347 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/0000755000175000017500000000000011610661040020136 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/0000755000175000017500000000000011610661040021357 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661040022454 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/0000755000175000017500000000000011610661040023725 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/global/0000755000175000017500000000000011610661040025165 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/global/GlobalContextManager.java0000644000175000017500000001020610541574201032073 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.global; import org.apache.xbean.naming.context.ContextFlyweight; import javax.naming.Context; import javax.naming.Name; import javax.naming.OperationNotSupportedException; import javax.naming.NoInitialContextException; import javax.naming.spi.InitialContextFactory; import javax.naming.spi.ObjectFactory; import java.util.Hashtable; /** * The GlobalContextManager contains the static global context object. JNDI effectively requires a single global static * to resolve the root context, and this class manages that static. This class is also an URLContextFactory and * an InitialContextFactory which returns the registered global context. * * To use this factory simply set the following system property or pass the property in the environment to new InitialContext: * * java.naming.factory.initial = org.apache.xbean.naming.global.GlobalContextManager * * @version $Rev$ $Date$ */ public class GlobalContextManager implements ObjectFactory, InitialContextFactory { private static Context DEFAULT_CONTEXT = new DefaultGlobalContext(); private static Context globalContext; /** * Gets the global context. This context is the root of all contexts and will contain entries such as "java:comp". * @return the global context */ public static synchronized Context getGlobalContext() { if (globalContext == null) return DEFAULT_CONTEXT; return globalContext; } /** * Sets the global context. To invoke this method the calling code must have "setFactory" RuntimePermission. * @param globalContext the new global context */ public static synchronized void setGlobalContext(Context globalContext) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkSetFactory(); } GlobalContextManager.globalContext = globalContext; } /** * Returns the Context registered with the GlobalManager. This method is equivalent to: * * return GlobalContextManager.getGlobalContext(); * * @param obj must be null * @param name ignored * @param nameCtx ignored * @param environment ignored * @return GlobalManager.getGlobalContext() * @throws javax.naming.OperationNotSupportedException if obj is not null */ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { if (obj == null) { return GlobalContextManager.getGlobalContext(); } else { throw new OperationNotSupportedException(); } } /** * Returns the Context registered with the GlobalManager. This method is equivalent to: * * return GlobalContextManager.getGlobalContext(); * * @param environment ignored * @return GlobalContextManager.getGlobalContext() */ public Context getInitialContext(Hashtable environment) { return GlobalContextManager.getGlobalContext(); } private static class DefaultGlobalContext extends ContextFlyweight { protected Context getContext() throws NoInitialContextException { synchronized (GlobalContextManager.class) { if (globalContext == null) throw new NoInitialContextException("Global context has not been set"); return globalContext; } } } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/0000755000175000017500000000000011610661040025411 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/VirtualSubcontext.java0000644000175000017500000000624011325725140031770 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.NamingEnumeration; import javax.naming.NameParser; import javax.naming.Binding; import javax.naming.NameClassPair; import java.util.Hashtable; /** * @version $Rev$ $Date$ */ public class VirtualSubcontext extends ContextFlyweight { private final Name nameInContext; private final Context context; public VirtualSubcontext(Name nameInContext, Context context) throws NamingException { if (context instanceof VirtualSubcontext) { VirtualSubcontext virtualSubcontext = (VirtualSubcontext) context; this.nameInContext = virtualSubcontext.getName(nameInContext); this.context = virtualSubcontext.context; } else { this.nameInContext = nameInContext; this.context = context; } } @Override protected Context getContext() throws NamingException { return context; } @Override protected Name getName(Name name) throws NamingException { return context.composeName(nameInContext, name); } @Override protected String getName(String name) throws NamingException { Name parsedName = context.getNameParser("").parse(name); return context.composeName(nameInContext, parsedName).toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VirtualSubcontext that = (VirtualSubcontext) o; if (context != null ? !context.equals(that.context) : that.context != null) return false; if (nameInContext != null ? !nameInContext.equals(that.nameInContext) : that.nameInContext != null) return false; return true; } @Override public int hashCode() { int result = nameInContext != null ? nameInContext.hashCode() : 0; result = 31 * result + (context != null ? context.hashCode() : 0); return result; } public void close() throws NamingException { context.close(); } public String getNameInNamespace() throws NamingException { Name parsedNameInNamespace = context.getNameParser("").parse(context.getNameInNamespace()); return context.composeName(parsedNameInNamespace, nameInContext).toString(); } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ImmutableContext.java0000644000175000017500000001541411205641633031553 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.OperationNotSupportedException; import org.apache.xbean.naming.reference.CachingReference; /** * * @version $Rev: 417891 $ $Date: 2006-06-28 15:45:07 -0700 (Wed, 28 Jun 2006) $ */ public class ImmutableContext extends AbstractContext { private final Map localBindings; private final Map absoluteIndex; public ImmutableContext(Map bindings) throws NamingException { this("", bindings, true); } public ImmutableContext(Map bindings, boolean cacheReferences) throws NamingException { this("", bindings, cacheReferences); } public ImmutableContext(String nameInNamespace, Map bindings, boolean cacheReferences) throws NamingException { super(nameInNamespace, ContextAccess.UNMODIFIABLE); if (cacheReferences) { bindings = CachingReference.wrapReferences(bindings, this); } Map localBindings = ContextUtil.createBindings(bindings, this); this.localBindings = Collections.unmodifiableMap(localBindings); Map globalBindings = ImmutableContext.buildAbsoluteIndex("", localBindings); this.absoluteIndex = Collections.unmodifiableMap(globalBindings); } private static Map buildAbsoluteIndex(String nameInNamespace, Map bindings) { String path = nameInNamespace; if (path.length() > 0) { path += "/"; } Map globalBindings = new HashMap(); for (Map.Entry entry : bindings.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof NestedImmutableContext) { NestedImmutableContext nestedContext = (NestedImmutableContext) value; globalBindings.putAll(ImmutableContext.buildAbsoluteIndex(nestedContext.getNameInNamespace(), nestedContext.localBindings)); } globalBindings.put(path + name, value); } return globalBindings; } protected Object getDeepBinding(String name) { return absoluteIndex.get(name); } protected Map getBindings() { return localBindings; } protected final void addDeepBinding(String name, Object value, boolean createIntermediateContexts) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final boolean addBinding(String name, Object value, boolean rebind) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final void removeDeepBinding(Name name, boolean pruneEmptyContexts) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } public boolean isNestedSubcontext(Object value) { if (value instanceof NestedImmutableContext) { NestedImmutableContext context = (NestedImmutableContext) value; return this == context.getImmutableContext(); } return false; } public Context createNestedSubcontext(String path, Map bindings) { return new NestedImmutableContext(path, bindings); } /** * Nested context which shares the absolute index map in MapContext. */ public final class NestedImmutableContext extends AbstractContext { private final Map localBindings; private final String pathWithSlash; public NestedImmutableContext(String path, Map bindings) { super(ImmutableContext.this.getNameInNamespace(path), ContextAccess.UNMODIFIABLE); path = getNameInNamespace(); if (!path.endsWith("/")) path += "/"; this.pathWithSlash = path; this.localBindings = Collections.unmodifiableMap(bindings); } protected Object getDeepBinding(String name) { String absoluteName = pathWithSlash + name; return absoluteIndex.get(absoluteName); } protected Map getBindings() { return localBindings; } protected final void addDeepBinding(String name, Object value, boolean createIntermediateContexts) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final boolean addBinding(String name, Object value, boolean rebind) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final void removeDeepBinding(Name name, boolean pruneEmptyContexts) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected final boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } public boolean isNestedSubcontext(Object value) { if (value instanceof NestedImmutableContext) { NestedImmutableContext context = (NestedImmutableContext) value; return getImmutableContext() == context.getImmutableContext(); } return false; } public Context createNestedSubcontext(String path, Map bindings) { return new NestedImmutableContext(path, bindings); } protected ImmutableContext getImmutableContext() { return ImmutableContext.this; } } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ImmutableFederatedContext.java0000644000175000017500000000721211325725140033353 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.naming.context; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.OperationNotSupportedException; /** * @version $Rev: 901481 $ $Date: 2010-01-21 02:14:08 +0100 (jeu. 21 janv. 2010) $ */ public class ImmutableFederatedContext extends AbstractFederatedContext { public ImmutableFederatedContext(String nameInNamespace, Set federatedContexts) { super(nameInNamespace, ContextAccess.UNMODIFIABLE, federatedContexts); } public void federateContext(Context context) throws NamingException { addFederatedContext(this, context); } public void unfederateContext(Context context) throws NamingException { removeFederatedContext(this, context); } @Override protected Map getWrapperBindings() throws NamingException { return Collections.emptyMap(); } public Context createNestedSubcontext(String path, Map bindings) throws NamingException { return new NestedImmutableFederatedContext(path, bindings); } /** * Nested context which shares the absolute index map in MapContext. */ public class NestedImmutableFederatedContext extends AbstractFederatedContext { private final AtomicReference> bindingsRef; private final String pathWithSlash; public NestedImmutableFederatedContext(String path, Map bindings) throws NamingException { super(ImmutableFederatedContext.this, path); path = getNameInNamespace(); if (!path.endsWith("/")) path += "/"; this.pathWithSlash = path; this.bindingsRef = new AtomicReference>(Collections.unmodifiableMap(bindings)); } public Context createNestedSubcontext(String path, Map bindings) throws NamingException { return new NestedImmutableFederatedContext(getNameInNamespace(path), bindings); } protected Object getDeepBinding(String name) { String absoluteName = pathWithSlash + name; return ImmutableFederatedContext.this.getDeepBinding(absoluteName); } protected Map getWrapperBindings() throws NamingException { return bindingsRef.get(); } protected boolean addBinding(String name, Object value, boolean rebind) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } protected boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { throw new OperationNotSupportedException("Context is immutable"); } } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ContextAccessControlList.java0000644000175000017500000000643711077673776033263 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.naming.Name; import javax.naming.NamingException; /** * @version $Rev$ $Date$ */ public class ContextAccessControlList implements ContextAccess { private final boolean defaultAllow; private final List allow; private final List deny; public ContextAccessControlList(boolean defaultAllow, List allow, List deny) { this.defaultAllow = defaultAllow; this.allow = toACL(allow); this.deny = toACL(deny); } private List toACL(List input) { if (input == null) return Collections.emptyList(); ArrayList list = new ArrayList(input.size()); for (Object value : input) { if (value instanceof Name) { list.add((Name) value); } else if (value instanceof String) { String string = (String) value; Name name; try { name = ContextUtil.NAME_PARSER.parse(string); } catch (NamingException e) { throw new IllegalArgumentException("error while parsing name: " + value); } list.add(name); } else { throw new IllegalArgumentException("name is not an instance of Name or String: " + value); } } return Collections.unmodifiableList(list); } public boolean isModifiable(Name name) { if (name == null) throw new NullPointerException("name is null"); if (defaultAllow) { // allow by default, so allow if it wasn't explicitly denied or was explicitly allowed return !isDenied(name) || isAllowed(name); } else { // deny by default, so allow if it was explicitly allowed or wasn't explicitly denied return isAllowed(name) && !isDenied(name); } } protected boolean isAllowed(Name name) { if (name == null) throw new NullPointerException("name is null"); for (Name prefix : allow) { if (name.startsWith(prefix)) { return true; } } return false; } protected boolean isDenied(Name name) { if (name == null) throw new NullPointerException("name is null"); for (Name prefix : deny) { if (name.startsWith(prefix)) { return true; } } return false; } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ContextFederation.java0000644000175000017500000001525411325725140031715 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.naming.Binding; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.NotContextException; import javax.naming.OperationNotSupportedException; /** * @version $Rev$ $Date$ */ public class ContextFederation { private final Context actualContext; private final AtomicReference> federatedContextRef = new AtomicReference>(Collections.emptySet()); public static final int MAX_WRITE_ATTEMPTS = 10; public ContextFederation(Context actualContext) { this.actualContext = actualContext; } public ContextFederation(Context actualContext, Set federatedContexts) { this.actualContext = actualContext; Set copy = new LinkedHashSet(federatedContexts); federatedContextRef.set(Collections.unmodifiableSet(copy)); } public void addContext(Context context) { Set federatedContext; Set newFederatedContext; for (int i = 0; i < MAX_WRITE_ATTEMPTS; i++) { federatedContext = getFederatedContexts(); newFederatedContext = new LinkedHashSet(federatedContext); newFederatedContext.add(context); newFederatedContext = Collections.unmodifiableSet(newFederatedContext); if (federatedContextRef.compareAndSet(federatedContext, newFederatedContext)) { return; } } throw new RuntimeException("Unable to update federatedContextRef within " + MAX_WRITE_ATTEMPTS + " attempts"); } public void removeContext(Context context) { Set federatedContext; Set newFederatedContext; for (int i = 0; i < MAX_WRITE_ATTEMPTS; i++) { federatedContext = getFederatedContexts(); newFederatedContext = new LinkedHashSet(federatedContext); newFederatedContext.remove(context); newFederatedContext = Collections.unmodifiableSet(newFederatedContext); if (federatedContextRef.compareAndSet(federatedContext, newFederatedContext)) { return; } } throw new RuntimeException("Unable to update federatedContextRef within " + MAX_WRITE_ATTEMPTS + " attempts"); } public Set getFederatedContexts() { return federatedContextRef.get(); } public Object getFederatedBinding(String name) throws NamingException { for (Context context : getFederatedContexts()) { try { Object value = context.lookup(name); if (value != null) { return value; } } catch (NamingException e) { // ignore } } return null; } public Map getFederatedBindings(String name) throws NamingException { Map bindings = new HashMap(); for (Context context : getFederatedContexts()) { // list federated context try { NamingEnumeration namingEnumeration = context.listBindings(name); // add to bindings while (namingEnumeration.hasMoreElements()) { Binding binding = (Binding) namingEnumeration.nextElement(); String bindingName = binding.getName(); // don't overwrite existing bindings if (!bindings.containsKey(bindingName)) { bindings.put(bindingName, binding.getObject()); } } } catch (NotContextException e) { //this context does not include the supplied name } } return bindings; } protected boolean addBinding(String name, Object value, boolean rebind) throws NamingException { for (Context context : getFederatedContexts()) { try { if (rebind) { context.rebind(name, value); } else { context.bind(name, value); } return true; } catch (OperationNotSupportedException ignored) { } } return false; } protected boolean removeBinding(String name) throws NamingException { for (Context context : getFederatedContexts()) { try { context.unbind(name); return true; } catch (OperationNotSupportedException ignored) { } } return false; } public Object lookup(Name name) { for (Context federatedContext : getFederatedContexts()) { try { Object value = federatedContext.lookup(name); if (value instanceof Context) { return new VirtualSubcontext(name, actualContext); } else { return value; } } catch (NamingException ignored) { } } return null; } public ContextFederation createSubcontextFederation(String subcontextName, Context actualSubcontext) throws NamingException { Name parsedSubcontextName = actualContext.getNameParser("").parse(subcontextName); ContextFederation subcontextFederation = new ContextFederation(actualSubcontext); for (Context federatedContext : getFederatedContexts()) { VirtualSubcontext virtualSubcontext = new VirtualSubcontext(parsedSubcontextName, federatedContext); subcontextFederation.addContext(virtualSubcontext); } return subcontextFederation; } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/AbstractFederatedContext.java0000644000175000017500000001674211325725140033207 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import java.util.Collections; import java.util.Map; import java.util.Set; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingException; /** * @version $Rev$ $Date$ */ public abstract class AbstractFederatedContext extends AbstractContext { private final ContextFederation contextFederation; private final AbstractFederatedContext masterContext; public AbstractFederatedContext() { this("", ContextAccess.MODIFIABLE); } public AbstractFederatedContext(String nameInNamespace) { this(nameInNamespace, ContextAccess.MODIFIABLE); } public AbstractFederatedContext(String nameInNamespace, ContextAccess contextAccess) { super(nameInNamespace, contextAccess); this.masterContext = this; this.contextFederation = new ContextFederation(this); } public AbstractFederatedContext(String nameInNamespace, ContextAccess contextAccess, Set federatedContexts) { super(nameInNamespace, contextAccess); this.masterContext = this; this.contextFederation = new ContextFederation(this, federatedContexts); } public AbstractFederatedContext(AbstractFederatedContext masterContext, String nameInNamespace) throws NamingException { super(nameInNamespace, masterContext.getContextAccess()); this.masterContext = masterContext; this.contextFederation = this.masterContext.contextFederation.createSubcontextFederation(nameInNamespace, this); } protected Object faultLookup(String stringName, Name parsedName) { Object value = contextFederation.lookup(parsedName); if (value != null) { return value; } return super.faultLookup(stringName, parsedName); } @Override protected Object getDeepBinding(String name) { try { Object value = contextFederation.getFederatedBinding(name); if (value instanceof Context) { return null; } return value; } catch (NamingException e) { return null; } } @Override protected Object getBinding(String name) throws NamingException { Object value = contextFederation.getFederatedBinding(name); if (value instanceof Context) { return createNestedSubcontext(name, getBindings(name)); } if (value == null) { value = getWrapperBindings().get(name); } return value; } protected final Map getBindings() throws NamingException { return getBindings(""); } protected final Map getBindings(String name) throws NamingException { Map bindings = contextFederation.getFederatedBindings(name); bindings.putAll(getWrapperBindings()); return bindings; } protected abstract Map getWrapperBindings() throws NamingException; protected boolean addBinding(String name, Object value, boolean rebind) throws NamingException { if (!(value instanceof Context && !isNestedSubcontext(value))) { return contextFederation.addBinding(name, value, rebind); } else if (!isNestedSubcontext(value)) { Context federatedContext = (Context) value; // if we already have a context bound at the specified value Object existingValue = getBinding(name); if (existingValue != null) { if (!(existingValue instanceof AbstractFederatedContext)) { throw new NameAlreadyBoundException(name); } AbstractFederatedContext nestedContext = (AbstractFederatedContext) existingValue; addFederatedContext(nestedContext, federatedContext); return true; } else { AbstractFederatedContext nestedContext = (AbstractFederatedContext) createNestedSubcontext(name, Collections.emptyMap()); addFederatedContext(nestedContext, federatedContext); // call back into this method using the new nested context // this gives subclasses a chance to handle the binding return addBinding(name, nestedContext, rebind); } } return false; } protected boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { return contextFederation.removeBinding(name); } protected static void addFederatedContext(AbstractFederatedContext wrappingContext, Context innerContext) throws NamingException { wrappingContext.contextFederation.addContext(innerContext); for (Map.Entry entry : wrappingContext.getWrapperBindings().entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof AbstractFederatedContext) { AbstractFederatedContext nestedContext = (AbstractFederatedContext) value; Name parsedName = wrappingContext.getNameParser().parse(name); Name nameInNamespace = wrappingContext.getNameInNamespace(parsedName); VirtualSubcontext virtualSubcontext = new VirtualSubcontext(nameInNamespace, innerContext); addFederatedContext(nestedContext, virtualSubcontext); } } } protected static void removeFederatedContext(AbstractFederatedContext wrappingContext, Context innerContext) throws NamingException { wrappingContext.contextFederation.removeContext(innerContext); for (Map.Entry entry : wrappingContext.getWrapperBindings().entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof AbstractFederatedContext) { AbstractFederatedContext nestedContext = (AbstractFederatedContext) value; Name parsedName = wrappingContext.getNameParser().parse(name); Name nameInNamespace = wrappingContext.getNameInNamespace(parsedName); VirtualSubcontext virtualSubcontext = new VirtualSubcontext(nameInNamespace, innerContext); removeFederatedContext(nestedContext, virtualSubcontext); } } } public boolean isNestedSubcontext(Object value) { if (value instanceof AbstractFederatedContext) { AbstractFederatedContext context = (AbstractFederatedContext) value; return getMasterContext() == context.getMasterContext(); } return false; } protected AbstractFederatedContext getMasterContext() { return masterContext; } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ContextAccess.java0000644000175000017500000000236710541574201031036 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Name; /** * @version $Rev$ $Date$ */ public interface ContextAccess { ContextAccess MODIFIABLE = new ContextAccess() { public boolean isModifiable(Name name) { return true; } }; ContextAccess UNMODIFIABLE = new ContextAccess() { public boolean isModifiable(Name name) { return false; } }; boolean isModifiable(Name name); } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ContextUtil.java0000644000175000017500000002473711325725140030560 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import org.apache.xbean.naming.reference.SimpleReference; import javax.naming.Binding; import javax.naming.CompoundName; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameClassPair; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.spi.NamingManager; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Properties; /** * @version $Rev$ $Date$ */ public final class ContextUtil { private ContextUtil() { } public final static NameParser NAME_PARSER = new SimpleNameParser(); public static Name parseName(String name) throws NamingException { return NAME_PARSER.parse(name); } public static Object resolve(Object value, String stringName, Name parsedName, Context nameCtx) throws NamingException { if (!(value instanceof Reference)) { return value; } Reference reference = (Reference) value; // for SimpleReference we can just call the getContext method if (reference instanceof SimpleReference) { try { return ((SimpleReference) reference).getContent(); } catch (NamingException e) { throw e; } catch (Exception e) { throw (NamingException) new NamingException("Could not look up : " + stringName == null? parsedName.toString(): stringName).initCause(e); } } // for normal References we have to do it the slow way try { if (parsedName == null) { parsedName = NAME_PARSER.parse(stringName); } return NamingManager.getObjectInstance(reference, parsedName, nameCtx, nameCtx.getEnvironment()); } catch (NamingException e) { throw e; } catch (Exception e) { throw (NamingException) new NamingException("Could not look up : " + stringName == null? parsedName.toString(): stringName).initCause(e); } } public static Map listToMap(NamingEnumeration enumeration) { Map result = new HashMap(); while (enumeration.hasMoreElements()) { NameClassPair nameClassPair = (NameClassPair) enumeration.nextElement(); String name = nameClassPair.getName(); result.put(name, nameClassPair.getClassName()); } return result; } public static Map listBindingsToMap(NamingEnumeration enumeration) { Map result = new HashMap(); while (enumeration.hasMoreElements()) { Binding binding = (Binding) enumeration.nextElement(); String name = binding.getName(); result.put(name, binding.getObject()); } return result; } public static final class ListEnumeration implements NamingEnumeration { private final Iterator iterator; public ListEnumeration(Map localBindings) { this.iterator = localBindings.entrySet().iterator(); } public boolean hasMore() { return iterator.hasNext(); } public boolean hasMoreElements() { return iterator.hasNext(); } public NameClassPair next() { return nextElement(); } public NameClassPair nextElement() { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); String className; if (value instanceof Reference) { Reference reference = (Reference) value; className = reference.getClassName(); } else { className = value.getClass().getName(); } return new NameClassPair(name, className); } public void close() { } } public static final class ListBindingEnumeration implements NamingEnumeration { private final Iterator iterator; private final Context context; public ListBindingEnumeration(Map localBindings, Context context) { this.iterator = localBindings.entrySet().iterator(); this.context = context; } public boolean hasMore() { return iterator.hasNext(); } public boolean hasMoreElements() { return iterator.hasNext(); } public Binding next() { return nextElement(); } public Binding nextElement() { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); return new ReadOnlyBinding(name, value, context); } public void close() { } } public static final class ReadOnlyBinding extends Binding { private final Object value; private final Context context; public ReadOnlyBinding(String name, Object value, Context context) { super(name, value); this.value = value; this.context = context; } public void setName(String name) { throw new UnsupportedOperationException("Context is read only"); } public String getClassName() { if (value instanceof Reference) { Reference reference = (Reference) value; return reference.getClassName(); } return value.getClass().getName(); } public void setClassName(String name) { throw new UnsupportedOperationException("Context is read only"); } public Object getObject() { try { return resolve(value, getName(), null, context); } catch (NamingException e) { throw new RuntimeException(e); } } public void setObject(Object obj) { throw new UnsupportedOperationException("Context is read only"); } public boolean isRelative() { return false; } public void setRelative(boolean r) { throw new UnsupportedOperationException("Context is read only"); } } private static final class SimpleNameParser implements NameParser { private static final Properties PARSER_PROPERTIES = new Properties(); static { PARSER_PROPERTIES.put("jndi.syntax.direction", "left_to_right"); PARSER_PROPERTIES.put("jndi.syntax.separator", "/"); } private SimpleNameParser() { } public Name parse(String name) throws NamingException { return new CompoundName(name, PARSER_PROPERTIES); } } public static Map createBindings(Map absoluteBindings, NestedContextFactory factory) throws NamingException { // create a tree of Nodes using the absolute bindings Node node = buildMapTree(absoluteBindings); // convert the node tree into a tree of context objects return ContextUtil.createBindings(null, node, factory); } private static Map createBindings(String nameInNameSpace, Node node, NestedContextFactory factory) throws NamingException { Map bindings = new HashMap(node.size()); for (Map.Entry entry : node.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); // if this is a nested node we need to create a context for the node if (value instanceof Node) { Node nestedNode = (Node) value; // recursive call create bindings to cause building the context depth first String path = nameInNameSpace == null ? name : nameInNameSpace + "/" + name; Map nestedBindings = createBindings(path, nestedNode, factory); Context nestedContext = factory.createNestedSubcontext(path, nestedBindings); bindings.put(name, nestedContext); } else { bindings.put(name, value); } } return bindings; } /** * Do nothing subclass of hashmap used to differentiate between a Map in the tree an a nested element during tree building */ public static final class Node extends HashMap { } public static Node buildMapTree(Map absoluteBindings) throws NamingException { Node rootContext = new Node(); for (Map.Entry entry : absoluteBindings.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); Node parentContext = rootContext; Name compoundName = ContextUtil.parseName(name); for (Enumeration parts = compoundName.getAll(); parts.hasMoreElements();) { String part = (String) parts.nextElement(); // the last element in the path is the name of the value if (parts.hasMoreElements()) { // nest node into parent Node bindings = (Node) parentContext.get(part); if (bindings == null) { bindings = new Node(); parentContext.put(part, bindings); } parentContext = bindings; } } parentContext.put(compoundName.get(compoundName.size() - 1), value); } return rootContext; } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/AbstractContext.java0000644000175000017500000010323711205641633031400 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.CompositeName; import javax.naming.Context; import javax.naming.InvalidNameException; import javax.naming.Name; import javax.naming.NameAlreadyBoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.NotContextException; import javax.naming.LinkRef; import javax.naming.NameNotFoundException; import javax.naming.InitialContext; import javax.naming.OperationNotSupportedException; import javax.naming.NameClassPair; import javax.naming.Binding; import java.io.Serializable; import java.util.Collections; import java.util.Hashtable; import java.util.Map; public abstract class AbstractContext implements Context, NestedContextFactory, Serializable { private static final long serialVersionUID = 6481918425692261483L; private final String nameInNamespace; private final Name parsedNameInNamespace; private final ContextAccess contextAccess; private final boolean modifiable; private final ThreadLocal inCall = new ThreadLocal(); protected AbstractContext(String nameInNamespace) { this(nameInNamespace, ContextAccess.MODIFIABLE); } public AbstractContext(String nameInNamespace, ContextAccess contextAccess) { this.nameInNamespace = nameInNamespace; try { this.parsedNameInNamespace = getNameParser().parse(nameInNamespace); } catch (NamingException e) { throw new RuntimeException(e); } this.contextAccess = contextAccess; this.modifiable = contextAccess.isModifiable(getParsedNameInNamespace()); } public void close() throws NamingException { //Ignore. Explicitly do not close the context } protected ContextAccess getContextAccess() { return contextAccess; } // // Lookup Binding // /** * Gets the object bound to the name. The name may contain slashes. * @param name the name * @return the object bound to the name, or null if not found */ protected Object getDeepBinding(String name) { return null; } /** * Gets the object bound to the name. The name will not contain slashes. * @param name the name * @return the object bound to the name, or null if not found * @throws javax.naming.NamingException on error */ protected Object getBinding(String name) throws NamingException { Map bindings = getBindings(); return bindings.get(name); } /** * Finds the specified entry. Normally there is no need to override this method; instead you should * simply implement the getDeepBindings(String) and getBindings(String) method. * * This method will follow links except for the final element which is always just returned without * inspection. This means this method can be used to implement lookupLink. * * @param stringName the string version of the name; maybe null * @param parsedName the parsed name; may be null * @return the value bound to the name * @throws NamingException if no value is bound to that name or if a problem occurs during the lookup */ protected Object lookup(String stringName, Name parsedName) throws NamingException { if (stringName == null && parsedName == null) { throw new IllegalArgumentException("Both stringName and parsedName are null"); } if (stringName == null) stringName = parsedName.toString(); // try to look up the name directly (this is the fastest path) Object directLookup = getDeepBinding(stringName); if (directLookup != null) { return ContextUtil.resolve(directLookup, stringName, parsedName, this); } // if the parsed name has no parts, they are asking for the current context if (parsedName == null) parsedName = getNameParser().parse(stringName); if (parsedName.isEmpty()) { return this; } // we didn't find an entry, pop the first element off the parsed name and attempt to // get a context from the bindings and delegate to that context Object localValue; String firstNameElement = parsedName.get(0); if (firstNameElement.length() == 0) { // the element is null... this is normally caused by looking up with a trailing '/' character localValue = this; } else { localValue = getBinding(firstNameElement); } if (localValue != null) { // if the name only had one part, we've looked up everything if (parsedName.size() == 1) { localValue = ContextUtil.resolve(localValue, stringName, parsedName, this); return localValue; } // if we have a link ref, follow it if (localValue instanceof LinkRef) { LinkRef linkRef = (LinkRef) localValue; localValue = lookup(linkRef.getLinkName()); } // we have more to lookup so we better have a context object if (!(localValue instanceof Context)) { throw new NameNotFoundException(stringName); } // delegate to the sub-context return ((Context) localValue).lookup(parsedName.getSuffix(1)); } // if we didn't find an entry, it may be an absolute name Object value = faultLookup(stringName, parsedName); if (value != null) { return value; } if (parsedName.size() > 1) { throw new NotContextException(stringName); } else { throw new NameNotFoundException(stringName); } } /** * When a value can not be found within this context, this method is called as a last ditch effort befrore * thowing a null pointer exception. * @param stringName the string version of the name; will not be null * @param parsedName the parsed name; will not be null * @return the value or null if no fault value could be found */ protected Object faultLookup(String stringName, Name parsedName) { if (!stringName.startsWith(nameInNamespace) && stringName.indexOf(':') > 0 && inCall.get() == null) { inCall.set(parsedName); try { Context ctx = new InitialContext(); return ctx.lookup(parsedName); } catch (NamingException ignored) { // thrown below } finally { inCall.set(null); } } return null; } protected Context lookupFinalContext(Name name) throws NamingException { Object value; try { value = lookup(name.getPrefix(name.size() - 1)); } catch (NamingException e) { throw new NotContextException("The intermediate context " + name.get(name.size() - 1) + " does not exist"); } if (value == null) { throw new NotContextException("The intermediate context " + name.get(name.size() - 1) + " does not exist"); } else if (!(value instanceof Context)) { throw new NotContextException("The intermediate context " + name.get(name.size() - 1) + " does is not a context"); } else { return (Context) value; } } // // List Bindings // /** * Gets a map of the bindings for the current node (i.e., no names with slashes). * This method must not return null. * * @return a Map from binding name to binding value * @throws NamingException if a problem occurs while getting the bindigns */ protected abstract Map getBindings() throws NamingException; // // Add Binding // protected void addDeepBinding(Name name, Object value, boolean rebind, boolean createIntermediateContexts) throws NamingException { if (name == null) throw new NullPointerException("name is null"); if (value == null) throw new NullPointerException("value is null"); if (name.isEmpty()) { throw new InvalidNameException("Name is empty"); } if (name.size() == 1) { addBinding(name.get(0), value, rebind); return; } if (!createIntermediateContexts) { Context context = lookupFinalContext(name); String lastSegment = name.get(name.size() - 1); addBinding(context, lastSegment, value, rebind); } else { Context currentContext = this; for (int i = 0; i < name.size(); i++) { String part = name.get(i); // empty path parts are not allowed if (part.length() == 0) { // this could be supported but it would be tricky throw new InvalidNameException("Name part " + i + " is empty: " + name); } // Is this the last element in the name? if (i == name.size() - 1) { // we're at the end... (re)bind the value into the parent context addBinding(currentContext, part, value, rebind); // all done... this is redundant but makes the code more readable break; } else { Object currentValue = getBinding(currentContext, part); if (currentValue == null) { // the next step in the tree is not present, so create everything down // and add it to the current bindings Context subcontext = createSubcontextTree(name.getPrefix(i).toString(), name.getSuffix(i), value); addBinding(currentContext, part, subcontext, rebind); // all done break; } else { // the current value must be a nested subcontext if (!(currentValue instanceof Context)) { throw new NotContextException("Expected an instance of context to be bound at " + part + " but found an instance of " + currentValue.getClass().getName()); } currentContext = (Context) currentValue; // now we recurse into the current context } } } } } /** * Gets the value bound to the specified name within the specified context. If the specified context is an * AbstractContext this method will call the faster getBinding method, otherwise it will call lookup. * * @param context the context to get the binding from * @param name the binding name * @return the bound value or null if no value was bound */ private static Object getBinding(Context context, String name) { try { if (context instanceof AbstractContext) { AbstractContext abstractContext = (AbstractContext) context; return abstractContext.getBinding(name); } else { return context.lookup(name); } } catch (NamingException e) { return null; } } /** * Binds the specified value to the specified name within the specified context. If the specified context is an * AbstractContext and is a nested subcontext, this method will call the direct addBinding method, otherwise it * will call public (re)bind method. * * @param context the context to add the binding to * @param name the binding name * @param value the value to bind * @param rebind if true, this method will replace any exsiting binding, otherwise a NamingException will be thrown * @throws NamingException if a problem occurs while (re)binding */ protected void addBinding(Context context, String name, Object value, boolean rebind) throws NamingException { if (context == this || (context instanceof AbstractContext && isNestedSubcontext(context))) { AbstractContext abstractContext = (AbstractContext) context; abstractContext.addBinding(name, value, rebind); } else { if (rebind) { context.rebind(name, value); } else { context.bind(name, value); } } } protected abstract boolean addBinding(String name, Object value, boolean rebind) throws NamingException; /** * Creates a context tree which will be rooted at the specified path and contain a single entry located down * a path specified by the name. All necessary intermediate contexts will be created using the createContext method. * @param path the path to the context that will contains this context * @param name the name under which the value should be bound * @param value the value * @return a context with the value bound at the specified name * @throws NamingException if a problem occurs while creating the subcontext tree */ protected Context createSubcontextTree(String path, Name name, Object value) throws NamingException { if (path == null) throw new NullPointerException("path is null"); if (name == null) throw new NullPointerException("name is null"); if (name.size() < 2) throw new InvalidNameException("name must have at least 2 parts " + name); if (path.length() > 0 && !path.endsWith("/")) path += "/"; for (int i = name.size() - 1; i > 0; i--) { String fullPath = path + name.getPrefix(i); String key = name.get(i); value = createNestedSubcontext(fullPath, Collections.singletonMap(key, value)); } return (Context) value; } // // Remove Binding // /** * Removes the binding from the context. The name will not contain a path and the value will not * be a nested context although it may be a foreign context. * @param name name under which the value should be bound * @param removeNotEmptyContext ??? TODO figure this out * @return whether removal was successful * @throws NamingException if a problem occurs during the bind such as a value already being bound */ protected abstract boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException; protected void removeDeepBinding(Name name, boolean pruneEmptyContexts) throws NamingException { removeDeepBinding(name, pruneEmptyContexts, false); } protected void removeDeepBinding(Name name, boolean pruneEmptyContexts, boolean removeNotEmptyContext) throws NamingException { if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new InvalidNameException("Name is empty"); } if (name.size() == 1) { removeBinding(name.get(0), removeNotEmptyContext); return; } if (!pruneEmptyContexts) { Context context = lookupFinalContext(name); context.unbind(name.getSuffix(name.size() - 1)); } else { // we serch the tree for a target context and name to remove // this is normally the last context in the tree and the final name part, but // it may be farther up the path if the intervening nodes are empty Context targetContext = this; String targetName = name.get(0); Context currentContext = this; for (int i = 0; i < name.size(); i++) { String part = name.get(i); // empty path parts are not allowed if (part.length() == 0) { throw new InvalidNameException("Name part " + i + " is empty: " + name); } // update targets if (getSize(currentContext) > 1) { targetContext = currentContext; targetName = part; } // Is this the last element in the name? if (i == name.size() - 1) { // we're at the end... unbind value unbind(targetContext, targetName, true); // all done... this is redundant but makes the code more readable break; } else { Object currentValue = getBinding(currentContext, part); if (currentValue == null) { // path not found we are done, but first prune the empty contexts if (targetContext != currentContext) { unbind(targetContext, targetName, false); } break; } else { // the current value must be a context if (!(currentValue instanceof Context)) { throw new NotContextException("Expected an instance of context to be bound at " + part + " but found an instance of " + currentValue.getClass().getName()); } currentContext = (Context) currentValue; // now we recurse into the current context } } } } } protected static boolean isEmpty(Context context) throws NamingException { if (context instanceof AbstractContext) { AbstractContext abstractContext = (AbstractContext) context; Map currentBindings = abstractContext.getBindings(); return currentBindings.isEmpty(); } else { NamingEnumeration namingEnumeration = context.list(""); return namingEnumeration.hasMore(); } } protected static int getSize(Context context) throws NamingException { if (context instanceof AbstractContext) { AbstractContext abstractContext = (AbstractContext) context; Map currentBindings = abstractContext.getBindings(); return currentBindings.size(); } else { NamingEnumeration namingEnumeration = context.list(""); int size = 0; while (namingEnumeration.hasMore()) size++; return size; } } /** * Unbinds any value bound to the specified name within the specified context. If the specified context is an * AbstractContext and is a nested context, this method will call the direct removeBinding method, otherwise it * will call public unbind. * * @param context the context to remove the binding from * @param name the binding name * @param removeNotEmptyContext ??? TODO figure this out * @throws NamingException if a problem occurs while unbinding */ private void unbind(Context context, String name, boolean removeNotEmptyContext) throws NamingException { if (context == this || (context instanceof AbstractContext && isNestedSubcontext(context))) { AbstractContext abstractContext = (AbstractContext) context; abstractContext.removeBinding(name, removeNotEmptyContext); } else { context.unbind(name); } } // // Environment // /** * Always returns a new (empty) Hashtable. * @return a new (empty) Hashtable */ public Hashtable getEnvironment() { return new Hashtable(); } public Object addToEnvironment(String propName, Object propVal) throws NamingException { if (propName == null) throw new NullPointerException("propName is null"); if (propVal == null) throw new NullPointerException("propVal is null"); Map env = getEnvironment(); return env.put(propName, propVal); } public Object removeFromEnvironment(String propName) throws NamingException { if (propName == null) throw new NullPointerException("propName is null"); Map env = getEnvironment(); return env.remove(propName); } // // Name handling // /** * Gets the name of this context withing the global namespace. This method may return null * if the location of the node in the global namespace is not known * @return the name of this context within the global namespace or null if unknown. */ public String getNameInNamespace() { return nameInNamespace; } /** * Gets the name of this context withing the global namespace. This method may return null * if the location of the node in the global namespace is not known * @return the name of this context within the global namespace or null if unknown. */ protected Name getParsedNameInNamespace() { return parsedNameInNamespace; } /** * Gets the name of a path withing the global namespace context. * @param path path to extend * @return full path in namespace */ protected String getNameInNamespace(String path) { String nameInNamespace = getNameInNamespace(); if (nameInNamespace == null || nameInNamespace.length() == 0) { return path; } else { return nameInNamespace + "/" + path; } } /** * Gets the name of a path withing the global namespace context. * @param path path to extend * @return full path in namespace * @throws javax.naming.NamingException on error */ protected Name getNameInNamespace(Name path) throws NamingException { Name nameInNamespace = getParsedNameInNamespace(); if (nameInNamespace == null || nameInNamespace.size() == 0) { return path; } else { return composeName(nameInNamespace, path); } } /** * A parser that can turn Strings into javax.naming.Name objects. * @return ContextUtil.NAME_PARSER */ protected NameParser getNameParser() { return ContextUtil.NAME_PARSER; } public NameParser getNameParser(Name name) { return getNameParser(); } public NameParser getNameParser(String name) { return getNameParser(); } public Name composeName(Name name, Name prefix) throws NamingException { if (name == null) throw new NullPointerException("name is null"); if (prefix == null) throw new NullPointerException("prefix is null"); Name result = (Name) prefix.clone(); result.addAll(name); return result; } public String composeName(String name, String prefix) throws NamingException { if (name == null) throw new NullPointerException("name is null"); if (prefix == null) throw new NullPointerException("prefix is null"); CompositeName result = new CompositeName(prefix); result.addAll(new CompositeName(name)); return result.toString(); } // // Lookup // public Object lookup(String name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); Object value = lookup(name, null); // if we got a link back we need to resolve it if (value instanceof LinkRef) { LinkRef linkRef = (LinkRef) value; value = lookup(linkRef.getLinkName()); } return value; } public Object lookup(Name name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); Object value = lookup(null, name); // if we got a link back we need to resolve it if (value instanceof LinkRef) { LinkRef linkRef = (LinkRef) value; value = lookup(linkRef.getLinkName()); } return value; } public Object lookupLink(String name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); return lookup(name, null); } public Object lookupLink(Name name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); return lookup(null, name); } // // Bind, rebind, rename and unbind // public void bind(String name, Object obj) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.length() == 0) { throw new NameAlreadyBoundException("Cannot bind to an empty name (this context)"); } bind(new CompositeName(name), obj); } public void bind(Name name, Object obj) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new NameAlreadyBoundException("Cannot bind to an empty name (this context)"); } addDeepBinding(name, obj, false, false); } public void rebind(String name, Object obj) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); rebind(new CompositeName(name), obj); } public void rebind(Name name, Object obj) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new NameAlreadyBoundException("Cannot rebind an empty name (this context)"); } addDeepBinding(name, obj, true, false); } public void rename(String oldName, String newName) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (oldName == null) throw new NullPointerException("oldName is null"); if (newName == null) throw new NullPointerException("newName is null"); rename(new CompositeName(oldName), new CompositeName(newName)); } public void rename(Name oldName, Name newName) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (oldName == null || newName == null) { throw new NullPointerException("name is null"); } else if (oldName.isEmpty() || newName.isEmpty()) { throw new NameAlreadyBoundException("Name cannot be empty"); } this.bind(newName, this.lookup(oldName)); this.unbind(oldName); } public void unbind(String name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); unbind(new CompositeName(name)); } public void unbind(Name name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new InvalidNameException("Cannot unbind empty name"); } removeDeepBinding(name, false); } // // List // protected NamingEnumeration list() throws NamingException { Map bindings = getBindings(); return new ContextUtil.ListEnumeration(bindings); } protected NamingEnumeration listBindings() throws NamingException { Map bindings = getBindings(); return new ContextUtil.ListBindingEnumeration(bindings, this); } public NamingEnumeration list(String name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); // if the name is empty, list the current context if (name.length() == 0) { return list(); } // lookup the target context Object target; try { target = lookup(name); } catch (NamingException e) { throw new NotContextException(name); } if (target == this) { return list(); } else if (target instanceof Context) { return ((Context) target).list(""); } else { throw new NotContextException("The name " + name + " cannot be listed"); } } public NamingEnumeration list(Name name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); // if the name is empty, list the current context if (name.isEmpty()) { return list(); } // lookup the target context Object target; try { target = lookup(name); } catch (NamingException e) { throw new NotContextException(name.toString()); } if (target == this) { return list(); } else if (target instanceof Context) { return ((Context) target).list(""); } else { throw new NotContextException("The name " + name + " cannot be listed"); } } public NamingEnumeration listBindings(String name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); // if the name is empty, list the current context if (name.length() == 0) { return listBindings(); } // lookup the target context Object target; try { target = lookup(name); } catch (NamingException e) { throw new NotContextException(name); } if (target == this) { return listBindings(); } else if (target instanceof Context) { return ((Context) target).listBindings(""); } else { throw new NotContextException("The name " + name + " cannot be listed"); } } public NamingEnumeration listBindings(Name name) throws NamingException { if (name == null) throw new NullPointerException("name is null"); // if the name is empty, list the current context if (name.isEmpty()) { return listBindings(); } // lookup the target context Object target; try { target = lookup(name); } catch (NamingException e) { throw new NotContextException(name.toString()); } if (target == this) { return listBindings(); } else if (target instanceof Context) { return ((Context) target).listBindings(""); } else { throw new NotContextException("The name " + name + " cannot be listed"); } } // // Subcontexts // public Context createSubcontext(String name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); return createSubcontext(new CompositeName(name)); } public Context createSubcontext(Name name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new NameAlreadyBoundException("Cannot create a subcontext if the name is empty"); } Context abstractContext = createNestedSubcontext(name.toString(), Collections.EMPTY_MAP); addDeepBinding(name, abstractContext, false, false); return abstractContext; } public void destroySubcontext(String name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); destroySubcontext(new CompositeName(name)); } public void destroySubcontext(Name name) throws NamingException { if (!modifiable) throw new OperationNotSupportedException("Context is read only"); if (name == null) throw new NullPointerException("name is null"); if (name.isEmpty()) { throw new InvalidNameException("Cannot destroy subcontext with empty name"); } unbind(name); } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/WritableContext.java0000644000175000017500000002731011207141417031400 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Hashtable; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.naming.Context; import javax.naming.ContextNotEmptyException; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingException; import javax.naming.Referenceable; import javax.naming.Reference; import javax.naming.spi.NamingManager; import org.apache.xbean.naming.reference.CachingReference; /** * @version $Rev$ $Date$ */ public class WritableContext extends AbstractFederatedContext { private final Lock writeLock = new ReentrantLock(); private final AtomicReference> bindingsRef; private final AtomicReference> indexRef; private final boolean cacheReferences; private final boolean supportReferenceable; private final boolean checkDereferenceDifferent; private final boolean assumeDereferenceBound; public WritableContext() throws NamingException { this("", Collections.emptyMap(), ContextAccess.MODIFIABLE, false); } public WritableContext(String nameInNamespace) throws NamingException { this(nameInNamespace, Collections.emptyMap(), ContextAccess.MODIFIABLE, false); } public WritableContext(String nameInNamespace, Map bindings) throws NamingException { this(nameInNamespace, bindings, ContextAccess.MODIFIABLE, false); } public WritableContext(String nameInNamespace, Map bindings, boolean cacheReferences) throws NamingException { this(nameInNamespace, bindings, ContextAccess.MODIFIABLE, cacheReferences); } public WritableContext(String nameInNamespace, Map bindings, ContextAccess contextAccess) throws NamingException { this(nameInNamespace, bindings, contextAccess, false); } public WritableContext(String nameInNamespace, Map bindings, ContextAccess contextAccess, boolean cacheReferences) throws NamingException { this(nameInNamespace, bindings, contextAccess, cacheReferences, true, true, false); } public WritableContext(String nameInNamespace, Map bindings, ContextAccess contextAccess, boolean cacheReferences, boolean supportReferenceable, boolean checkDereferenceDifferent, boolean assumeDereferenceBound) throws NamingException { super(nameInNamespace, contextAccess); this.cacheReferences = cacheReferences; if (this.cacheReferences) { bindings = CachingReference.wrapReferences(bindings, this); } this.supportReferenceable = supportReferenceable; this.checkDereferenceDifferent = checkDereferenceDifferent; this.assumeDereferenceBound = assumeDereferenceBound; Map localBindings = ContextUtil.createBindings(bindings, this); this.bindingsRef = new AtomicReference>(Collections.unmodifiableMap(localBindings)); this.indexRef = new AtomicReference>(Collections.unmodifiableMap(buildIndex("", localBindings))); } protected boolean addBinding(String name, Object value, boolean rebind) throws NamingException { if (super.addBinding(name, value, rebind)) { return true; } addBinding(bindingsRef, name, getNameInNamespace(name), value, rebind); return true; } protected void addBinding(AtomicReference> bindingsRef, String name, String nameInNamespace, Object value, boolean rebind) throws NamingException { if (supportReferenceable && value instanceof Referenceable) { Reference ref = ((Referenceable)value).getReference(); if (ref != null) { if (checkDereferenceDifferent) { try { Object o = NamingManager.getObjectInstance(ref, null, null, new Hashtable()); if (!value.equals(o)) { value = ref; } } catch (Exception e) { if (!assumeDereferenceBound) { value = ref; } } } else { value = ref; } } } if (cacheReferences) { value = CachingReference.wrapReference(name, value, this); } writeLock.lock(); try { Map bindings = bindingsRef.get(); if (!rebind && bindings.containsKey(name)) { throw new NameAlreadyBoundException(name); } Map newBindings = new HashMap(bindings); newBindings.put(name,value); bindingsRef.set(newBindings); addToIndex(nameInNamespace, value); } finally { writeLock.unlock(); } } private void addToIndex(String name, Object value) { Map index = indexRef.get(); Map newIndex = new HashMap(index); newIndex.put(name, value); if (value instanceof NestedWritableContext) { NestedWritableContext nestedcontext = (NestedWritableContext) value; Map newIndexValues = buildIndex(name, nestedcontext.bindingsRef.get()); newIndex.putAll(newIndexValues); } indexRef.set(newIndex); } protected boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { if (super.removeBinding(name, removeNotEmptyContext)) { return true; } removeBinding(bindingsRef, name, getNameInNamespace(name), removeNotEmptyContext); return true; } private boolean removeBinding(AtomicReference> bindingsRef, String name, String nameInNamespace, boolean removeNotEmptyContext) throws NamingException { writeLock.lock(); try { Map bindings = bindingsRef.get(); if (!bindings.containsKey(name)) { // remove is idempotent meaning remove succeededs even if there was no value bound return false; } Map newBindings = new HashMap(bindings); Object oldValue = newBindings.remove(name); if (!removeNotEmptyContext && oldValue instanceof Context && !isEmpty((Context)oldValue)) { throw new ContextNotEmptyException(name); } bindingsRef.set(newBindings); Map newIndex = removeFromIndex(nameInNamespace); indexRef.set(newIndex); return true; } finally { writeLock.unlock(); } } private Map removeFromIndex(String name) { Map index = indexRef.get(); Map newIndex = new HashMap(index); Object oldValue = newIndex.remove(name); if (oldValue instanceof NestedWritableContext) { NestedWritableContext nestedcontext = (NestedWritableContext) oldValue; Map removedIndexValues = buildIndex(name, nestedcontext.bindingsRef.get()); for (String key : removedIndexValues.keySet()) { newIndex.remove(key); } } return newIndex; } public Context createNestedSubcontext(String path, Map bindings) throws NamingException { if (getNameInNamespace().length() > 0) { path = getNameInNamespace() + "/" + path; } return new NestedWritableContext(path, bindings); } private static Map buildIndex(String nameInNamespace, Map bindings) { String path = nameInNamespace; if (path.length() > 0 && !path.endsWith("/")) { path += "/"; } Map absoluteIndex = new HashMap(); for (Map.Entry entry : bindings.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof NestedWritableContext) { NestedWritableContext nestedContext = (NestedWritableContext) value; absoluteIndex.putAll(buildIndex(nestedContext.pathWithSlash, nestedContext.bindingsRef.get())); } absoluteIndex.put(path + name, value); } return absoluteIndex; } protected Object getDeepBinding(String name) { Map index = indexRef.get(); return index.get(name); } protected Map getWrapperBindings() throws NamingException { return bindingsRef.get(); } /** * Nested context which shares the absolute index map in MapContext. */ public class NestedWritableContext extends AbstractFederatedContext { private final AtomicReference> bindingsRef; private final String pathWithSlash; public NestedWritableContext(String path, Map bindings) throws NamingException { super(WritableContext.this, path); path = getNameInNamespace(); if (!path.endsWith("/")) path += "/"; this.pathWithSlash = path; this.bindingsRef = new AtomicReference>(Collections.unmodifiableMap(bindings)); } public Context createNestedSubcontext(String path, Map bindings) throws NamingException { return new NestedWritableContext(getNameInNamespace(path), bindings); } protected Object getDeepBinding(String name) { String absoluteName = pathWithSlash + name; return WritableContext.this.getDeepBinding(absoluteName); } protected Map getWrapperBindings() throws NamingException { return bindingsRef.get(); } protected boolean addBinding(String name, Object value, boolean rebind) throws NamingException { if (super.addBinding(name, value, rebind)) { return true; } WritableContext.this.addBinding(bindingsRef, name, getNameInNamespace(name), value, rebind); return true; } protected boolean removeBinding(String name, boolean removeNotEmptyContext) throws NamingException { if (WritableContext.this.removeBinding(bindingsRef, name, getNameInNamespace(name), removeNotEmptyContext)) { return true; } return super.removeBinding(name, false); } } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/NestedContextFactory.java0000644000175000017500000000323111077673776032424 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.NamingException; import java.util.Map; /** * @version $Rev$ $Date$ */ public interface NestedContextFactory { /** * Is the specified value an instance of a nested context * @param value the value to inspect * @return true if the specified value an instance of a nested context; false otherwise */ boolean isNestedSubcontext(Object value); /** * Creates a nested subcontext instance. This does not cause the nested context to be bound. * @param path the path to the new nested context * @param bindings the initial bindings for the context * @return the new nested context * @throws javax.naming.NamingException on error */ Context createNestedSubcontext(String path, Map bindings) throws NamingException; } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/context/ContextFlyweight.java0000644000175000017500000001223611325725140031574 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.NamingEnumeration; import javax.naming.NameParser; import javax.naming.NameClassPair; import javax.naming.Binding; import java.util.Hashtable; /** * @version $Rev$ $Date$ */ public abstract class ContextFlyweight implements Context { protected abstract Context getContext() throws NamingException; protected Name getName(Name name) throws NamingException { return name; } protected String getName(String name) throws NamingException { return name; } public void close() throws NamingException { } public String getNameInNamespace() throws NamingException { return getContext().getNameInNamespace(); } public Object lookup(Name name) throws NamingException { return getContext().lookup(getName(name)); } public Object lookup(String name) throws NamingException { return getContext().lookup(getName(name)); } public void bind(Name name, Object obj) throws NamingException { getContext().bind(getName(name), obj); } public void bind(String name, Object obj) throws NamingException { getContext().bind(getName(name), obj); } public void rebind(Name name, Object obj) throws NamingException { getContext().rebind(getName(name), obj); } public void rebind(String name, Object obj) throws NamingException { getContext().rebind(getName(name), obj); } public void unbind(Name name) throws NamingException { getContext().unbind(getName(name)); } public void unbind(String name) throws NamingException { getContext().unbind(getName(name)); } public void rename(Name oldName, Name newName) throws NamingException { getContext().rename(getName(oldName), getName(newName)); } public void rename(String oldName, String newName) throws NamingException { getContext().rename(getName(oldName), getName(newName)); } public NamingEnumeration list(Name name) throws NamingException { return getContext().list(getName(name)); } public NamingEnumeration list(String name) throws NamingException { return getContext().list(getName(name)); } public NamingEnumeration listBindings(Name name) throws NamingException { return getContext().listBindings(getName(name)); } public NamingEnumeration listBindings(String name) throws NamingException { return getContext().listBindings(getName(name)); } public void destroySubcontext(Name name) throws NamingException { getContext().destroySubcontext(getName(name)); } public void destroySubcontext(String name) throws NamingException { getContext().destroySubcontext(getName(name)); } public Context createSubcontext(Name name) throws NamingException { return getContext().createSubcontext(getName(name)); } public Context createSubcontext(String name) throws NamingException { return getContext().createSubcontext(getName(name)); } public Object lookupLink(Name name) throws NamingException { return getContext().lookupLink(getName(name)); } public Object lookupLink(String name) throws NamingException { return getContext().lookupLink(getName(name)); } public NameParser getNameParser(Name name) throws NamingException { return getContext().getNameParser(getName(name)); } public NameParser getNameParser(String name) throws NamingException { return getContext().getNameParser(getName(name)); } public Name composeName(Name name, Name prefix) throws NamingException { return getContext().composeName(name, prefix); } public String composeName(String name, String prefix) throws NamingException { return getContext().composeName(name, prefix); } public Object addToEnvironment(String propName, Object propVal) throws NamingException { return getContext().addToEnvironment(propName, propVal); } public Object removeFromEnvironment(String propName) throws NamingException { return getContext().removeFromEnvironment(propName); } public Hashtable getEnvironment() throws NamingException { return getContext().getEnvironment(); } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/java/0000755000175000017500000000000011610661040024646 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/java/javaURLContextFactory.java0000644000175000017500000000226311325725140031722 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.java; import org.apache.xbean.naming.global.GlobalContextManager; /** * URLContextFactory for the java: namespace. * * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class javaURLContextFactory extends GlobalContextManager { public javaURLContextFactory() { System.out.println(getClass().getName()); } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/reference/0000755000175000017500000000000011610661040025663 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/reference/CachingReference.java0000644000175000017500000000547111205641633031716 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.reference; import java.util.LinkedHashMap; import java.util.Map; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Context; import org.apache.xbean.naming.context.ContextUtil; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class CachingReference extends SimpleReference { public static Object wrapReference(String fullName, Object value, Context context) { if (value instanceof Reference && !(value instanceof CachingReference)) { return new CachingReference(fullName, (Reference)value, context); } return value; } public static Map wrapReferences(Map bindings, Context context) { LinkedHashMap newBindings = new LinkedHashMap(bindings); for (Map.Entry entry : bindings.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof Reference && !(value instanceof CachingReference)) { newBindings.put(name, new CachingReference(name, (Reference) value, context)); } } return newBindings; } private final Object lock = new Object(); private final String stringName; private final Context context; private final Reference reference; private final String className; private Object value; public CachingReference(String fullName, Reference reference, Context context) { this.stringName = fullName; this.reference = reference; className = reference.getClassName(); this.context = context; } public Object getContent() throws NamingException { synchronized(lock) { if (value == null) { value = ContextUtil.resolve(reference, stringName, null, context); } return value; } } public String getClassName() { return className; } } xbean-3.7/xbean-naming/src/main/java/org/apache/xbean/naming/reference/SimpleReference.java0000644000175000017500000001050511077673776031631 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.reference; import java.util.Enumeration; import java.util.Hashtable; import java.util.NoSuchElementException; import javax.naming.Context; import javax.naming.Name; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.NamingException; import javax.naming.spi.ObjectFactory; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public abstract class SimpleReference extends Reference { private static final Enumeration EMPTY_ENUMERATION = new Enumeration() { public boolean hasMoreElements() { return false; } public RefAddr nextElement() { throw new NoSuchElementException(); } }; public SimpleReference() { super(null); } /** * Gets the actual referenced Object. * @return the referenced object * @throws javax.naming.NamingException on error */ public abstract Object getContent() throws NamingException; /** * We will atleast return an Object. Subclasses may want to provide a more specific class. * @return "java.lang.Object" */ public String getClassName() { return "java.lang.Object"; } /** * If the JNDI context does not understand simple references, this method will be called * to obtain the class name of a factory. This factory in turn understands the simple * reference. This style is much slower because JNDI will use reflection to load and * create this class. * @return factory class name */ public final String getFactoryClassName() { return SimpleObjectFactory.class.getName(); } // // Disabled methods that we no longer need // public final String getFactoryClassLocation() { return null; } public final RefAddr get(String addrType) { return null; } public final RefAddr get(int posn) { throw new ArrayIndexOutOfBoundsException(posn); } public final Enumeration getAll() { return EMPTY_ENUMERATION; } public final int size() { return 0; } public final void add(RefAddr addr) { throw new UnsupportedOperationException("SimpleReference has no addresses so none can be added"); } public final void add(int posn, RefAddr addr) { throw new UnsupportedOperationException("SimpleReference has no addresses so none can be added"); } public final Object remove(int posn) { throw new ArrayIndexOutOfBoundsException(posn); } public final void clear() { } // // Reset the java.lang.Object methods back to default implementations // public boolean equals(Object obj) { return this == obj; } public int hashCode() { return System.identityHashCode(this); } public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } public Object clone() { throw new UnsupportedOperationException("SimpleReference can not be cloned"); } /** * Simply calls getContent() on the SimpleReference */ public static final class SimpleObjectFactory implements ObjectFactory { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { if (obj instanceof SimpleReference) { SimpleReference reference = (SimpleReference) obj; return reference.getContent(); } return null; } } } xbean-3.7/xbean-naming/src/test-data/0000755000175000017500000000000011610661040017370 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/0000755000175000017500000000000011610661040016461 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/0000755000175000017500000000000011610661040017402 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/0000755000175000017500000000000011610661040020171 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/0000755000175000017500000000000011610661040021412 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661040022507 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/0000755000175000017500000000000011610661040023760 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/global/0000755000175000017500000000000011610661040025220 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/global/GlobalContextManagerTest.java0000644000175000017500000000710110541574201032766 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.global; import org.apache.xbean.naming.context.AbstractContextTest; import org.apache.xbean.naming.context.ImmutableContext; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NoInitialContextException; import java.util.Hashtable; import java.util.Map; import java.util.HashMap; /** * @version $Rev$ $Date$ */ public class GlobalContextManagerTest extends AbstractContextTest { public void testNoGlobalContextSet() throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, GlobalContextManager.class.getName()); try { InitialContext initialContext = new InitialContext(env); initialContext.lookup(""); fail("expected a NoInitialContextException"); } catch (NoInitialContextException expected) { } } public void testDefaultInitialContext() throws Exception { Map bindings = new HashMap(); bindings.put("string", "foo"); bindings.put("nested/context/string", "bar"); bindings.put("a/b/c/d/e/string", "beer"); bindings.put("a/b/c/d/e/one", new Integer(1)); bindings.put("a/b/c/d/e/two", new Integer(2)); bindings.put("a/b/c/d/e/three", new Integer(3)); bindings.put("java:comp/env/foo", new Integer(42)); bindings.put("foo:bar/baz", "caz"); ImmutableContext immutableContext = new ImmutableContext(bindings); assertEq(bindings, immutableContext); GlobalContextManager.setGlobalContext(immutableContext); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, GlobalContextManager.class.getName()); InitialContext initialContext = new InitialContext(env); assertEq(bindings, initialContext); } public void testPackageDir() throws Exception { Map bindings = new HashMap(); bindings.put("java:comp/string", "foo"); bindings.put("java:comp/nested/context/string", "bar"); bindings.put("java:comp/a/b/c/d/e/string", "beer"); bindings.put("java:comp/a/b/c/d/e/one", new Integer(1)); bindings.put("java:comp/a/b/c/d/e/two", new Integer(2)); bindings.put("java:comp/a/b/c/d/e/three", new Integer(3)); bindings.put("java:comp/env/foo", new Integer(42)); bindings.put("java:comp/baz", "caz"); ImmutableContext immutableContext = new ImmutableContext(bindings); assertEq(bindings, immutableContext); GlobalContextManager.setGlobalContext(immutableContext); Hashtable env = new Hashtable(); env.put(Context.URL_PKG_PREFIXES, "org.apache.xbean.naming"); Context ctx = (Context) new InitialContext(env).lookup("java:comp"); assertEq(bindings, "java:comp", ctx); } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/referenceable/0000755000175000017500000000000011610661040026542 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/referenceable/Foo.java0000644000175000017500000000361111204576131030136 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.naming.referenceable; import javax.naming.Referenceable; import javax.naming.Reference; import javax.naming.NamingException; import javax.naming.StringRefAddr; /** * @version $Rev: 776407 $ $Date: 2009-05-19 20:37:13 +0200 (mar. 19 mai 2009) $ */ public class Foo implements Referenceable { private final String value; public Foo(String value) { this.value = value; } public String getValue() { return value; } public Reference getReference() throws NamingException { return new Reference(Foo.class.getName(), new StringRefAddr("value", value), FooFactory.class.getName(), null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Foo foo = (Foo) o; if (value != null ? !value.equals(foo.value) : foo.value != null) return false; return true; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/referenceable/FooFactory.java0000644000175000017500000000377311204576131031477 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.naming.referenceable; import java.util.Hashtable; import javax.naming.spi.ObjectFactory; import javax.naming.Referenceable; import javax.naming.Reference; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.Context; import javax.naming.RefAddr; /** * @version $Rev: 776407 $ $Date: 2009-05-19 20:37:13 +0200 (mar. 19 mai 2009) $ */ public class FooFactory implements Referenceable, ObjectFactory { private Foo foo; public FooFactory() { } public FooFactory(Foo foo) { this.foo = foo; } public Foo getFoo() { return foo; } public void setFoo(Foo foo) { this.foo = foo; } public Reference getReference() throws NamingException { return foo.getReference(); } public Object getObjectInstance(Object o, Name name, Context context, Hashtable hashtable) throws Exception { if (o instanceof Reference) { Reference ref = (Reference) o; if (Foo.class.getName().equals(ref.getClassName())) { RefAddr addr = ref.get("value"); return new Foo((String) addr.getContent()); } } return null; } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/0000755000175000017500000000000011610661040025444 5ustar drazzibdrazzibxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ReferenceableTest.java0000644000175000017500000000354511205103677031707 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.naming.context; import javax.naming.Context; import org.apache.xbean.naming.referenceable.Foo; import org.apache.xbean.naming.referenceable.FooFactory; /** * @version $Rev: 776890 $ $Date: 2009-05-21 00:44:15 +0200 (jeu. 21 mai 2009) $ */ public class ReferenceableTest extends AbstractContextTest { public void testReferenceable() throws Exception { Context context = new WritableContext(); context.createSubcontext("bar"); Foo foo1 = new Foo("foo1"); context.bind("bar/foo1", foo1); Object o1 = context.lookup("bar/foo1"); assertEquals(foo1, o1); // assertNotSame(foo1, o1); } public void testReferenceable2() throws Exception { Context context = new WritableContext(); context.createSubcontext("bar"); Foo foo1 = new Foo("foo1"); FooFactory fooFactory1 = new FooFactory(foo1); context.bind("bar/foo1", fooFactory1); Object o1 = context.lookup("bar/foo1"); assertEquals(foo1, o1); assertNotSame(foo1, o1); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ImmutableFederatedContextTest.javaxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ImmutableFederatedContextTest.j0000644000175000017500000000634211325725140033561 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.naming.context; import junit.framework.TestCase; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; /** * @version $Rev: 901481 $ $Date: 2010-01-21 02:14:08 +0100 (jeu. 21 janv. 2010) $ */ public class ImmutableFederatedContextTest extends TestCase { public void testJavaContextFederation() throws Exception { Context comp = new ImmutableContext(Collections.singletonMap("comp/env/foo", "foo")); Context module = new ImmutableContext(Collections.singletonMap("module/env/bar", "bar")); Context application = new ImmutableContext(Collections.singletonMap("application/env/baz", "baz")); Context global1 = new ImmutableContext(Collections.singletonMap("global/env/foo1", "foo1")); Context global2 = new ImmutableContext(Collections.singletonMap("global/env/foo2", "foo2")); Set globals = new LinkedHashSet(); ImmutableFederatedContext global = new ImmutableFederatedContext("", globals); Set locals = new LinkedHashSet(); locals.add(comp); locals.add(module); locals.add(application); locals.add(global); ImmutableFederatedContext w = new ImmutableFederatedContext("", locals); assertEquals("foo", w.lookup("comp/env/foo")); assertEquals("bar", w.lookup("module/env/bar")); assertEquals("baz", w.lookup("application/env/baz")); try { w.lookup("global/env/foo1"); fail("foo1 not yet bound"); } catch (NamingException e) { } global.federateContext(global1); assertEquals("foo1", w.lookup("global/env/foo1")); try { w.lookup("global/env/foo2"); fail("foo2 not yet bound"); } catch (NamingException e) { } global.federateContext(global2); assertEquals("foo2", w.lookup("global/env/foo2")); Context c = (Context) w.lookup("global"); assertEquals("foo1", c.lookup("env/foo1")); assertEquals("foo2", c.lookup("env/foo2")); global.unfederateContext(global2); try { w.lookup("global/env/foo2"); fail("foo2 not yet bound"); } catch (NamingException e) { } } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/FederationTest.java0000644000175000017500000003551610541574201031245 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.NameAlreadyBoundException; import java.util.Map; import java.util.HashMap; import java.util.Iterator; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class FederationTest extends AbstractContextTest { private Context rootContext; private MutableContext unmodifibleContext; private Context writableContext; private Map rootBindings; private Map unmodifibleBindings; private Map writableBindings; private final class MutableContext extends WritableContext { public MutableContext(Map bindings) throws NamingException { super("", bindings, ContextAccess.UNMODIFIABLE); } public void addDeepBinding(Name name, Object value, boolean rebind, boolean createIntermediateContexts) throws NamingException { super.addDeepBinding(name, value, rebind, createIntermediateContexts); } protected void removeDeepBinding(Name name, boolean pruneEmptyContexts) throws NamingException { super.removeDeepBinding(name, pruneEmptyContexts); } } public void setUp() throws Exception { super.setUp(); rootBindings = new HashMap(); rootBindings.put("string", "blah"); rootBindings.put("nested/context/string", "blah"); rootBindings.put("java:comp/env/string", "blah"); rootBindings.put("java:comp/env/one", new Integer(1)); rootBindings.put("java:comp/env/two", new Integer(2)); rootBindings.put("java:comp/env/three", new Integer(3)); rootContext = new WritableContext(); FederationTest.bind(rootContext, rootBindings); assertEq(rootBindings, rootContext); unmodifibleBindings = new HashMap(); unmodifibleBindings.put("string", "blah"); unmodifibleBindings.put("one", new Integer(1)); unmodifibleBindings.put("two", new Integer(2)); unmodifibleBindings.put("three", new Integer(3)); unmodifibleContext = new MutableContext(unmodifibleBindings); assertEq(unmodifibleBindings, unmodifibleContext); rootContext.bind("java:comp/unmodifible", unmodifibleContext); putAllBindings(rootBindings, "java:comp/unmodifible", unmodifibleBindings); writableBindings = new HashMap(); writableBindings.put("string", "blah"); writableBindings.put("one", new Integer(1)); writableBindings.put("two", new Integer(2)); writableBindings.put("three", new Integer(3)); writableContext = new WritableContext("", writableBindings); assertEq(writableBindings, writableContext); rootContext.bind("java:comp/writable", writableContext); putAllBindings(rootBindings, "java:comp/writable", writableBindings); } public void testBasic() throws Exception { assertEq(rootBindings, rootContext); } public void testMutability() throws Exception { assertModifiable(rootContext); assertUnmodifiable(unmodifibleContext); assertModifiable(writableContext); assertModifiable(lookupSubcontext(rootContext, "java:comp/unmodifible")); assertModifiable(lookupSubcontext(rootContext, "java:comp/writable")); } public void testBindDirect() throws Exception { // // bind directly into the unmodifible context unmodifibleContext.addDeepBinding(parse("DIRECT"), "DIRECT_VALUE", false, true); // visible from root context rootBindings.put("java:comp/unmodifible/DIRECT", "DIRECT_VALUE"); assertEq(rootBindings, rootContext); // visible from unmodifibleContext unmodifibleBindings.put("DIRECT", "DIRECT_VALUE"); assertEq(unmodifibleBindings, unmodifibleContext); } public void testBindWrapper() throws Exception { // // bind over the top of a value in the subcontext rootContext.rebind("java:comp/unmodifible/three", "three"); // visible from root context rootBindings.put("java:comp/unmodifible/three", "three"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); // // bind into root context OVER the unmodifible context rootContext.bind("java:comp/unmodifible/TEST", "TEST_VALUE"); // visible from root context rootBindings.put("java:comp/unmodifible/TEST", "TEST_VALUE"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); } public void testBindInner() throws Exception { // bind into root context OVER the writable context rootContext.bind("java:comp/writable/TEST", "TEST_VALUE"); // visible from root context rootBindings.put("java:comp/writable/TEST", "TEST_VALUE"); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.put("TEST", "TEST_VALUE"); assertEq(writableBindings, writableContext); } public void testRebindDirect() throws Exception { // // bind directly into the unmodifible context unmodifibleContext.addDeepBinding(parse("DIRECT"), "DIRECT_VALUE", true, true); // visible from root context rootBindings.put("java:comp/unmodifible/DIRECT", "DIRECT_VALUE"); assertEq(rootBindings, rootContext); // visible from unmodifibleContext unmodifibleBindings.put("DIRECT", "DIRECT_VALUE"); assertEq(unmodifibleBindings, unmodifibleContext); // // bind over the top of a value in the subcontext unmodifibleContext.addDeepBinding(parse("three"), "three", true, true); // visible from root context rootBindings.put("java:comp/unmodifible/three", "three"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext unmodifibleBindings.put("three", "three"); assertEq(unmodifibleBindings, unmodifibleContext); } public void testRebindWrapper() throws Exception { // // bind into root context OVER the unmodifible context rootContext.rebind("java:comp/unmodifible/TEST", "TEST_VALUE"); // visible from root context rootBindings.put("java:comp/unmodifible/TEST", "TEST_VALUE"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); // // bind into root context OVER the unmodifible context rootContext.rebind("java:comp/unmodifible/TEST", "NEW_TEST_VALUE"); // visible from root context rootBindings.put("java:comp/unmodifible/TEST", "NEW_TEST_VALUE"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); // // bind over the top of a value in the subcontext rootContext.rebind("java:comp/unmodifible/three", "three"); // visible from root context rootBindings.put("java:comp/unmodifible/three", "three"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); rootContext.rebind("java:comp/unmodifible/three", "thirty-three"); // visible from root context rootBindings.put("java:comp/unmodifible/three", "thirty-three"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); } public void testRebindInner() throws Exception { // // rebind new name into writable context rootContext.rebind("java:comp/writable/three", "three"); // visible from root context rootBindings.put("java:comp/writable/three", "three"); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.put("three", "three"); assertEq(writableBindings, writableContext); // // rebind new value into writable context rootContext.rebind("java:comp/writable/three", "thirty-three"); // visible from root context rootBindings.put("java:comp/writable/three", "thirty-three"); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.put("three", "thirty-three"); assertEq(writableBindings, writableContext); } public void testUnbindWrapper() throws Exception { // todo ths should throw an exception... value is not removable // unbind value under unmodifible... no exception occurs since unbind is idempotent rootContext.unbind("java:comp/unmodifible/three"); // no change in root context assertEq(rootBindings, rootContext); // no change in unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); } public void testUnbindDirect() throws Exception { // unbind directly from the unmodifible context unmodifibleContext.removeDeepBinding(parse("three"), true); // visible from root context rootBindings.remove("java:comp/unmodifible/three"); assertEq(rootBindings, rootContext); // visible from unmodifibleContext unmodifibleBindings.remove("three"); assertEq(unmodifibleBindings, unmodifibleContext); } public void testUnbindInner() throws Exception { // unbind directly from the unmodifible context rootContext.unbind("java:comp/writable/three"); // visible from root context rootBindings.remove("java:comp/writable/three"); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.remove("three"); assertEq(writableBindings, writableContext); } public void testRenameInner() throws Exception { // // rename in inner context rootContext.rename("java:comp/writable/three", "java:comp/writable/four"); // visible from root context rootBindings.remove("java:comp/writable/three"); rootBindings.put("java:comp/writable/four", new Integer(3)); assertEq(rootBindings, rootContext); // visible from unmodifibleContext writableBindings.remove("three"); writableBindings.put("four", new Integer(3)); assertEq(writableBindings, writableContext); // // rename from inner to wrapper rootContext.rename("java:comp/writable/two", "java:comp/unmodifible/four"); // visible from root context rootBindings.remove("java:comp/writable/two"); rootBindings.put("java:comp/unmodifible/four", new Integer(2)); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.remove("two"); assertEq(writableBindings, writableContext); // not visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); // // rename from wrapper to inner rootContext.rename("java:comp/unmodifible/four", "java:comp/writable/two"); // visible from root context rootBindings.remove("java:comp/unmodifible/four"); rootBindings.put("java:comp/writable/two", new Integer(2)); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.put("two", new Integer(2)); assertEq(writableBindings, writableContext); // not visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); } public void testCreateSubcontextWrapper() throws Exception { // // createSubcontext in wrapper rootContext.createSubcontext("java:comp/unmodifible/context"); rootContext.bind("java:comp/unmodifible/context/foo", "bar"); // visible from root context rootBindings.put("java:comp/unmodifible/context/foo", "bar"); assertEq(rootBindings, rootContext); // not-visible from unmodifibleContext assertEq(unmodifibleBindings, unmodifibleContext); } public void testCreateSubcontextInner() throws Exception { // bind into root context OVER the writable context rootContext.bind("java:comp/writable/TEST", "TEST_VALUE"); // visible from root context rootBindings.put("java:comp/writable/TEST", "TEST_VALUE"); assertEq(rootBindings, rootContext); // visible from writableContext writableBindings.put("TEST", "TEST_VALUE"); assertEq(writableBindings, writableContext); } public static void putAllBindings(Map rootBindings, String nestedPath, Map nestedBindings) { for (Iterator iterator = nestedBindings.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); String fullName = nestedPath + "/" + name; rootBindings.put(fullName, value); } } public static void bind(Context context, Map bindings) throws NamingException { for (Iterator iterator = bindings.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); Name parsedName = context.getNameParser("").parse(name); for (int i =1; i < parsedName.size(); i++) { Name contextName = parsedName.getPrefix(i); if (!FederationTest.bindingExists(context, contextName)) { context.createSubcontext(contextName); } } context.bind(name, value); } } public static boolean bindingExists(Context context, Name contextName) { try { return context.lookup(contextName) != null; } catch (NamingException e) { } return false; } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/AbstractContextTest.java0000644000175000017500000003727310541574201032277 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import junit.framework.TestCase; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.NamingEnumeration; import javax.naming.OperationNotSupportedException; import java.util.Map; import java.util.Iterator; import java.util.TreeSet; /** * @version $Rev$ $Date$ */ public abstract class AbstractContextTest extends TestCase { public static Name parse(String name) throws NamingException { return ContextUtil.NAME_PARSER.parse(name); } public static void assertEq(Map expected, Context actual) throws NamingException { AbstractContextTest.assertEq(ContextUtil.buildMapTree(expected), actual, actual, null); } public static void assertEq(Map expected, String pathInExpected, Context actual) throws NamingException { ContextUtil.Node node = ContextUtil.buildMapTree(expected); Name parsedName = actual.getNameParser("").parse(pathInExpected); for (int i = 0; i < parsedName.size(); i++) { String part = parsedName.get(i); Object value = node.get(part); if (value == null) { throw new NamingException("look for " + parsedName.getPrefix(i+1) + " in node tree is null "); } node = (ContextUtil.Node) value; } AbstractContextTest.assertEq(node, actual, actual, null); } private static void assertEq(ContextUtil.Node node, Context rootContext, Context currentContext, String path) throws NamingException { for (Iterator iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String expectedName = (String) entry.getKey(); Object expectedValue = entry.getValue(); String fullName = path == null ? expectedName : path + "/" + expectedName; // verify we can lookup by string name and parsed name using the root context and current context Object value = AbstractContextTest.assertLookup(expectedValue, currentContext, expectedName); Object absoluteValue = AbstractContextTest.assertLookup(expectedValue, rootContext, fullName); assertSame(fullName, value, absoluteValue); if (expectedValue instanceof ContextUtil.Node) { ContextUtil.Node expectedNode = (ContextUtil.Node) expectedValue; // verufy listing of this context returns the expected results AbstractContextTest.assertList(expectedNode, currentContext, expectedName); AbstractContextTest.assertList(expectedNode, rootContext, fullName); AbstractContextTest.assertEq(expectedNode, rootContext, (Context) value, fullName); } } } public static Object assertLookup(Object expectedValue, Context context, String name) throws NamingException { Object value = context.lookup(name); String contextName = context.getNameInNamespace(); if (contextName == null || contextName.length() == 0) contextName = ""; assertNotNull("lookup of " + name + " on " + contextName + " returned null", value); if (expectedValue instanceof ContextUtil.Node) { assertTrue("Expected lookup of " + name + " on " + contextName + " to return a Context, but got a " + value.getClass().getName(), value instanceof Context); } else { assertEquals("lookup of " + name + " on " + contextName, expectedValue, value); } Name parsedName = context.getNameParser("").parse(name); Object valueFromParsedName = context.lookup(parsedName); assertSame("lookup of " + name + " on " + contextName + " using a parsed name", value, valueFromParsedName); return value; } public static void assertList(ContextUtil.Node node, Context context, String name) throws NamingException { String contextName = context.getNameInNamespace(); if (contextName == null || contextName.length() == 0) contextName = ""; AbstractContextTest.assertListResults(node, context.list(name), contextName, name, false); AbstractContextTest.assertListResults(node, context.listBindings(name), contextName, name, true); Name parsedName = context.getNameParser("").parse(name); AbstractContextTest.assertListResults(node, context.list(parsedName), contextName, "parsed name " + name, false); AbstractContextTest.assertListResults(node, context.listBindings(parsedName), contextName, "parsed name " + name, true); } public static void assertListResults(ContextUtil.Node node, NamingEnumeration enumeration, String contextName, String name, boolean wasListBinding) { Map actualValues; if (wasListBinding) { actualValues = ContextUtil.listBindingsToMap(enumeration); } else { actualValues = ContextUtil.listToMap(enumeration); } for (Iterator iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String expectedName = (String) entry.getKey(); Object expectedValue = entry.getValue(); Object actualValue = actualValues.get(expectedName); assertNotNull("list of " + name + " on " + contextName + " did not find value for " + name, actualValue); if (wasListBinding) { if (expectedValue instanceof ContextUtil.Node) { assertTrue("Expected list of " + name + " on " + contextName + " result value for " + expectedName + " to return a Context, but got a " + actualValue.getClass().getName(), actualValue instanceof Context); } else { assertEquals("list of " + name + " on " + contextName + " for value for " + expectedName, expectedValue, actualValue); } } else { if (!(expectedValue instanceof ContextUtil.Node)) { assertEquals("list of " + name + " on " + contextName + " for value for " + expectedName, expectedValue.getClass().getName(), actualValue); } else { // can't really test this since it the value is the name of a nested node class } } } TreeSet extraNames = new TreeSet(actualValues.keySet()); extraNames.removeAll(node.keySet()); if (!extraNames.isEmpty()) { fail("list of " + name + " on " + contextName + " did not find values: " + extraNames); } } public static Context lookupSubcontext(Context context, String name) throws NamingException { Object value = context.lookup(name); assertTrue("Expected an instance of Context from look up of " + name + " in context " + context.getNameInNamespace(), value instanceof Context); return (Context) value; } public static void assertHasBinding(Context context, String name) { String nameInNamespace = null; try { nameInNamespace = context.getNameInNamespace(); } catch (NamingException e) { throw new RuntimeException("getNameInNamespace threw a NamingException", e); } try { Object value = context.lookup(name); if (value != null) { fail("Lookup of " + name + " on context " + nameInNamespace + " return null"); } } catch (NamingException e) { fail("Lookup of " + name + " on context " + nameInNamespace + " threw " + e.getClass().getName()); } } public static void assertHasBinding(Context context, Name name) { String nameInNamespace = null; try { nameInNamespace = context.getNameInNamespace(); } catch (NamingException e) { throw new RuntimeException("getNameInNamespace threw a NamingException", e); } try { Object value = context.lookup(name); if (value != null) { fail("Lookup of " + name + " on context " + nameInNamespace + " return null"); } } catch (NamingException e) { fail("Lookup of " + name + " on context " + nameInNamespace + " threw " + e.getClass().getName()); } } public static void assertNoBinding(Context context, String name) { String nameInNamespace = null; try { nameInNamespace = context.getNameInNamespace(); } catch (NamingException e) { throw new RuntimeException("getNameInNamespace threw a NamingException", e); } try { Object value = context.lookup(name); if (value == null) { fail("Context " + nameInNamespace + " has a binding for " + name); } } catch (NamingException expected) { } } public static void assertNoBinding(Context context, Name name) { String nameInNamespace = null; try { nameInNamespace = context.getNameInNamespace(); } catch (NamingException e) { throw new RuntimeException("getNameInNamespace threw a NamingException", e); } try { Object value = context.lookup(name); if (value == null) { fail("Context " + nameInNamespace + " has a binding for " + name); } } catch (NamingException expected) { } } public static void assertUnmodifiable(Context context) throws Exception { Object value = "VALUE"; String nameString = "TEST_NAME"; Name name = context.getNameParser("").parse(nameString); // // bind // try { context.bind(nameString, value); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.bind(name, value); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } // // rebind // try { context.rebind(nameString, value); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.rebind(name, value); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } // // rename // String newNameString = "NEW_TEST_NAME"; Name newName = context.getNameParser("").parse(newNameString); try { context.rename(nameString, newNameString); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.rename(name, newName); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } // // unbind // try { context.unbind(nameString); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.unbind(name); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } // // createSubcontext // try { context.createSubcontext(nameString); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.createSubcontext(name); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } // // destroySubcontext // try { context.destroySubcontext(nameString); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } try { context.destroySubcontext(name); fail("Expected an OperationNotSupportedException"); } catch(OperationNotSupportedException expected) { } } public static void assertModifiable(Context context) throws Exception { Object value = "VALUE"; Object newValue = "NEW_VALUE"; String nameString = "TEST_NAME"; Name name = context.getNameParser("").parse(nameString); String newNameString = "NEW_TEST_NAME"; Name newName = context.getNameParser("").parse(newNameString); assertNoBinding(context, nameString); assertNoBinding(context, name); // // bind / unbind // context.bind(nameString, value); assertSame(value, context.lookup(nameString)); context.unbind(nameString); assertNoBinding(context, nameString); context.bind(name, value); assertSame(value, context.lookup(name)); context.unbind(name); assertNoBinding(context, name); // // rebind // context.bind(nameString, value); assertSame(value, context.lookup(nameString)); context.rebind(nameString, newValue); assertSame(newValue, context.lookup(nameString)); context.unbind(nameString); assertNoBinding(context, nameString); context.bind(name, value); assertSame(value, context.lookup(name)); context.rebind(name, newValue); assertSame(newValue, context.lookup(name)); context.unbind(name); assertNoBinding(context, name); // // rename // context.bind(nameString, value); assertSame(value, context.lookup(nameString)); context.rename(nameString, newNameString); assertSame(value, context.lookup(newNameString)); assertNoBinding(context, nameString); context.unbind(newNameString); assertNoBinding(context, nameString); context.bind(name, value); assertSame(value, context.lookup(name)); context.rename(name, newName); assertSame(value, context.lookup(newName)); assertNoBinding(context, name); context.unbind(newName); assertNoBinding(context, name); // // createSubcontext / destroySubcontext // context.createSubcontext(nameString); assertTrue(context.lookup(nameString) instanceof Context); context.destroySubcontext(nameString); assertNoBinding(context, nameString); context.createSubcontext(name); assertTrue(context.lookup(name) instanceof Context); context.destroySubcontext(name); assertNoBinding(context, name); } public static boolean bindingExists(Context context, Name contextName) { try { return context.lookup(contextName) != null; } catch (NamingException e) { } return false; } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/UnmodifiableContextTest.java0000644000175000017500000001066710541574201033130 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.Name; import javax.naming.NameParser; import java.util.HashMap; import java.util.Map; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class UnmodifiableContextTest extends AbstractContextTest { private static final String STRING_VAL = "some string"; private final class MutableContext extends WritableContext { public MutableContext(Map bindings) throws NamingException { super("", bindings, ContextAccess.UNMODIFIABLE); } public void addDeepBinding(Name name, Object value, boolean rebind, boolean createIntermediateContexts) throws NamingException { super.addDeepBinding(name, value, rebind, createIntermediateContexts); } protected void removeDeepBinding(Name name, boolean pruneEmptyContexts) throws NamingException { super.removeDeepBinding(name, pruneEmptyContexts); } } public void testBasic() throws Exception { Map map = new HashMap(); map.put("string", STRING_VAL); map.put("nested/context/string", STRING_VAL); map.put("a/b/c/d/e/string", STRING_VAL); map.put("a/b/c/d/e/one", new Integer(1)); map.put("a/b/c/d/e/two", new Integer(2)); map.put("a/b/c/d/e/three", new Integer(3)); Context context = new WritableContext("", map, ContextAccess.UNMODIFIABLE); assertEq(map, context); assertUnmodifiable(context); } public void testAddBinding() throws Exception { Map map = new HashMap(); map.put("string", STRING_VAL); map.put("nested/context/string", STRING_VAL); map.put("a/b/c/d/e/string", STRING_VAL); map.put("a/b/c/d/e/one", new Integer(1)); map.put("a/b/c/d/e/two", new Integer(2)); map.put("a/b/c/d/e/three", new Integer(3)); MutableContext context = new MutableContext(map); assertEq(map, context); assertUnmodifiable(context); // add a new deep tree map.put("uno/dos/tres", new Integer(123)); NameParser parser = context.getNameParser(); context.addDeepBinding(parser.parse("uno/dos/tres"), new Integer(123), false, true); assertEq(map, context); assertUnmodifiable(context); // modify an existing context map.put("a/b/c/d/e/four", new Integer(4)); context.addDeepBinding(parser.parse("a/b/c/d/e/four"), new Integer(4), false, true); assertEq(map, context); assertUnmodifiable(context); } public void testRemoveBinding() throws Exception { Map map = new HashMap(); map.put("string", STRING_VAL); map.put("nested/context/string", STRING_VAL); map.put("a/b/c/d/e/string", STRING_VAL); map.put("a/b/c/d/e/one", new Integer(1)); map.put("a/b/c/d/e/two", new Integer(2)); map.put("a/b/c/d/e/three", new Integer(3)); MutableContext context = new MutableContext(map); assertEq(map, context); assertUnmodifiable(context); // remove from an exisitng node map.remove("a/b/c/d/e/three"); NameParser parser = context.getNameParser(); context.removeDeepBinding(parser.parse("a/b/c/d/e/three"), true); assertEq(map, context); assertUnmodifiable(context); // remove a deep single element element... empty nodes should be removed map.remove("nested/context/string"); context.removeDeepBinding(parser.parse("nested/context/string"), true); assertEq(map, context); assertUnmodifiable(context); } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ImmutableContextTest.java0000644000175000017500000000657711165477212032465 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import java.util.HashMap; import java.util.Map; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class ImmutableContextTest extends AbstractContextTest { private static final String STRING_VAL = "some string"; public void testBasic() throws Exception { Map map = new HashMap(); map.put("string", STRING_VAL); map.put("nested/context/string", STRING_VAL); map.put("a/b/c/d/e/string", STRING_VAL); map.put("a/b/c/d/e/one", 1); map.put("a/b/c/d/e/two", 2); map.put("a/b/c/d/e/three", 3); map.put("a/a/b/c/d/e/three", 3); map.put("a/b/b/c/d/e/three", 3); Context context = new ImmutableContext(map); assertEq(map, context); assertEquals("a", ((Context)context.lookup("a")).getNameInNamespace()); assertEquals("a/a", ((Context)context.lookup("a/a")).getNameInNamespace()); assertEquals("a/b/b", ((Context)context.lookup("a/b/b")).getNameInNamespace()); assertEquals("a/b", ((Context)context.lookup("a/b")).getNameInNamespace()); assertEquals("a/b/c", ((Context)context.lookup("a/b/c")).getNameInNamespace()); assertEquals("a/b/c/d", ((Context)context.lookup("a/b/c/d")).getNameInNamespace()); assertEquals("a/b/c/d/e", ((Context)context.lookup("a/b/c/d/e")).getNameInNamespace()); } public void testNameInNamespace() throws Exception { Map map = new HashMap(); map.put("string", STRING_VAL); map.put("nested/context/string", STRING_VAL); map.put("a/b/c/d/e/string", STRING_VAL); map.put("a/b/c/d/e/one", 1); map.put("a/b/c/d/e/two", 2); map.put("a/b/c/d/e/three", 3); map.put("a/a/b/c/d/e/three", 3); map.put("a/b/b/c/d/e/three", 3); Context context = new ImmutableContext("a", map, false); assertEquals("a/a", ((Context)context.lookup("a")).getNameInNamespace()); assertEquals("a/a/a", ((Context)context.lookup("a/a")).getNameInNamespace()); assertEquals("a/a/b/b", ((Context)context.lookup("a/b/b")).getNameInNamespace()); assertEquals("a/a/b", ((Context)context.lookup("a/b")).getNameInNamespace()); assertEquals("a/a/b/c", ((Context)context.lookup("a/b/c")).getNameInNamespace()); assertEquals("a/a/b/c/d", ((Context)context.lookup("a/b/c/d")).getNameInNamespace()); assertEquals("a/a/b/c/d/e", ((Context)context.lookup("a/b/c/d/e")).getNameInNamespace()); } } xbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/WritableContextTest.java0000644000175000017500000010122011165477212032274 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NotContextException; import javax.naming.NameAlreadyBoundException; import javax.naming.InvalidNameException; import javax.naming.ContextNotEmptyException; import javax.naming.NamingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class WritableContextTest extends AbstractContextTest { private static final String STRING_VAL = "some string"; private Map bindings; private Context context; public void setUp() throws Exception { super.setUp(); // initialize the bindings map bindings = new HashMap(); bindings.put("string", WritableContextTest.STRING_VAL); bindings.put("nested/context/string", WritableContextTest.STRING_VAL); bindings.put("a/b/c/d/e/string", WritableContextTest.STRING_VAL); bindings.put("a/b/c/d/e/one", new Integer(1)); bindings.put("a/b/c/d/e/two", new Integer(2)); bindings.put("a/b/c/d/e/three", new Integer(3)); // create the contxt context = new WritableContext(); // bind the bindings for (Iterator iterator = bindings.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); Name parsedName = context.getNameParser("").parse(name); for (int i =1; i < parsedName.size(); i++) { Name contextName = parsedName.getPrefix(i); if (!bindingExists(context, contextName)) { context.createSubcontext(contextName); } } context.bind(name, value); } } public void testLookupAndList() throws Exception { assertEq(bindings, context); } public void testLookupExceptions() throws Exception{ // // lookup a non-existing value of an exisitng context // try { context.lookup("a/b/c/d/e/NoSuchValue"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } assertEq(bindings, context); try { context.lookup(parse("a/b/c/d/e/NoSuchValue")); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } assertEq(bindings, context); // // lookup a non-existing value of a non-exisitng context // try { context.list("a/b/NoSuchContext/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.list(parse("a/b/NoSuchContext/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // lookup null // try { context.lookup((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.lookup((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testLookupLinkExceptions() throws Exception{ // // lookupLink a non-existing value of an exisitng context // try { context.lookupLink("a/b/c/d/e/NoSuchValue"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } assertEq(bindings, context); try { context.lookupLink(parse("a/b/c/d/e/NoSuchValue")); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } assertEq(bindings, context); // // lookupLink a non-existing value of a non-exisitng context // try { context.list("a/b/NoSuchContext/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.list(parse("a/b/NoSuchContext/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // lookupLink null // try { context.lookupLink((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.lookupLink((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testListExceptions() throws Exception{ // // list a non-existing subcontext of an exisitng context // try { context.list("a/b/c/d/e/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.list(parse("a/b/c/d/e/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // list a non-existing subcontext of a non-exisitng context // try { context.list("a/b/NoSuchContext/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.list(parse("a/b/NoSuchContext/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // list a binding that is a value instead of a context // try { context.list("a/b/c/d/e/three"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.list(parse("a/b/c/d/e/three")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // list null // try { context.list((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.list((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testListBindingsExceptions() throws Exception{ // // listBindings a non-existing subcontext of an exisitng context // try { context.listBindings("a/b/c/d/e/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.listBindings(parse("a/b/c/d/e/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // listBindings a non-existing subcontext of a non-exisitng context // try { context.listBindings("a/b/NoSuchContext/NoSuchContext"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.listBindings(parse("a/b/NoSuchContext/NoSuchContext")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // listBindings a binding that is a value instead of a context // try { context.listBindings("a/b/c/d/e/three"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.listBindings(parse("a/b/c/d/e/three")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // listBindings null // try { context.listBindings((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.listBindings((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testBind() throws Exception { // bind(String) bindings.put("a/b/c/d/e/forty-two", new Integer(42)); context.bind("a/b/c/d/e/forty-two", new Integer(42)); assertEq(bindings, context); // bind(Name) bindings.put("a/b/c/d/e/forty-four", new Integer(44)); context.bind(parse("a/b/c/d/e/forty-four"), new Integer(44)); assertEq(bindings, context); } public void testBindExceptions() throws Exception{ // // bind over existing value of an exisitng context // try { context.bind("a/b/c/d/e/three", "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.bind(parse("a/b/c/d/e/three"), "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // bind over root context // try { context.bind("", "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.bind(parse(""), "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // bind to non-existing context // try { context.bind("a/b/NoSuchContext/name", "value"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.bind(parse("a/b/NoSuchContext/name"), "value"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // bind null // try { context.bind((String)null, "value"); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.bind((Name)null, "value"); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testUnbind() throws Exception { // unbind(String) bindings.remove("a/b/c/d/e/three"); context.unbind("a/b/c/d/e/three"); assertEq(bindings, context); // unbind(Name) bindings.remove("a/b/c/d/e/two"); context.unbind(parse("a/b/c/d/e/two")); assertEq(bindings, context); } public void testUnbindExceptions() throws Exception{ // // unbind non empty context // try { context.unbind("a/b/c"); fail("Expected ContextNotEmptyException"); } catch (ContextNotEmptyException expected) { } assertEq(bindings, context); try { context.unbind(parse("a/b/c")); fail("Expected ContextNotEmptyException"); } catch (ContextNotEmptyException expected) { } assertEq(bindings, context); // // unbind root context // try { context.unbind(""); fail("Expected InvalidNameException"); } catch (InvalidNameException expected) { } assertEq(bindings, context); try { context.unbind(parse("")); fail("Expected InvalidNameException"); } catch (InvalidNameException expected) { } assertEq(bindings, context); // // unbind non-existing context // try { context.unbind("a/b/NoSuchContext/name"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.unbind(parse("a/b/NoSuchContext/name")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // unbind null // try { context.unbind((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.unbind((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testRebind() throws Exception { // rebind(String) bindings.put("a/b/c/d/e/three", new Integer(33)); context.rebind("a/b/c/d/e/three", new Integer(33)); assertEq(bindings, context); // rebind(Name) bindings.put("a/b/c/d/e/three", new Integer(33333)); context.rebind(parse("a/b/c/d/e/three"), new Integer(33333)); assertEq(bindings, context); // rebind(String) - New Value bindings.put("a/b/c/d/e/forty-two", new Integer(42)); context.rebind("a/b/c/d/e/forty-two", new Integer(42)); assertEq(bindings, context); // rebind(Name) - New Value bindings.put("a/b/c/d/e/forty-four", new Integer(44)); context.rebind(parse("a/b/c/d/e/forty-four"), new Integer(44)); assertEq(bindings, context); } public void testRebindExceptions() throws Exception{ // // rebind over root context // try { context.rebind("", "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.rebind(parse(""), "value"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // rebind to non-existing context // try { context.rebind("a/b/NoSuchContext/name", "value"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.rebind(parse("a/b/NoSuchContext/name"), "value"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // rebind null // try { context.rebind((String)null, "value"); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rebind((Name)null, "value"); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testRename() throws Exception { // rename(String, String) Object value = bindings.remove("a/b/c/d/e/three"); bindings.put("a/b/c/d/e/boo", value); context.rename("a/b/c/d/e/three", "a/b/c/d/e/boo"); assertEq(bindings, context); // rename(Name, Name) value = bindings.remove("a/b/c/d/e/boo"); bindings.put("a/b/c/d/e/moo", value); context.rename(parse("a/b/c/d/e/boo"), parse("a/b/c/d/e/moo")); assertEq(bindings, context); } public void testRenameExceptions() throws Exception{ // // rename over existing value of an exisitng context // try { context.rename("a/b/c/d/e/one", "a/b/c/d/e/three"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.rename(parse("a/b/c/d/e/one"), parse("a/b/c/d/e/three")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // rename over root context // try { context.rename("a/b/c/d/e/one", ""); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.rename(parse("a/b/c/d/e/one"), parse("")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // rename to non-existing context // try { context.rename("a/b/c/d/e/one", "a/b/NoSuchContext/name"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.rename(parse("a/b/c/d/e/one"), parse("a/b/NoSuchContext/name")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // rename null // try { context.rename(null, "SOME_NAME"); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rename(null, parse("SOME_NAME")); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rename("SOME_NAME", null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rename(null, parse("SOME_NAME")); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rename((String)null, (String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.rename((Name)null, (Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testCreateSubcontext() throws Exception { // createSubcontext(String) bindings.put("a/b/c/d/e/f/foo", "bar"); context.createSubcontext("a/b/c/d/e/f"); context.bind("a/b/c/d/e/f/foo", "bar"); assertEq(bindings, context); // createSubcontext(Name) bindings.put("a/b/c/d/e/f2/foo", "bar"); context.createSubcontext(parse("a/b/c/d/e/f2")); context.bind(parse("a/b/c/d/e/f2/foo"), "bar"); assertEq(bindings, context); } public void testCreateSubcontextExceptions() throws Exception{ // // createSubcontext over existing value of an exisitng context // try { context.createSubcontext("a/b/c/d/e/three"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.createSubcontext(parse("a/b/c/d/e/three")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // createSubcontext over existing context // try { context.createSubcontext("a/b/c"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.createSubcontext(parse("a/b/c")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // createSubcontext over root context // try { context.createSubcontext(""); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.createSubcontext(parse("")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // createSubcontext in a non-existing context // try { context.createSubcontext("a/b/NoSuchContext/name"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.createSubcontext(parse("a/b/NoSuchContext/name")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // createSubcontext null // try { context.createSubcontext((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.createSubcontext((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testDestroySubcontext() throws Exception { // destroySubcontext(String) bindings.put("a/b/c/d/e/f/foo", "bar"); context.createSubcontext("a/b/c/d/e/f"); context.bind("a/b/c/d/e/f/foo", "bar"); assertEq(bindings, context); bindings.remove("a/b/c/d/e/f/foo"); context.unbind("a/b/c/d/e/f/foo"); context.destroySubcontext("a/b/c/d/e/f"); assertEq(bindings, context); // destroySubcontext(Name) bindings.put("a/b/c/d/e/f2/foo", "bar"); context.createSubcontext(parse("a/b/c/d/e/f2")); context.bind(parse("a/b/c/d/e/f2/foo"), "bar"); assertEq(bindings, context); bindings.remove("a/b/c/d/e/f2/foo"); context.unbind(parse("a/b/c/d/e/f2/foo")); context.destroySubcontext(parse("a/b/c/d/e/f2")); assertEq(bindings, context); } public void testDestroySubcontextExceptions() throws Exception{ // // destroySubcontext a value (not a context) // try { context.createSubcontext("a/b/c/d/e/three"); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); try { context.createSubcontext(parse("a/b/c/d/e/three")); fail("Expected NameAlreadyBoundException"); } catch (NameAlreadyBoundException expected) { } assertEq(bindings, context); // // destroySubcontext non empty context // try { context.destroySubcontext("a/b/c"); fail("Expected ContextNotEmptyException"); } catch (ContextNotEmptyException expected) { } assertEq(bindings, context); try { context.destroySubcontext(parse("a/b/c")); fail("Expected ContextNotEmptyException"); } catch (ContextNotEmptyException expected) { } assertEq(bindings, context); // // destroySubcontext root context // try { context.destroySubcontext(""); fail("Expected InvalidNameException"); } catch (InvalidNameException expected) { } assertEq(bindings, context); try { context.destroySubcontext(parse("")); fail("Expected InvalidNameException"); } catch (InvalidNameException expected) { } assertEq(bindings, context); // // destroySubcontext non-existing context // try { context.destroySubcontext("a/b/NoSuchContext/name"); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); try { context.destroySubcontext(parse("a/b/NoSuchContext/name")); fail("Expected NotContextException"); } catch (NotContextException expected) { } assertEq(bindings, context); // // destroySubcontext null // try { context.destroySubcontext((String)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); try { context.destroySubcontext((Name)null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } assertEq(bindings, context); } public void testLookupSubContext() throws Exception { Context ctx = (Context) context.lookup("a/b/c"); String s = (String) ctx.lookup("d/e/string"); assertEquals(s, WritableContextTest.STRING_VAL); } public void testDeepBinding() throws Exception { WritableContext w = new WritableContext("jca:"); w.addDeepBinding(w.getNameParser("").parse("test/test/GBean/resourceSource"), WritableContextTest.STRING_VAL, false, true); assertEquals(WritableContextTest.STRING_VAL, w.lookup("test/test/GBean/resourceSource")); w.rebind("test/test/GBean/resourceSource", 1); assertEquals(new Integer(1), w.lookup("test/test/GBean/resourceSource")); } public void testRemoveDeepBinding_Leaf() throws Exception { WritableContext w = new WritableContext("jca:"); // Test when only one object w.addDeepBinding(w.getNameParser("").parse("test/test/GBean/resourceSource"), WritableContextTest.STRING_VAL, true, true); assertEquals(WritableContextTest.STRING_VAL, w.lookup("test/test/GBean/resourceSource")); w.removeDeepBinding(w.getNameParser("").parse("test/test/GBean/resourceSource"), true, true); try { w.lookup("test"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } w.addDeepBinding(w.getNameParser("").parse("test/test/GBean/resourceSource"), WritableContextTest.STRING_VAL, true, true); assertEquals(WritableContextTest.STRING_VAL, w.lookup("test/test/GBean/resourceSource")); w.addDeepBinding(w.getNameParser("").parse("test/test/GBean/rresourceSource2"), new Integer(2), true, true); assertEquals(new Integer(2), w.lookup("test/test/GBean/rresourceSource2")); w.removeDeepBinding(w.getNameParser("").parse("test/test/GBean/resourceSource"), true, true); assertEquals(new Integer(2), w.lookup("test/test/GBean/rresourceSource2")); try { w.lookup("test/test/GBean/resourceSource"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } w.removeDeepBinding(w.getNameParser("").parse("test/test/GBean/rresourceSource2"), true, true); try { w.lookup("test"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } } public void testRemoveDeepBinding_Intermediate() throws Exception { WritableContext w = new WritableContext("jca:"); // Test when only one object w.addDeepBinding(w.getNameParser("").parse("test/test1/GBean/resourceSource"), WritableContextTest.STRING_VAL, true, true); assertEquals(WritableContextTest.STRING_VAL, w.lookup("test/test1/GBean/resourceSource")); w.removeDeepBinding(w.getNameParser("").parse("test/test1/GBean/resourceSource"), true, true); try { w.lookup("test"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } w.addDeepBinding(w.getNameParser("").parse("test/test1/GBean/resourceSource"), WritableContextTest.STRING_VAL, true, true); assertEquals(WritableContextTest.STRING_VAL, w.lookup("test/test1/GBean/resourceSource")); w.addDeepBinding(w.getNameParser("").parse("test/test2/GBean/rresourceSource2"), new Integer(2), true, true); assertEquals(new Integer(2), w.lookup("test/test2/GBean/rresourceSource2")); w.removeDeepBinding(w.getNameParser("").parse("test/test1/GBean/resourceSource"), true, true); assertEquals(new Integer(2), w.lookup("test/test2/GBean/rresourceSource2")); try { w.lookup("test/test1"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } w.removeDeepBinding(w.getNameParser("").parse("test/test2/GBean/rresourceSource2"), true, true); try { w.lookup("test"); fail("Expected NameNotFoundException"); } catch (NameNotFoundException expected) { } } public void test2PathsCreateSubcontext() throws Exception { WritableContext w = new WritableContext(); doBind(w, "a/b/c", "c"); doBind(w, "a/b/b/c", "c"); assertEquals("a", ((Context)w.lookup("a")).getNameInNamespace()); assertEquals("a/b", ((Context)w.lookup("a/b")).getNameInNamespace()); assertEquals("a/b/b", ((Context)w.lookup("a/b/b")).getNameInNamespace()); w = new WritableContext("a"); doBind(w, "a/b/c", "c"); doBind(w, "a/b/b/c", "c"); assertEquals("a/a", ((Context)w.lookup("a")).getNameInNamespace()); assertEquals("a/a/b", ((Context)w.lookup("a/b")).getNameInNamespace()); assertEquals("a/a/b/b", ((Context)w.lookup("a/a/b/b")).getNameInNamespace()); } private void doBind(Context context, String nameString, Object value) throws NamingException { Name name = context.getNameParser("").parse(nameString); Context current = context; for (int i = 0; i< name.size() - 1; i++) { String part = name.get(i); try { Object o = current.lookup(part); if (!(o instanceof Context)) { throw new NamingException("not a context at " + part +" found: " + o); } current = (Context) o; } catch (NamingException e) { current = current.createSubcontext(part); } } current.bind(name.get(name.size() - 1), value); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ContextAccessControlListTest.javaxbean-3.7/xbean-naming/src/test/java/org/apache/xbean/naming/context/ContextAccessControlListTest.ja0000644000175000017500000002162510541574201033575 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.naming.context; import javax.naming.Context; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ */ public class ContextAccessControlListTest extends AbstractContextTest { private ContextAccessControlList allowDenyACL; private ContextAccessControlList denyAllowACL; private Context allowDenyContext; private WritableContext denyAllowContext; public void testAllowDeny() throws Exception { // outside of listed assertTrue(allowDenyACL.isModifiable(parse("foo"))); // explicitly allowed assertTrue(allowDenyACL.isModifiable(parse("allow"))); // child of explicitly allowed assertTrue(allowDenyACL.isModifiable(parse("allow/foo"))); // explicitly denied assertFalse(allowDenyACL.isModifiable(parse("deny"))); // child of explicitly denied assertFalse(allowDenyACL.isModifiable(parse("deny/foo"))); // parent of denied assertTrue(allowDenyACL.isModifiable(parse("a/b"))); assertTrue(allowDenyACL.isModifiable(parse("one/two"))); // explicitly denied assertFalse(allowDenyACL.isModifiable(parse("a/b/c"))); assertFalse(allowDenyACL.isModifiable(parse("one/two/three"))); // child of denied assertFalse(allowDenyACL.isModifiable(parse("a/b/c/foo"))); assertFalse(allowDenyACL.isModifiable(parse("one/two/three/foo"))); assertFalse(allowDenyACL.isModifiable(parse("a/b/c/d"))); assertFalse(allowDenyACL.isModifiable(parse("one/two/three/four"))); // deny override assertTrue(allowDenyACL.isModifiable(parse("a/b/c/d/e"))); assertTrue(allowDenyACL.isModifiable(parse("one/two/three/four/five"))); // child of deny override assertTrue(allowDenyACL.isModifiable(parse("a/b/c/d/e/foo"))); assertTrue(allowDenyACL.isModifiable(parse("one/two/three/four/five/foo"))); } public void testDenyAllow() throws Exception { // outside of listed assertFalse(denyAllowACL.isModifiable(parse("foo"))); // explicitly allowed assertTrue(denyAllowACL.isModifiable(parse("allow"))); // child of explicitly allowed assertTrue(denyAllowACL.isModifiable(parse("allow/foo"))); // explicitly denied assertFalse(denyAllowACL.isModifiable(parse("deny"))); // child of explicitly denied assertFalse(denyAllowACL.isModifiable(parse("deny/foo"))); // parent of allowed assertFalse(denyAllowACL.isModifiable(parse("a/b"))); assertFalse(denyAllowACL.isModifiable(parse("one/two"))); // explicitly allowed assertTrue(denyAllowACL.isModifiable(parse("a/b/c"))); assertTrue(denyAllowACL.isModifiable(parse("one/two/three"))); // child of allowed assertTrue(denyAllowACL.isModifiable(parse("a/b/c/foo"))); assertTrue(denyAllowACL.isModifiable(parse("one/two/three/foo"))); assertTrue(denyAllowACL.isModifiable(parse("a/b/c/d"))); assertTrue(denyAllowACL.isModifiable(parse("one/two/three/four"))); // allow override assertFalse(denyAllowACL.isModifiable(parse("a/b/c/d/e"))); assertFalse(denyAllowACL.isModifiable(parse("one/two/three/four/five"))); // children of allow override assertFalse(denyAllowACL.isModifiable(parse("a/b/c/d/e/foo"))); assertFalse(denyAllowACL.isModifiable(parse("one/two/three/four/five/foo"))); } public void testAllowDenyContext() throws Exception { // outside of listed assertModifiable(lookupSubcontext(allowDenyContext, "foo")); // explicitly allowed assertModifiable(lookupSubcontext(allowDenyContext, "allow")); // child of explicitly allowed assertModifiable(lookupSubcontext(allowDenyContext, "allow/foo")); // explicitly denied assertUnmodifiable(lookupSubcontext(allowDenyContext, "deny")); // child of explicitly denied assertUnmodifiable(lookupSubcontext(allowDenyContext, "deny/foo")); // parent of denied assertModifiable(lookupSubcontext(allowDenyContext, "a/b")); assertModifiable(lookupSubcontext(allowDenyContext, "one/two")); // explicitly denied assertUnmodifiable(lookupSubcontext(allowDenyContext, "a/b/c")); assertUnmodifiable(lookupSubcontext(allowDenyContext, "one/two/three")); // child of denied assertUnmodifiable(lookupSubcontext(allowDenyContext, "a/b/c/foo")); assertUnmodifiable(lookupSubcontext(allowDenyContext, "one/two/three/foo")); assertUnmodifiable(lookupSubcontext(allowDenyContext, "a/b/c/d")); assertUnmodifiable(lookupSubcontext(allowDenyContext, "one/two/three/four")); // deny override assertModifiable(lookupSubcontext(allowDenyContext, "a/b/c/d/e")); assertModifiable(lookupSubcontext(allowDenyContext, "one/two/three/four/five")); // child of deny override assertModifiable(lookupSubcontext(allowDenyContext, "a/b/c/d/e/foo")); assertModifiable(lookupSubcontext(allowDenyContext, "one/two/three/four/five/foo")); } public void testDenyAllowContext() throws Exception { // outside of listed assertUnmodifiable(lookupSubcontext(denyAllowContext, "foo")); // explicitly allowed assertModifiable(lookupSubcontext(denyAllowContext, "allow")); // child of explicitly allowed assertModifiable(lookupSubcontext(denyAllowContext, "allow/foo")); // explicitly denied assertUnmodifiable(lookupSubcontext(denyAllowContext, "deny")); // child of explicitly denied assertUnmodifiable(lookupSubcontext(denyAllowContext, "deny/foo")); // parent of allowed assertUnmodifiable(lookupSubcontext(denyAllowContext, "a/b")); assertUnmodifiable(lookupSubcontext(denyAllowContext, "one/two")); // explicitly allowed assertModifiable(lookupSubcontext(denyAllowContext, "a/b/c")); assertModifiable(lookupSubcontext(denyAllowContext, "one/two/three")); // child of allowed assertModifiable(lookupSubcontext(denyAllowContext, "a/b/c/foo")); assertModifiable(lookupSubcontext(denyAllowContext, "one/two/three/foo")); assertModifiable(lookupSubcontext(denyAllowContext, "a/b/c/d")); assertModifiable(lookupSubcontext(denyAllowContext, "one/two/three/four")); // allow override assertUnmodifiable(lookupSubcontext(denyAllowContext, "a/b/c/d/e")); assertUnmodifiable(lookupSubcontext(denyAllowContext, "one/two/three/four/five")); // children of allow override assertUnmodifiable(lookupSubcontext(denyAllowContext, "a/b/c/d/e/foo")); assertUnmodifiable(lookupSubcontext(denyAllowContext, "one/two/three/four/five/foo")); } protected void setUp() throws Exception { super.setUp(); allowDenyACL = new ContextAccessControlList(true, Arrays.asList(new String[]{"allow", "a/b/c/d/e", "one/two/three/four/five"}), Arrays.asList(new String[]{"deny", "a/b/c", "one/two/three"})); denyAllowACL = new ContextAccessControlList(false, Arrays.asList(new String[]{"allow", "a/b/c", "one/two/three"}), Arrays.asList(new String[]{"deny", "a/b/c/d/e", "one/two/three/four/five"})); Map map = new HashMap(); // outside of listed map.put("foo/value", "bar"); // explicitly allowed map.put("allow/foo/cheese", "cheddar"); // explicitly denied map.put("deny/foo/cheese", "american"); // child of denied map.put("a/b/c/foo/value", "bar"); map.put("one/two/three/foo/value", "bar"); // child of deny override map.put("a/b/c/d/e/foo/value", "bar"); map.put("one/two/three/four/five/foo/value", "bar"); allowDenyContext = new WritableContext("", map, allowDenyACL); assertEq(map, allowDenyContext); denyAllowContext = new WritableContext("", map, denyAllowACL); assertEq(map, denyAllowContext); } } xbean-3.7/xbean-finder/0000755000175000017500000000000011610661040014711 5ustar drazzibdrazzibxbean-3.7/xbean-finder/pom.xml0000644000175000017500000000604511373256143016245 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-finder bundle Apache XBean :: Classpath Resource Finder XBean Finder helps to find annotations in classes org.apache.xbean xbean-bundleutils org.slf4j slf4j-api asm asm 3.1 provided asm asm-commons 3.1 provided org.osgi org.osgi.core 4.2.0 provided org.apache.felix maven-bundle-plugin 2.0.0 true *,org.objectweb.asm;version=3.1,org.objectweb.asm.commons;version=3.1 xbean-3.7/xbean-finder/src/0000755000175000017500000000000011610661040015500 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/0000755000175000017500000000000011610661040016424 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/resources/0000755000175000017500000000000011610661040020436 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/resources/META-INF/0000755000175000017500000000000011610661040021576 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/0000755000175000017500000000000011610661037017353 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/org/0000755000175000017500000000000011610661037020142 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/org/apache/0000755000175000017500000000000011610661037021363 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661037022460 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/0000755000175000017500000000000011610661040023721 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/UrlSet.java0000644000175000017500000001413011363706454026017 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import java.net.URL; import java.net.MalformedURLException; import java.util.Collection; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.HashMap; import java.util.Arrays; import java.io.IOException; import java.io.File; /** * @version $Rev$ $Date$ */ public class UrlSet { private final Map urls; public UrlSet(ClassLoader classLoader) throws IOException { this(getUrls(classLoader)); } public UrlSet(URL... urls){ this(Arrays.asList(urls)); } /** * Ignores all URLs that are not "jar" or "file" * @param urls */ public UrlSet(Collection urls){ this.urls = new HashMap(); for (URL location : urls) { try { // if (location.getProtocol().equals("file")) { // try { // // See if it's actually a jar // URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/"); // JarURLConnection juc = (JarURLConnection) jarUrl.openConnection(); // juc.getJarFile(); // location = jarUrl; // } catch (IOException e) { // } // this.urls.put(location.toExternalForm(), location); // } this.urls.put(location.toExternalForm(), location); } catch (Exception e) { e.printStackTrace(); } } } private UrlSet(Map urls) { this.urls = urls; } public UrlSet include(UrlSet urlSet){ Map urls = new HashMap(this.urls); urls.putAll(urlSet.urls); return new UrlSet(urls); } public UrlSet exclude(UrlSet urlSet) { Map urls = new HashMap(this.urls); Map parentUrls = urlSet.urls; for (String url : parentUrls.keySet()) { urls.remove(url); } return new UrlSet(urls); } public UrlSet exclude(ClassLoader parent) throws IOException { return exclude(new UrlSet(parent)); } public UrlSet exclude(File file) throws MalformedURLException { return exclude(relative(file)); } public UrlSet exclude(String pattern) throws MalformedURLException { return exclude(matching(pattern)); } /** * Calls excludePaths(System.getProperty("java.ext.dirs")) * @return * @throws MalformedURLException */ public UrlSet excludeJavaExtDirs() throws MalformedURLException { String extDirs = System.getProperty("java.ext.dirs"); return extDirs == null ? this : excludePaths(extDirs); } /** * Calls excludePaths(System.getProperty("java.endorsed.dirs")) * * @return * @throws MalformedURLException */ public UrlSet excludeJavaEndorsedDirs() throws MalformedURLException { String endorsedDirs = System.getProperty("java.endorsed.dirs"); return endorsedDirs == null ? this : excludePaths(endorsedDirs); } public UrlSet excludeJavaHome() throws MalformedURLException { String path = System.getProperty("java.home"); File java = new File(path); if (path.matches("/System/Library/Frameworks/JavaVM.framework/Versions/[^/]+/Home")){ java = java.getParentFile(); } return exclude(java); } public UrlSet excludePaths(String pathString) throws MalformedURLException { String[] paths = pathString.split(File.pathSeparator); UrlSet urlSet = this; for (String path : paths) { File file = new File(path); urlSet = urlSet.exclude(file); } return urlSet; } public UrlSet matching(String pattern) { Map urls = new HashMap(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.matches(pattern)){ urls.put(url, entry.getValue()); } } return new UrlSet(urls); } public UrlSet relative(File file) throws MalformedURLException { String urlPath = file.toURI().toURL().toExternalForm(); Map urls = new HashMap(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.startsWith(urlPath) || url.startsWith("jar:"+urlPath)){ urls.put(url, entry.getValue()); } } return new UrlSet(urls); } public List getUrls() { return new ArrayList(urls.values()); } private static List getUrls(ClassLoader classLoader) throws IOException { List list = new ArrayList(); ArrayList urls = Collections.list(classLoader.getResources("META-INF")); for (URL url : urls) { String externalForm = url.toExternalForm(); int i = externalForm.lastIndexOf("META-INF"); externalForm = externalForm.substring(0, i); url = new URL(externalForm); list.add(url); } list.addAll(Collections.list(classLoader.getResources(""))); return list; } } xbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/AbstractFinder.java0000644000175000017500000006622411350224046027473 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.finder; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.commons.EmptyVisitor; import org.objectweb.asm.signature.SignatureReader; import org.objectweb.asm.signature.SignatureVisitor; /** * @version $Rev: 924423 $ $Date: 2010-03-17 20:06:14 +0100 (mer. 17 mars 2010) $ */ public abstract class AbstractFinder { private final Map> annotated = new HashMap>(); protected final List classInfos = new ArrayList(); private final List classesNotLoaded = new ArrayList(); private final int ASM_FLAGS = ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES; protected abstract URL getResource(String className); protected abstract Class loadClass(String fixedName) throws ClassNotFoundException; public boolean isAnnotationPresent(Class annotation) { List infos = annotated.get(annotation.getName()); return infos != null && !infos.isEmpty(); } /** * Returns a list of classes that could not be loaded in last invoked findAnnotated* method. *

* The list will only contain entries of classes whose byte code matched the requirements * of last invoked find* method, but were unable to be loaded and included in the results. *

* The list returned is unmodifiable. Once obtained, the returned list will be a live view of the * results from the last findAnnotated* method call. *

* This method is not thread safe. * @return an unmodifiable live view of classes that could not be loaded in previous findAnnotated* call. */ public List getClassesNotLoaded() { return Collections.unmodifiableList(classesNotLoaded); } public List findAnnotatedPackages(Class annotation) { classesNotLoaded.clear(); List packages = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof PackageInfo) { PackageInfo packageInfo = (PackageInfo) info; try { Package pkg = packageInfo.get(); // double check via proper reflection if (pkg.isAnnotationPresent(annotation)) { packages.add(pkg); } } catch (ClassNotFoundException e) { classesNotLoaded.add(packageInfo.getName()); } } } return packages; } public List findAnnotatedClasses(Class annotation) { classesNotLoaded.clear(); List classes = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof ClassInfo) { ClassInfo classInfo = (ClassInfo) info; try { Class clazz = classInfo.get(); // double check via proper reflection if (clazz.isAnnotationPresent(annotation)) { classes.add(clazz); } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } } } return classes; } /** * Naive implementation - works extremelly slow O(n^3) * * @param annotation * @return list of directly or indirectly (inherited) annotated classes */ public List findInheritedAnnotatedClasses(Class annotation) { classesNotLoaded.clear(); List classes = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { try { if(info instanceof ClassInfo){ classes.add(((ClassInfo) info).get()); } } catch (ClassNotFoundException cnfe) { // TODO: ignored, but a log message would be appropriate } } boolean annClassFound; List tempClassInfos = new ArrayList(classInfos); do { annClassFound = false; for (int pos = 0; pos < tempClassInfos.size(); pos++) { ClassInfo classInfo = tempClassInfos.get(pos); try { // check whether any superclass is annotated String superType = classInfo.getSuperType(); for (Class clazz : classes) { if (superType.equals(clazz.getName())) { classes.add(classInfo.get()); tempClassInfos.remove(pos); annClassFound = true; break; } } // check whether any interface is annotated List interfces = classInfo.getInterfaces(); for (String interfce: interfces) { for (Class clazz : classes) { if (interfce.replaceFirst("<.*>","").equals(clazz.getName())) { classes.add(classInfo.get()); tempClassInfos.remove(pos); annClassFound = true; break; } } } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } catch (NoClassDefFoundError e) { classesNotLoaded.add(classInfo.getName()); } } } while (annClassFound); return classes; } public List findAnnotatedMethods(Class annotation) { classesNotLoaded.clear(); List seen = new ArrayList(); List methods = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && !info.getName().equals("")) { MethodInfo methodInfo = (MethodInfo) info; ClassInfo classInfo = methodInfo.getDeclaringClass(); if (seen.contains(classInfo)) continue; seen.add(classInfo); try { Class clazz = classInfo.get(); for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(annotation)) { methods.add(method); } } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } } } return methods; } public List findAnnotatedConstructors(Class annotation) { classesNotLoaded.clear(); List seen = new ArrayList(); List constructors = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && info.getName().equals("")) { MethodInfo methodInfo = (MethodInfo) info; ClassInfo classInfo = methodInfo.getDeclaringClass(); if (seen.contains(classInfo)) continue; seen.add(classInfo); try { Class clazz = classInfo.get(); for (Constructor constructor : clazz.getConstructors()) { if (constructor.isAnnotationPresent(annotation)) { constructors.add(constructor); } } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } } } return constructors; } public List findAnnotatedFields(Class annotation) { classesNotLoaded.clear(); List seen = new ArrayList(); List fields = new ArrayList(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof FieldInfo) { FieldInfo fieldInfo = (FieldInfo) info; ClassInfo classInfo = fieldInfo.getDeclaringClass(); if (seen.contains(classInfo)) continue; seen.add(classInfo); try { Class clazz = classInfo.get(); for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(annotation)) { fields.add(field); } } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } } } return fields; } public List findClassesInPackage(String packageName, boolean recursive) { classesNotLoaded.clear(); List classes = new ArrayList(); for (ClassInfo classInfo : classInfos) { try { if (recursive && classInfo.getPackageName().startsWith(packageName)){ classes.add(classInfo.get()); } else if (classInfo.getPackageName().equals(packageName)){ classes.add(classInfo.get()); } } catch (ClassNotFoundException e) { classesNotLoaded.add(classInfo.getName()); } } return classes; } protected List getAnnotationInfos(String name) { List infos = annotated.get(name); if (infos == null) { infos = new ArrayList(); annotated.put(name, infos); } return infos; } protected void readClassDef(InputStream in) throws IOException { ClassReader classReader = new ClassReader(in); classReader.accept(new InfoBuildingVisitor(), ASM_FLAGS); } public class Annotatable { private final List annotations = new ArrayList(); public Annotatable(AnnotatedElement element) { for (Annotation annotation : element.getAnnotations()) { annotations.add(new ClassFinder.AnnotationInfo(annotation.annotationType().getName())); } } public Annotatable() { } public List getAnnotations() { return annotations; } } public static interface Info { String getName(); List getAnnotations(); } public class PackageInfo extends Annotatable implements Info { private final String name; private final ClassFinder.ClassInfo info; private final Package pkg; public PackageInfo(Package pkg){ super(pkg); this.pkg = pkg; this.name = pkg.getName(); this.info = null; } public PackageInfo(String name) { info = new ClassFinder.ClassInfo(name, null); this.name = name; this.pkg = null; } public String getName() { return name; } public Package get() throws ClassNotFoundException { return (pkg != null)?pkg:info.get().getPackage(); } } public class ClassInfo extends Annotatable implements Info { private String name; private final List methods = new ArrayList(); private final List constructors = new ArrayList(); private String superType; private final List interfaces = new ArrayList(); private final List fields = new ArrayList(); private Class clazz; private ClassNotFoundException notFound; public ClassInfo(Class clazz) { super(clazz); this.clazz = clazz; this.name = clazz.getName(); Class superclass = clazz.getSuperclass(); this.superType = superclass != null ? superclass.getName(): null; } public ClassInfo(String name, String superType) { this.name = name; this.superType = superType; } public String getPackageName(){ return name.substring(0,name.lastIndexOf(".")); } public List getConstructors() { return constructors; } public List getInterfaces() { return interfaces; } public List getFields() { return fields; } public List getMethods() { return methods; } public String getName() { return name; } public String getSuperType() { return superType; } public Class get() throws ClassNotFoundException { if (clazz != null) return clazz; if (notFound != null) throw notFound; try { String fixedName = name.replaceFirst("<.*>", ""); this.clazz = loadClass(fixedName); return clazz; } catch (ClassNotFoundException notFound) { classesNotLoaded.add(name); this.notFound = notFound; throw notFound; } } public String toString() { return name; } } public class MethodInfo extends Annotatable implements Info { private final ClassInfo declaringClass; private final String returnType; private final String name; private final List> parameterAnnotations = new ArrayList>(); public MethodInfo(ClassInfo info, Constructor constructor){ super(constructor); this.declaringClass = info; this.name = ""; this.returnType = Void.TYPE.getName(); } public MethodInfo(ClassInfo info, Method method){ super(method); this.declaringClass = info; this.name = method.getName(); this.returnType = method.getReturnType().getName(); } public MethodInfo(ClassInfo declarignClass, String name, String returnType) { this.declaringClass = declarignClass; this.name = name; this.returnType = returnType; } public List> getParameterAnnotations() { return parameterAnnotations; } public List getParameterAnnotations(int index) { if (index >= parameterAnnotations.size()) { for (int i = parameterAnnotations.size(); i <= index; i++) { List annotationInfos = new ArrayList(); parameterAnnotations.add(i, annotationInfos); } } return parameterAnnotations.get(index); } public String getName() { return name; } public ClassInfo getDeclaringClass() { return declaringClass; } public String getReturnType() { return returnType; } public String toString() { return declaringClass + "@" + name; } } public class FieldInfo extends Annotatable implements Info { private final String name; private final String type; private final ClassInfo declaringClass; public FieldInfo(ClassInfo info, Field field){ super(field); this.declaringClass = info; this.name = field.getName(); this.type = field.getType().getName(); } public FieldInfo(ClassInfo declaringClass, String name, String type) { this.declaringClass = declaringClass; this.name = name; this.type = type; } public String getName() { return name; } public ClassInfo getDeclaringClass() { return declaringClass; } public String getType() { return type; } public String toString() { return declaringClass + "#" + name; } } public class AnnotationInfo extends Annotatable implements Info { private final String name; public AnnotationInfo(Annotation annotation){ this(annotation.getClass().getName()); } public AnnotationInfo(Class annotation) { this.name = annotation.getName().intern(); } public AnnotationInfo(String name) { name = name.replaceAll("^L|;$", ""); name = name.replace('/', '.'); this.name = name.intern(); } public String getName() { return name; } public String toString() { return name; } } public class InfoBuildingVisitor extends EmptyVisitor { private Info info; public InfoBuildingVisitor() { } public InfoBuildingVisitor(Info info) { this.info = info; } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (name.endsWith("package-info")) { info = new PackageInfo(javaName(name)); } else { ClassInfo classInfo = new ClassInfo(javaName(name), javaName(superName)); if (signature == null) { for (String interfce : interfaces) { classInfo.getInterfaces().add(javaName(interfce)); } } else { // the class uses generics new SignatureReader(signature).accept(new ClassFinder.GenericAwareInfoBuildingVisitor(ClassFinder.GenericAwareInfoBuildingVisitor.TYPE.CLASS, classInfo)); } info = classInfo; classInfos.add(classInfo); } } private String javaName(String name) { return (name == null)? null:name.replace('/', '.'); } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { AnnotationInfo annotationInfo = new AnnotationInfo(desc); info.getAnnotations().add(annotationInfo); getAnnotationInfos(annotationInfo.getName()).add(info); return new ClassFinder.InfoBuildingVisitor(annotationInfo); } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { ClassInfo classInfo = ((ClassInfo) info); FieldInfo fieldInfo = new FieldInfo(classInfo, name, desc); classInfo.getFields().add(fieldInfo); return new ClassFinder.InfoBuildingVisitor(fieldInfo); } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { ClassInfo classInfo = ((ClassInfo) info); MethodInfo methodInfo = new MethodInfo(classInfo, name, desc); classInfo.getMethods().add(methodInfo); return new ClassFinder.InfoBuildingVisitor(methodInfo); } public AnnotationVisitor visitParameterAnnotation(int param, String desc, boolean visible) { MethodInfo methodInfo = ((MethodInfo) info); List annotationInfos = methodInfo.getParameterAnnotations(param); AnnotationInfo annotationInfo = new AnnotationInfo(desc); annotationInfos.add(annotationInfo); return new ClassFinder.InfoBuildingVisitor(annotationInfo); } } public static class GenericAwareInfoBuildingVisitor implements SignatureVisitor { public enum TYPE { CLASS } public enum STATE { BEGIN, END, SUPERCLASS, INTERFACE, FORMAL_TYPE_PARAM } private Info info; private ClassFinder.GenericAwareInfoBuildingVisitor.TYPE type; private ClassFinder.GenericAwareInfoBuildingVisitor.STATE state; private static boolean debug = false; public GenericAwareInfoBuildingVisitor() { } public GenericAwareInfoBuildingVisitor(ClassFinder.GenericAwareInfoBuildingVisitor.TYPE type, Info info) { this.type = type; this.info = info; this.state = ClassFinder.GenericAwareInfoBuildingVisitor.STATE.BEGIN; } public void visitFormalTypeParameter(String s) { if (debug) System.out.println(" s=" + s); switch (state) { case BEGIN: ((ClassInfo) info).name += "<" + s; } state = ClassFinder.GenericAwareInfoBuildingVisitor.STATE.FORMAL_TYPE_PARAM; } public SignatureVisitor visitClassBound() { if (debug) System.out.println(" visitClassBound()"); return this; } public SignatureVisitor visitInterfaceBound() { if (debug) System.out.println(" visitInterfaceBound()"); return this; } public SignatureVisitor visitSuperclass() { if (debug) System.out.println(" visitSuperclass()"); state = ClassFinder.GenericAwareInfoBuildingVisitor.STATE.SUPERCLASS; return this; } public SignatureVisitor visitInterface() { if (debug) System.out.println(" visitInterface()"); ((ClassInfo) info).getInterfaces().add(""); state = ClassFinder.GenericAwareInfoBuildingVisitor.STATE.INTERFACE; return this; } public SignatureVisitor visitParameterType() { if (debug) System.out.println(" visitParameterType()"); return this; } public SignatureVisitor visitReturnType() { if (debug) System.out.println(" visitReturnType()"); return this; } public SignatureVisitor visitExceptionType() { if (debug) System.out.println(" visitExceptionType()"); return this; } public void visitBaseType(char c) { if (debug) System.out.println(" visitBaseType(" + c + ")"); } public void visitTypeVariable(String s) { if (debug) System.out.println(" visitTypeVariable(" + s + ")"); } public SignatureVisitor visitArrayType() { if (debug) System.out.println(" visitArrayType()"); return this; } public void visitClassType(String s) { if (debug) System.out.println(" visitClassType(" + s + ")"); switch (state) { case INTERFACE: List interfces = ((ClassInfo) info).getInterfaces(); int idx = interfces.size() - 1; String interfce = interfces.get(idx); if (interfce.length() == 0) { interfce = javaName(s); } else { interfce += javaName(s); } interfces.set(idx, interfce); break; case SUPERCLASS: if (!s.equals("java/lang/Object")) { ((ClassInfo) info).superType = javaName(s); } } } public void visitInnerClassType(String s) { if (debug) System.out.println(" visitInnerClassType(" + s + ")"); } public void visitTypeArgument() { if (debug) System.out.println(" visitTypeArgument()"); switch (state) { case INTERFACE: List interfces = ((ClassInfo) info).getInterfaces(); int idx = interfces.size() - 1; String interfce = interfces.get(idx); interfce += "<"; interfces.set(idx, interfce); } } public SignatureVisitor visitTypeArgument(char c) { if (debug) System.out.println(" visitTypeArgument(" + c + ")"); switch (state) { case INTERFACE: List interfces = ((ClassInfo) info).getInterfaces(); int idx = interfces.size() - 1; String interfce = interfces.get(idx); interfce += "<"; interfces.set(idx, interfce); } return this; } public void visitEnd() { if (debug) System.out.println(" visitEnd()"); switch (state) { case INTERFACE: List interfces = ((ClassInfo) info).getInterfaces(); int idx = interfces.size() - 1; String interfce = interfces.get(idx); interfce += ">"; interfces.set(idx, interfce); break; case FORMAL_TYPE_PARAM: String name = ((ClassInfo) info).name; if (name.contains("<")) { ((ClassInfo) info).name += ">"; } } state = ClassFinder.GenericAwareInfoBuildingVisitor.STATE.END; } private String javaName(String name) { return (name == null)? null:name.replace('/', '.'); } } } xbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/BundleAssignableClassFinder.java0000644000175000017500000002416511370414213032115 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.xbean.osgi.bundle.util.BundleClassFinder; import org.apache.xbean.osgi.bundle.util.BundleDescription; import org.apache.xbean.osgi.bundle.util.ClassDiscoveryFilter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.osgi.framework.Bundle; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version $Rev: 941557 $ $Date: 2010-05-06 03:16:59 +0200 (jeu. 06 mai 2010) $ */ public class BundleAssignableClassFinder extends BundleClassFinder { private static final Logger logger = LoggerFactory.getLogger(BundleAssignableClassFinder.class); private Class[] clses; private Set targetClassNames = new HashSet(); private Set targetInterfaceNames = new HashSet(); private Set wiredImportedPackageNames = new HashSet(); /** * Create a new BundleClassFinder, it will search all the classes based the rule defined by the parameters via ASM tool * @param packageAdmin * @param bundle * @param clses * @param discoveryFilter */ public BundleAssignableClassFinder(PackageAdmin packageAdmin, Bundle bundle, Class[] clses, ClassDiscoveryFilter discoveryFilter) { super(packageAdmin, bundle, discoveryFilter); if (clses == null || clses.length == 0) { throw new IllegalArgumentException("At least one class or interface should be specified"); } this.clses = clses; for (Class cls : clses) { String asmStyleName = cls.getName().replace('.', '/'); if (cls.isInterface()) { targetInterfaceNames.add(asmStyleName); } else { targetClassNames.add(asmStyleName); } } initialize(); } public BundleAssignableClassFinder(PackageAdmin packageAdmin, Class[] clses, Bundle bundle) { this(packageAdmin, bundle, clses, FULL_CLASS_DISCOVERY_FILTER); } @Override protected BundleClassFinder createSubBundleClassFinder(PackageAdmin packageAdmin, Bundle bundle, ClassDiscoveryFilter classDiscoveryFilter) { return new BundleAssignableClassFinder(packageAdmin, bundle, clses, classDiscoveryFilter); } @Override protected boolean isClassAcceptable(String name, InputStream in) throws IOException { ClassReader classReader = new ClassReader(in); String className = classReader.getClassName(); if ((classReader.getAccess() & Opcodes.ACC_INTERFACE) == 0) { if (targetClassNames.contains(className)) { return true; } } else { if (targetInterfaceNames.contains(className)) { return true; } } String[] interfaceNames = classReader.getInterfaces(); try { for (String interfaceName : interfaceNames) { if (wiredImportedPackageNames.contains(toASMStylePackageName(interfaceName))) { return isClassAssignable(bundle.loadClass(toJavaStyleClassName(interfaceName))); } else { if (isInterfaceAssignable(interfaceName)) { return true; } } } String superClassName = classReader.getSuperName(); if (wiredImportedPackageNames.contains(toASMStylePackageName(superClassName))) { return isClassAssignable(bundle.loadClass(toJavaStyleClassName(superClassName))); } return isSuperClassAssignable(superClassName); } catch (ClassNotFoundException e) { return false; } } @Override protected boolean isClassAcceptable(URL url) { InputStream in = null; try { in = url.openStream(); return isClassAcceptable("", in); } catch (IOException e) { logger.warn("Unable to check the class of url " + url, e); return false; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } private void initialize() { BundleDescription description = new BundleDescription(bundle.getHeaders()); List imports = description.getExternalImports(); for (BundleDescription.ImportPackage packageImport : imports) { String packageName = packageImport.getName(); ExportedPackage[] exports = packageAdmin.getExportedPackages(packageName); Bundle wiredBundle = isWired(bundle, exports); if (wiredBundle != null) { wiredImportedPackageNames.add(packageName.replace('.', '/')); break; } } } private boolean isClassAssignable(Class cls) { for (Class targetClass : clses) { if (targetClass.isAssignableFrom(cls)) { return true; } } return false; } /** * * @param interfaceName The interface name should be in the format of org/test/SimpleInterface * @return return true if the method parameter interfaceName is assignable to any interface in the expected interfaces */ private boolean isInterfaceAssignable(String interfaceName) { //Check each interface in interfaceNames set if (targetInterfaceNames.contains(interfaceName)) { return true; } //Check ancestor intefaces URL url = bundle.getResource("/" + interfaceName + ".class"); if (url == null) { //TODO what should we do if we do not find the interface ? return false; } InputStream in = null; try { in = url.openStream(); ClassReader classReader = new ClassReader(in); String[] superInterfaceNames = classReader.getInterfaces(); for (String superInterfaceName : superInterfaceNames) { if (isInterfaceAssignable(superInterfaceName)) { return true; } } return false; } catch (IOException e) { logger.warn("Unable to check the interface " + interfaceName, e); return false; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } /** * * @param superClassName The super class name should be in the format of org/test/SimpleClass * @return return true if the method parameter superClassName is assignable to any interface in the expected interfaces or any class in the expected classes */ private boolean isSuperClassAssignable(String superClassName) { if (targetClassNames.contains(superClassName)) { return true; } //Check parent class URL url = bundle.getResource("/" + superClassName + ".class"); if (url == null) { //TODO what should we do if we do not find the super class ? return false; } InputStream in = null; try { in = url.openStream(); ClassReader classReader = new ClassReader(in); String[] superInterfaceNames = classReader.getInterfaces(); //Check interfaces for (String superInterfaceName : superInterfaceNames) { if (isInterfaceAssignable(superInterfaceName)) { return true; } } //Check className if (classReader.getSuperName().equals("java/lang/Object")) { return targetClassNames.contains("java/lang/Object"); } else { return isSuperClassAssignable(classReader.getSuperName()); } } catch (IOException e) { logger.warn("Unable to check the super class " + superClassName, e); return false; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } /** * Get the ASM style package name from the parameter className. * If the className is ended with .class extension, e.g. /org/apache/geronimo/TestCass.class or org.apache.geronimo.TestClass.class, * then org/apache/geronimo is returned * If the className is not ended with .class extension, e.g. /org/apache/geronimo/TestCass or org.apache.geronimo.TestClass, * then org/apache/geronimo is returned * @param className * @return ASM style package name, should be in the format of "org/apache/geronimo" */ protected String toASMStylePackageName(String className) { if (className.endsWith(EXT)) { className = className.substring(0, className.length() - EXT.length()); } className = className.replace('.', '/'); int iLastDotIndex = className.lastIndexOf('/'); if (iLastDotIndex != -1) { return className.substring(0, iLastDotIndex); } else { return ""; } } } xbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/BundleAnnotationFinder.java0000644000175000017500000000514511371713051031171 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.finder; import java.io.InputStream; import java.net.URL; import java.util.zip.ZipEntry; import org.apache.xbean.osgi.bundle.util.BundleResourceFinder; import org.apache.xbean.osgi.bundle.util.ResourceDiscoveryFilter; import org.osgi.framework.Bundle; import org.osgi.service.packageadmin.PackageAdmin; /** * @version $Rev: 942659 $ $Date: 2010-05-10 07:14:17 +0200 (lun. 10 mai 2010) $ */ public class BundleAnnotationFinder extends AbstractFinder { private final Bundle bundle; public BundleAnnotationFinder(PackageAdmin packageAdmin, Bundle bundle) throws Exception { this(packageAdmin, bundle, BundleResourceFinder.FULL_DISCOVERY_FILTER); } public BundleAnnotationFinder(PackageAdmin packageAdmin, Bundle bundle, ResourceDiscoveryFilter discoveryFilter) throws Exception { this.bundle = bundle; BundleResourceFinder bundleResourceFinder = new BundleResourceFinder(packageAdmin, bundle, "", ".class", discoveryFilter); bundleResourceFinder.find(new AnnotationFindingCallback()); } @Override protected URL getResource(String s) { return bundle.getResource(s); } @Override protected Class loadClass(String s) throws ClassNotFoundException { return bundle.loadClass(s); } private class AnnotationFindingCallback implements BundleResourceFinder.ResourceFinderCallback { public void foundInDirectory(Bundle bundle, String baseDir, URL url) throws Exception { InputStream in = url.openStream(); try { readClassDef(in); } finally { in.close(); } } public void foundInJar(Bundle bundle, String jarName, ZipEntry entry, InputStream in) throws Exception { readClassDef(in); } } } xbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/ResourceFinder.java0000644000175000017500000012126211363706454027525 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author David Blevins * @version $Rev: 936567 $ $Date: 2010-04-22 01:41:32 +0200 (jeu. 22 avril 2010) $ */ public class ResourceFinder { private final URL[] urls; private final String path; private final ClassLoader classLoader; private final List resourcesNotLoaded = new ArrayList(); public ResourceFinder(URL... urls) { this(null, Thread.currentThread().getContextClassLoader(), urls); } public ResourceFinder(String path) { this(path, Thread.currentThread().getContextClassLoader(), null); } public ResourceFinder(String path, URL... urls) { this(path, Thread.currentThread().getContextClassLoader(), urls); } public ResourceFinder(String path, ClassLoader classLoader) { this(path, classLoader, null); } public ResourceFinder(String path, ClassLoader classLoader, URL... urls) { if (path == null){ path = ""; } else if (path.length() > 0 && !path.endsWith("/")) { path += "/"; } this.path = path; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } this.classLoader = classLoader; for (int i = 0; urls != null && i < urls.length; i++) { URL url = urls[i]; if (url == null || isDirectory(url) || url.getProtocol().equals("jar")) { continue; } try { urls[i] = new URL("jar", "", -1, url.toString() + "!/"); } catch (MalformedURLException e) { } } this.urls = (urls == null || urls.length == 0)? null : urls; } private static boolean isDirectory(URL url) { String file = url.getFile(); return (file.length() > 0 && file.charAt(file.length() - 1) == '/'); } /** * Returns a list of resources that could not be loaded in the last invoked findAvailable* or * mapAvailable* methods. *

* The list will only contain entries of resources that match the requirements * of the last invoked findAvailable* or mapAvailable* methods, but were unable to be * loaded and included in their results. *

* The list returned is unmodifiable and the results of this method will change * after each invocation of a findAvailable* or mapAvailable* methods. *

* This method is not thread safe. */ public List getResourcesNotLoaded() { return Collections.unmodifiableList(resourcesNotLoaded); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public URL find(String uri) throws IOException { String fullUri = path + uri; URL resource = getResource(fullUri); if (resource == null) { throw new IOException("Could not find resource '" + fullUri + "'"); } return resource; } public List findAll(String uri) throws IOException { String fullUri = path + uri; Enumeration resources = getResources(fullUri); List list = new ArrayList(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); list.add(url); } return list; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find String // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Reads the contents of the URL as a {@link String}'s and returns it. * * @param uri * @return a stringified content of a resource * @throws IOException if a resource pointed out by the uri param could not be find * @see ClassLoader#getResource(String) */ public String findString(String uri) throws IOException { String fullUri = path + uri; URL resource = getResource(fullUri); if (resource == null) { throw new IOException("Could not find a resource in : " + fullUri); } return readContents(resource); } /** * Reads the contents of the found URLs as a list of {@link String}'s and returns them. * * @param uri * @return a list of the content of each resource URL found * @throws IOException if any of the found URLs are unable to be read. */ public List findAllStrings(String uri) throws IOException { String fulluri = path + uri; List strings = new ArrayList(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { URL url = resources.nextElement(); String string = readContents(url); strings.add(string); } return strings; } /** * Reads the contents of the found URLs as a Strings and returns them. * Individual URLs that cannot be read are skipped and added to the * list of 'resourcesNotLoaded' * * @param uri * @return a list of the content of each resource URL found * @throws IOException if classLoader.getResources throws an exception */ public List findAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); String fulluri = path + uri; List strings = new ArrayList(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { String string = readContents(url); strings.add(string); } catch (IOException notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return strings; } /** * Reads the contents of all non-directory URLs immediately under the specified * location and returns them in a map keyed by the file name. *

* Any URLs that cannot be read will cause an exception to be thrown. *

* Example classpath: *

* META-INF/serializables/one * META-INF/serializables/two * META-INF/serializables/three * META-INF/serializables/four/foo.txt *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAvailableStrings("serializables"); * map.contains("one"); // true * map.contains("two"); // true * map.contains("three"); // true * map.contains("four"); // false * * @param uri * @return a list of the content of each resource URL found * @throws IOException if any of the urls cannot be read */ public Map mapAllStrings(String uri) throws IOException { Map strings = new HashMap(); Map resourcesMap = getResourcesMap(uri); for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); URL url = (URL) entry.getValue(); String value = readContents(url); strings.put(name, value); } return strings; } /** * Reads the contents of all non-directory URLs immediately under the specified * location and returns them in a map keyed by the file name. *

* Individual URLs that cannot be read are skipped and added to the * list of 'resourcesNotLoaded' *

* Example classpath: *

* META-INF/serializables/one * META-INF/serializables/two # not readable * META-INF/serializables/three * META-INF/serializables/four/foo.txt *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAvailableStrings("serializables"); * map.contains("one"); // true * map.contains("two"); // false * map.contains("three"); // true * map.contains("four"); // false * * @param uri * @return a list of the content of each resource URL found * @throws IOException if classLoader.getResources throws an exception */ public Map mapAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); Map strings = new HashMap(); Map resourcesMap = getResourcesMap(uri); for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); URL url = (URL) entry.getValue(); try { String value = readContents(url); strings.put(name, value); } catch (IOException notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return strings; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Class // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Executes {@link #findString(String)} assuming the contents URL found is the name of * a class that should be loaded and returned. * * @param uri * @return * @throws IOException * @throws ClassNotFoundException */ public Class findClass(String uri) throws IOException, ClassNotFoundException { String className = findString(uri); return (Class) classLoader.loadClass(className); } /** * Executes findAllStrings assuming the strings are * the names of a classes that should be loaded and returned. *

* Any URL or class that cannot be loaded will cause an exception to be thrown. * * @param uri * @return * @throws IOException * @throws ClassNotFoundException */ public List findAllClasses(String uri) throws IOException, ClassNotFoundException { List classes = new ArrayList(); List strings = findAllStrings(uri); for (String className : strings) { Class clazz = classLoader.loadClass(className); classes.add(clazz); } return classes; } /** * Executes findAvailableStrings assuming the strings are * the names of a classes that should be loaded and returned. *

* Any class that cannot be loaded will be skipped and placed in the * 'resourcesNotLoaded' collection. * * @param uri * @return * @throws IOException if classLoader.getResources throws an exception */ public List findAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); List classes = new ArrayList(); List strings = findAvailableStrings(uri); for (String className : strings) { try { Class clazz = classLoader.loadClass(className); classes.add(clazz); } catch (Exception notAvailable) { resourcesNotLoaded.add(className); } } return classes; } /** * Executes mapAllStrings assuming the value of each entry in the * map is the name of a class that should be loaded. *

* Any class that cannot be loaded will be cause an exception to be thrown. *

* Example classpath: *

* META-INF/xmlparsers/xerces * META-INF/xmlparsers/crimson *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAvailableStrings("xmlparsers"); * map.contains("xerces"); // true * map.contains("crimson"); // true * Class xercesClass = map.get("xerces"); * Class crimsonClass = map.get("crimson"); * * @param uri * @return * @throws IOException * @throws ClassNotFoundException */ public Map mapAllClasses(String uri) throws IOException, ClassNotFoundException { Map classes = new HashMap(); Map map = mapAllStrings(uri); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); String className = (String) entry.getValue(); Class clazz = classLoader.loadClass(className); classes.put(string, clazz); } return classes; } /** * Executes mapAvailableStrings assuming the value of each entry in the * map is the name of a class that should be loaded. *

* Any class that cannot be loaded will be skipped and placed in the * 'resourcesNotLoaded' collection. *

* Example classpath: *

* META-INF/xmlparsers/xerces * META-INF/xmlparsers/crimson *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAvailableStrings("xmlparsers"); * map.contains("xerces"); // true * map.contains("crimson"); // true * Class xercesClass = map.get("xerces"); * Class crimsonClass = map.get("crimson"); * * @param uri * @return * @throws IOException if classLoader.getResources throws an exception */ public Map mapAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); Map classes = new HashMap(); Map map = mapAvailableStrings(uri); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); String className = (String) entry.getValue(); try { Class clazz = classLoader.loadClass(className); classes.put(string, clazz); } catch (Exception notAvailable) { resourcesNotLoaded.add(className); } } return classes; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Implementation // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Assumes the class specified points to a file in the classpath that contains * the name of a class that implements or is a subclass of the specfied class. *

* Any class that cannot be loaded will be cause an exception to be thrown. *

* Example classpath: *

* META-INF/java.io.InputStream # contains the classname org.acme.AcmeInputStream * META-INF/java.io.OutputStream *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Class clazz = finder.findImplementation(java.io.InputStream.class); * clazz.getName(); // returns "org.acme.AcmeInputStream" * * @param interfase a superclass or interface * @return * @throws IOException if the URL cannot be read * @throws ClassNotFoundException if the class found is not loadable * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public Class findImplementation(Class interfase) throws IOException, ClassNotFoundException { String className = findString(interfase.getName()); Class impl = classLoader.loadClass(className); if (!interfase.isAssignableFrom(impl)) { throw new ClassCastException("Class not of type: " + interfase.getName()); } return impl; } /** * Assumes the class specified points to a file in the classpath that contains * the name of a class that implements or is a subclass of the specfied class. *

* Any class that cannot be loaded or assigned to the specified interface will be cause * an exception to be thrown. *

* Example classpath: *

* META-INF/java.io.InputStream # contains the classname org.acme.AcmeInputStream * META-INF/java.io.InputStream # contains the classname org.widget.NeatoInputStream * META-INF/java.io.InputStream # contains the classname com.foo.BarInputStream *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List classes = finder.findAllImplementations(java.io.InputStream.class); * classes.contains("org.acme.AcmeInputStream"); // true * classes.contains("org.widget.NeatoInputStream"); // true * classes.contains("com.foo.BarInputStream"); // true * * @param interfase a superclass or interface * @return * @throws IOException if the URL cannot be read * @throws ClassNotFoundException if the class found is not loadable * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public List findAllImplementations(Class interfase) throws IOException, ClassNotFoundException { List implementations = new ArrayList(); List strings = findAllStrings(interfase.getName()); for (String className : strings) { Class impl = classLoader.loadClass(className); if (!interfase.isAssignableFrom(impl)) { throw new ClassCastException("Class not of type: " + interfase.getName()); } implementations.add(impl); } return implementations; } /** * Assumes the class specified points to a file in the classpath that contains * the name of a class that implements or is a subclass of the specfied class. *

* Any class that cannot be loaded or are not assignable to the specified class will be * skipped and placed in the 'resourcesNotLoaded' collection. *

* Example classpath: *

* META-INF/java.io.InputStream # contains the classname org.acme.AcmeInputStream * META-INF/java.io.InputStream # contains the classname org.widget.NeatoInputStream * META-INF/java.io.InputStream # contains the classname com.foo.BarInputStream *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List classes = finder.findAllImplementations(java.io.InputStream.class); * classes.contains("org.acme.AcmeInputStream"); // true * classes.contains("org.widget.NeatoInputStream"); // true * classes.contains("com.foo.BarInputStream"); // true * * @param interfase a superclass or interface * @return * @throws IOException if classLoader.getResources throws an exception */ public List findAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); List implementations = new ArrayList(); List strings = findAvailableStrings(interfase.getName()); for (String className : strings) { try { Class impl = classLoader.loadClass(className); if (interfase.isAssignableFrom(impl)) { implementations.add(impl); } else { resourcesNotLoaded.add(className); } } catch (Exception notAvailable) { resourcesNotLoaded.add(className); } } return implementations; } /** * Assumes the class specified points to a directory in the classpath that holds files * containing the name of a class that implements or is a subclass of the specfied class. *

* Any class that cannot be loaded or assigned to the specified interface will be cause * an exception to be thrown. *

* Example classpath: *

* META-INF/java.net.URLStreamHandler/jar * META-INF/java.net.URLStreamHandler/file * META-INF/java.net.URLStreamHandler/http *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAllImplementations(java.net.URLStreamHandler.class); * Class jarUrlHandler = map.get("jar"); * Class fileUrlHandler = map.get("file"); * Class httpUrlHandler = map.get("http"); * * @param interfase a superclass or interface * @return * @throws IOException if the URL cannot be read * @throws ClassNotFoundException if the class found is not loadable * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public Map mapAllImplementations(Class interfase) throws IOException, ClassNotFoundException { Map implementations = new HashMap(); Map map = mapAllStrings(interfase.getName()); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); String className = (String) entry.getValue(); Class impl = classLoader.loadClass(className); if (!interfase.isAssignableFrom(impl)) { throw new ClassCastException("Class not of type: " + interfase.getName()); } implementations.put(string, impl); } return implementations; } /** * Assumes the class specified points to a directory in the classpath that holds files * containing the name of a class that implements or is a subclass of the specfied class. *

* Any class that cannot be loaded or are not assignable to the specified class will be * skipped and placed in the 'resourcesNotLoaded' collection. *

* Example classpath: *

* META-INF/java.net.URLStreamHandler/jar * META-INF/java.net.URLStreamHandler/file * META-INF/java.net.URLStreamHandler/http *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Map map = finder.mapAllImplementations(java.net.URLStreamHandler.class); * Class jarUrlHandler = map.get("jar"); * Class fileUrlHandler = map.get("file"); * Class httpUrlHandler = map.get("http"); * * @param interfase a superclass or interface * @return * @throws IOException if classLoader.getResources throws an exception */ public Map mapAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); Map implementations = new HashMap(); Map map = mapAvailableStrings(interfase.getName()); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); String className = (String) entry.getValue(); try { Class impl = classLoader.loadClass(className); if (interfase.isAssignableFrom(impl)) { implementations.put(string, impl); } else { resourcesNotLoaded.add(className); } } catch (Exception notAvailable) { resourcesNotLoaded.add(className); } } return implementations; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Properties // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Finds the corresponding resource and reads it in as a properties file *

* Example classpath: *

* META-INF/widget.properties *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * Properties widgetProps = finder.findProperties("widget.properties"); * * @param uri * @return * @throws IOException if the URL cannot be read or is not in properties file format */ public Properties findProperties(String uri) throws IOException { String fulluri = path + uri; URL resource = getResource(fulluri); if (resource == null) { throw new IOException("Could not find resource: " + fulluri); } return loadProperties(resource); } /** * Finds the corresponding resources and reads them in as a properties files *

* Any URL that cannot be read in as a properties file will cause an exception to be thrown. *

* Example classpath: *

* META-INF/app.properties * META-INF/app.properties * META-INF/app.properties *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List appProps = finder.findAllProperties("app.properties"); * * @param uri * @return * @throws IOException if the URL cannot be read or is not in properties file format */ public List findAllProperties(String uri) throws IOException { String fulluri = path + uri; List properties = new ArrayList(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { URL url = resources.nextElement(); Properties props = loadProperties(url); properties.add(props); } return properties; } /** * Finds the corresponding resources and reads them in as a properties files *

* Any URL that cannot be read in as a properties file will be added to the * 'resourcesNotLoaded' collection. *

* Example classpath: *

* META-INF/app.properties * META-INF/app.properties * META-INF/app.properties *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List appProps = finder.findAvailableProperties("app.properties"); * * @param uri * @return * @throws IOException if classLoader.getResources throws an exception */ public List findAvailableProperties(String uri) throws IOException { resourcesNotLoaded.clear(); String fulluri = path + uri; List properties = new ArrayList(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { Properties props = loadProperties(url); properties.add(props); } catch (Exception notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return properties; } /** * Finds the corresponding resources and reads them in as a properties files *

* Any URL that cannot be read in as a properties file will cause an exception to be thrown. *

* Example classpath: *

* META-INF/jdbcDrivers/oracle.properties * META-INF/jdbcDrivers/mysql.props * META-INF/jdbcDrivers/derby *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List driversList = finder.findAvailableProperties("jdbcDrivers"); * Properties oracleProps = driversList.get("oracle.properties"); * Properties mysqlProps = driversList.get("mysql.props"); * Properties derbyProps = driversList.get("derby"); * * @param uri * @return * @throws IOException if the URL cannot be read or is not in properties file format */ public Map mapAllProperties(String uri) throws IOException { Map propertiesMap = new HashMap(); Map map = getResourcesMap(uri); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); URL url = (URL) entry.getValue(); Properties properties = loadProperties(url); propertiesMap.put(string, properties); } return propertiesMap; } /** * Finds the corresponding resources and reads them in as a properties files *

* Any URL that cannot be read in as a properties file will be added to the * 'resourcesNotLoaded' collection. *

* Example classpath: *

* META-INF/jdbcDrivers/oracle.properties * META-INF/jdbcDrivers/mysql.props * META-INF/jdbcDrivers/derby *

* ResourceFinder finder = new ResourceFinder("META-INF/"); * List driversList = finder.findAvailableProperties("jdbcDrivers"); * Properties oracleProps = driversList.get("oracle.properties"); * Properties mysqlProps = driversList.get("mysql.props"); * Properties derbyProps = driversList.get("derby"); * * @param uri * @return * @throws IOException if classLoader.getResources throws an exception */ public Map mapAvailableProperties(String uri) throws IOException { resourcesNotLoaded.clear(); Map propertiesMap = new HashMap(); Map map = getResourcesMap(uri); for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String string = (String) entry.getKey(); URL url = (URL) entry.getValue(); try { Properties properties = loadProperties(url); propertiesMap.put(string, properties); } catch (Exception notAvailable) { resourcesNotLoaded.add(url.toExternalForm()); } } return propertiesMap; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Map Resources // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public Map getResourcesMap(String uri) throws IOException { String basePath = path + uri; Map resources = new HashMap(); if (!basePath.endsWith("/")) { basePath += "/"; } Enumeration urls = getResources(basePath); while (urls.hasMoreElements()) { URL location = urls.nextElement(); try { if (location.getProtocol().equals("jar")) { readJarEntries(location, basePath, resources); } else if (location.getProtocol().equals("file")) { readDirectoryEntries(location, resources); } } catch (Exception e) { } } return resources; } private static void readDirectoryEntries(URL location, Map resources) throws MalformedURLException { File dir = new File(URLDecoder.decode(location.getPath())); if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File file : files) { if (!file.isDirectory()) { String name = file.getName(); URL url = file.toURI().toURL(); resources.put(name, url); } } } } private static void readJarEntries(URL location, String basePath, Map resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); JarFile jarfile = null; jarfile = conn.getJarFile(); Enumeration entries = jarfile.entries(); while (entries != null && entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (entry.isDirectory() || !name.startsWith(basePath) || name.length() == basePath.length()) { continue; } name = name.substring(basePath.length()); if (name.contains("/")) { continue; } URL resource = new URL(location, name); resources.put(name, resource); } } private Properties loadProperties(URL resource) throws IOException { InputStream in = resource.openStream(); BufferedInputStream reader = null; try { reader = new BufferedInputStream(in); Properties properties = new Properties(); properties.load(reader); return properties; } finally { try { in.close(); reader.close(); } catch (Exception e) { } } } private String readContents(URL resource) throws IOException { InputStream in = resource.openStream(); BufferedInputStream reader = null; StringBuffer sb = new StringBuffer(); try { reader = new BufferedInputStream(in); int b = reader.read(); while (b != -1) { sb.append((char) b); b = reader.read(); } return sb.toString().trim(); } finally { try { in.close(); reader.close(); } catch (Exception e) { } } } private URL getResource(String fullUri) { if (urls == null){ return classLoader.getResource(fullUri); } return findResource(fullUri, urls); } private Enumeration getResources(String fulluri) throws IOException { if (urls == null) { return classLoader.getResources(fulluri); } Vector resources = new Vector(); for (URL url : urls) { URL resource = findResource(fulluri, url); if (resource != null){ resources.add(resource); } } return resources.elements(); } private URL findResource(String resourceName, URL... search) { for (int i = 0; i < search.length; i++) { URL currentUrl = search[i]; if (currentUrl == null) { continue; } try { String protocol = currentUrl.getProtocol(); if (protocol.equals("jar")) { /* * If the connection for currentUrl or resURL is * used, getJarFile() will throw an exception if the * entry doesn't exist. */ URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL(); JarFile jarFile; JarURLConnection juc; try { juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection(); jarFile = juc.getJarFile(); } catch (IOException e) { // Don't look for this jar file again search[i] = null; throw e; } try { juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection(); jarFile = juc.getJarFile(); String entryName; if (currentUrl.getFile().endsWith("!/")) { entryName = resourceName; } else { String file = currentUrl.getFile(); int sepIdx = file.lastIndexOf("!/"); if (sepIdx == -1) { // Invalid URL, don't look here again search[i] = null; continue; } sepIdx += 2; StringBuffer sb = new StringBuffer(file.length() - sepIdx + resourceName.length()); sb.append(file.substring(sepIdx)); sb.append(resourceName); entryName = sb.toString(); } if (entryName.equals("META-INF/") && jarFile.getEntry("META-INF/MANIFEST.MF") != null) { return targetURL(currentUrl, "META-INF/MANIFEST.MF"); } if (jarFile.getEntry(entryName) != null) { return targetURL(currentUrl, resourceName); } } finally { if (!juc.getUseCaches()) { try { jarFile.close(); } catch (Exception e) { } } } } else if (protocol.equals("file")) { String baseFile = currentUrl.getFile(); String host = currentUrl.getHost(); int hostLength = 0; if (host != null) { hostLength = host.length(); } StringBuffer buf = new StringBuffer(2 + hostLength + baseFile.length() + resourceName.length()); if (hostLength > 0) { buf.append("//").append(host); } // baseFile always ends with '/' buf.append(baseFile); String fixedResName = resourceName; // Do not create a UNC path, i.e. \\host while (fixedResName.startsWith("/") || fixedResName.startsWith("\\")) { fixedResName = fixedResName.substring(1); } buf.append(fixedResName); String filename = buf.toString(); File file = new File(filename); File file2 = new File(URLDecoder.decode(filename)); if (file.exists() || file2.exists()) { return targetURL(currentUrl, fixedResName); } } else { URL resourceURL = targetURL(currentUrl, resourceName); URLConnection urlConnection = resourceURL.openConnection(); try { urlConnection.getInputStream().close(); } catch (SecurityException e) { return null; } // HTTP can return a stream on a non-existent file // So check for the return code; if (!resourceURL.getProtocol().equals("http")) { return resourceURL; } int code = ((HttpURLConnection) urlConnection).getResponseCode(); if (code >= 200 && code < 300) { return resourceURL; } } } catch (MalformedURLException e) { // Keep iterating through the URL list } catch (IOException e) { } catch (SecurityException e) { } } return null; } private URL targetURL(URL base, String name) throws MalformedURLException { StringBuffer sb = new StringBuffer(base.getFile().length() + name.length()); sb.append(base.getFile()); sb.append(name); String file = sb.toString(); return new URL(base.getProtocol(), base.getHost(), base.getPort(), file, null); } } xbean-3.7/xbean-finder/src/main/java/org/apache/xbean/finder/ClassFinder.java0000644000175000017500000002357511350224046026777 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; /** * ClassFinder searches the classpath of the specified classloader for * packages, classes, constructors, methods, or fields with specific annotations. * * For security reasons ASM is used to find the annotations. Classes are not * loaded unless they match the requirements of a called findAnnotated* method. * Once loaded, these classes are cached. * * The getClassesNotLoaded() method can be used immediately after any find* * method to get a list of classes which matched the find requirements (i.e. * contained the annotation), but were unable to be loaded. * * @author David Blevins * @version $Rev: 924423 $ $Date: 2010-03-17 20:06:14 +0100 (mer. 17 mars 2010) $ */ public class ClassFinder extends AbstractFinder { private final ClassLoader classLoader; /** * Creates a ClassFinder that will search the urls in the specified classloader * excluding the urls in the classloader's parent. * * To include the parent classloader, use: * * new ClassFinder(classLoader, false); * * To exclude the parent's parent, use: * * new ClassFinder(classLoader, classLoader.getParent().getParent()); * * @param classLoader source of classes to scan * @throws Exception if something goes wrong */ public ClassFinder(ClassLoader classLoader) throws Exception { this(classLoader, true); } /** * Creates a ClassFinder that will search the urls in the specified classloader. * * @param classLoader source of classes to scan * @param excludeParent Allegedly excludes classes from parent classloader, whatever that might mean * @throws Exception if something goes wrong. */ public ClassFinder(ClassLoader classLoader, boolean excludeParent) throws Exception { this(classLoader, getUrls(classLoader, excludeParent)); } /** * Creates a ClassFinder that will search the urls in the specified classloader excluding * the urls in the 'exclude' classloader. * * @param classLoader source of classes to scan * @param exclude source of classes to exclude from scanning * @throws Exception if something goes wrong */ public ClassFinder(ClassLoader classLoader, ClassLoader exclude) throws Exception { this(classLoader, getUrls(classLoader, exclude)); } public ClassFinder(ClassLoader classLoader, URL url) { this(classLoader, Arrays.asList(url)); } public ClassFinder(ClassLoader classLoader, Collection urls) { this.classLoader = classLoader; List classNames = new ArrayList(); for (URL location : urls) { try { if (location.getProtocol().equals("jar")) { classNames.addAll(jar(location)); } else if (location.getProtocol().equals("file")) { try { // See if it's actually a jar URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/"); JarURLConnection juc = (JarURLConnection) jarUrl.openConnection(); juc.getJarFile(); classNames.addAll(jar(jarUrl)); } catch (IOException e) { classNames.addAll(file(location)); } } } catch (Exception e) { e.printStackTrace(); } } for (String className : classNames) { readClassDef(className); } } public ClassFinder(Class... classes){ this(Arrays.asList(classes)); } public ClassFinder(List classes){ this.classLoader = null; List infos = new ArrayList(); List packages = new ArrayList(); for (Class clazz : classes) { try { Package aPackage = clazz.getPackage(); if (aPackage != null && !packages.contains(aPackage)){ infos.add(new PackageInfo(aPackage)); packages.add(aPackage); } ClassInfo classInfo = new ClassInfo(clazz); infos.add(classInfo); classInfos.add(classInfo); for (Method method : clazz.getDeclaredMethods()) { infos.add(new MethodInfo(classInfo, method)); } for (Constructor constructor : clazz.getConstructors()) { infos.add(new MethodInfo(classInfo, constructor)); } for (Field field : clazz.getDeclaredFields()) { infos.add(new FieldInfo(classInfo, field)); } } catch (NoClassDefFoundError e) { throw new NoClassDefFoundError("Could not fully load class: " + clazz.getName() + "\n due to:" + e.getMessage() + "\n in classLoader: \n" + clazz.getClassLoader()); } } for (Info info : infos) { for (AnnotationInfo annotation : info.getAnnotations()) { List annotationInfos = getAnnotationInfos(annotation.getName()); annotationInfos.add(info); } } } private static Collection getUrls(ClassLoader classLoader, boolean excludeParent) throws IOException { return getUrls(classLoader, excludeParent? classLoader.getParent() : null); } private static Collection getUrls(ClassLoader classLoader, ClassLoader excludeParent) throws IOException { UrlSet urlSet = new UrlSet(classLoader); if (excludeParent != null){ urlSet = urlSet.exclude(excludeParent); } return urlSet.getUrls(); } @Override protected URL getResource(String className) { return classLoader.getResource(className); } @Override protected Class loadClass(String fixedName) throws ClassNotFoundException { return classLoader.loadClass(fixedName); } private List file(URL location) { List classNames = new ArrayList(); File dir = new File(URLDecoder.decode(location.getPath())); if (dir.getName().equals("META-INF")) { dir = dir.getParentFile(); // Scrape "META-INF" off } if (dir.isDirectory()) { scanDir(dir, classNames, ""); } return classNames; } private void scanDir(File dir, List classNames, String packageName) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { scanDir(file, classNames, packageName + file.getName() + "."); } else if (file.getName().endsWith(".class")) { String name = file.getName(); name = name.replaceFirst(".class$", ""); if (name.contains(".")) continue; classNames.add(packageName + name); } } } private List jar(URL location) throws IOException { String jarPath = location.getFile(); if (jarPath.indexOf("!") > -1){ jarPath = jarPath.substring(0, jarPath.indexOf("!")); } URL url = new URL(jarPath); InputStream in = url.openStream(); try { JarInputStream jarStream = new JarInputStream(in); return jar(jarStream); } finally { in.close(); } } private List jar(JarInputStream jarStream) throws IOException { List classNames = new ArrayList(); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } String className = entry.getName(); className = className.replaceFirst(".class$", ""); if (className.contains(".")) continue; className = className.replace('/', '.'); classNames.add(className); } return classNames; } protected void readClassDef(String className) { if (!className.endsWith(".class")) { className = className.replace('.', '/') + ".class"; } try { URL resource = getResource(className); if (resource != null) { InputStream in = resource.openStream(); try { readClassDef(in); } finally { in.close(); } } else { new Exception("Could not load " + className).printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } xbean-3.7/xbean-finder/src/test/0000755000175000017500000000000011610661037016465 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/0000755000175000017500000000000011610661037020477 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/0000755000175000017500000000000011610661037021637 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/java.io.InputStream0000644000175000017500000000001410521607162025355 0ustar drazzibdrazziborg.acme.Onexbean-3.7/xbean-finder/src/test/resources/META-INF/javax.naming.spi.ObjectFactory/0000755000175000017500000000000011610661037027547 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/javax.naming.spi.ObjectFactory/ldap0000644000175000017500000000003610521607162030410 0ustar drazzibdrazziborg.acme.ldapURLContextFactoryxbean-3.7/xbean-finder/src/test/resources/META-INF/javax.naming.spi.ObjectFactory/kernel0000644000175000017500000000004010521607162030743 0ustar drazzibdrazziborg.acme.kernelURLContextFactoryxbean-3.7/xbean-finder/src/test/resources/META-INF/javax.naming.spi.ObjectFactory/java0000644000175000017500000000003610521607162030411 0ustar drazzibdrazziborg.acme.javaURLContextFactoryxbean-3.7/xbean-finder/src/test/resources/META-INF/java.net.URLStreamHandler/0000755000175000017500000000000011610661037026460 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/java.net.URLStreamHandler/bar0000644000175000017500000000002610521607162027144 0ustar drazzibdrazziborg.acme.BarUrlHandlerxbean-3.7/xbean-finder/src/test/resources/META-INF/java.net.URLStreamHandler/baz0000644000175000017500000000001610521607162027153 0ustar drazzibdrazziborg.acme.Threexbean-3.7/xbean-finder/src/test/resources/META-INF/java.net.URLStreamHandler/foo0000644000175000017500000000002610521607162027163 0ustar drazzibdrazziborg.acme.FooUrlHandlerxbean-3.7/xbean-finder/src/test/resources/META-INF/java.io.OutputStream0000644000175000017500000000004010521607162025555 0ustar drazzibdrazziborg.openejb.ClassThatDoesntExistxbean-3.7/xbean-finder/src/test/resources/META-INF/serializables/0000755000175000017500000000000011610661037024470 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/serializables/three0000644000175000017500000000001610521607162025516 0ustar drazzibdrazziborg.acme.Threexbean-3.7/xbean-finder/src/test/resources/META-INF/serializables/two0000644000175000017500000000001410521607162025216 0ustar drazzibdrazziborg.acme.Twoxbean-3.7/xbean-finder/src/test/resources/META-INF/serializables/one0000644000175000017500000000001410521607162025166 0ustar drazzibdrazziborg.acme.Onexbean-3.7/xbean-finder/src/test/resources/META-INF/tvshows/0000755000175000017500000000000011610661037023354 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/tvshows/familyguy.properties0000644000175000017500000000205211373255046027504 0ustar drazzibdrazzib################################################################################ # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ################################################################################ creator=Seth MacFarlane father=Peter mother=Lois son=Chris daughter=Meg baby=Stewie xbean-3.7/xbean-finder/src/test/resources/META-INF/tvshows/simpsons.properties0000644000175000017500000000205111373255046027350 0ustar drazzibdrazzib################################################################################ # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ################################################################################ creator=Matt Groening father=Homer mother=Marge son=Bart daughter=Lisa baby=Maggie xbean-3.7/xbean-finder/src/test/resources/META-INF/java.io.Serializable0000644000175000017500000000001410521607162025510 0ustar drazzibdrazziborg.acme.Onexbean-3.7/xbean-finder/src/test/resources/META-INF/movies/0000755000175000017500000000000011610661037023141 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/movies/serentity.properties0000644000175000017500000000201111373255046027304 0ustar drazzibdrazzib################################################################################ # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ################################################################################ director=Joss Whedon star=Nathan Fillion year=2005 xbean-3.7/xbean-finder/src/test/resources/META-INF/movies/kingkong.properties0000644000175000017500000000201011373255046027064 0ustar drazzibdrazzib################################################################################ # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ################################################################################ director=Peter Jackson star=Naomi Watts year=2005 xbean-3.7/xbean-finder/src/test/resources/META-INF/movies/ishtar.properties0000644000175000017500000000176711373255046026571 0ustar drazzibdrazzib################################################################################ # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ################################################################################ # Malformed \uxxxx encoding \u999xbean-3.7/xbean-finder/src/test/resources/META-INF/externalizables/0000755000175000017500000000000011610661037025033 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/resources/META-INF/externalizables/three0000644000175000017500000000004010521607162026056 0ustar drazzibdrazziborg.openejb.ClassThatDoesntExistxbean-3.7/xbean-finder/src/test/resources/META-INF/externalizables/two0000644000175000017500000000001410521607162025561 0ustar drazzibdrazziborg.acme.Twoxbean-3.7/xbean-finder/src/test/resources/META-INF/externalizables/one0000644000175000017500000000001410521607162025531 0ustar drazzibdrazziborg.acme.Onexbean-3.7/xbean-finder/src/test/java/0000755000175000017500000000000011610661037017406 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/0000755000175000017500000000000011610661037020175 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/apache/0000755000175000017500000000000011610661037021416 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661037022513 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/apache/xbean/finder/0000755000175000017500000000000011610661037023762 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/apache/xbean/finder/ResourceFinderTest.java0000644000175000017500000004231011010256577030407 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; /** * @version $Rev: 654018 $ $Date: 2008-05-07 09:42:55 +0200 (mer. 07 mai 2008) $ */ import junit.framework.TestCase; import org.acme.BarUrlHandler; import org.acme.FooUrlHandler; import org.acme.One; import org.acme.Three; import org.acme.Two; import org.acme.javaURLContextFactory; import org.acme.kernelURLContextFactory; import org.acme.ldapURLContextFactory; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.ArrayList; public class ResourceFinderTest extends TestCase { ResourceFinder resourceFinder = new ResourceFinder("META-INF/"); public void testGetResourcesMap1() throws Exception { Map resourcesMap = resourceFinder.getResourcesMap(""); Set> entries = resourcesMap.entrySet(); for (Map.Entry entry : entries) { String key = entry.getKey(); URL value = entry.getValue(); assertTrue("key not a directory", !key.contains("/")); assertTrue("contains META-INF/", value.getPath().contains("META-INF/")); assertTrue("ends with META-INF/" + key, value.getPath().endsWith("META-INF/" + key)); assertTrue("value not a directory", !value.getPath().endsWith("/")); } } public void testGetResourcesMap2() throws Exception { String token = "tvshows"; Map resourcesMap = resourceFinder.getResourcesMap(token); Set> entries = resourcesMap.entrySet(); for (Map.Entry entry : entries) { String key = entry.getKey(); URL value = entry.getValue(); assertTrue("key not a directory", !key.contains("/")); assertTrue("contains META-INF/", value.getPath().contains("META-INF/")); assertTrue("ends with META-INF/" + token + "/" + key, value.getPath().endsWith("META-INF/" + token + "/" + key)); assertTrue("value not a directory", !value.getPath().endsWith("/")); } assertTrue("map contains simpsons.properties", resourcesMap.containsKey("simpsons.properties")); assertTrue("map contains familyguy.properties", resourcesMap.containsKey("familyguy.properties")); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find String // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public void testFindString() throws Exception { String expected = One.class.getName(); String actual = resourceFinder.findString("java.io.Serializable"); assertEquals(expected, actual); } public void testFindAllStrings() throws Exception { List manifests = null; try { manifests = resourceFinder.findAllStrings("MANIFEST.MF"); } catch (Exception thisIsLegal) { return; } assertTrue("manifests found", manifests.size() > 1); for (String manifest : manifests) { assertTrue("starts with 'Manifest-Version'", manifest.startsWith("Manifest-Version")); } } public void testFindAvailableStrings() throws Exception { List manifests = resourceFinder.findAvailableStrings("MANIFEST.MF"); assertTrue("manifests found", manifests.size() > 1); for (String manifest : manifests) { assertTrue("starts with 'Manifest-Version'", manifest.startsWith("Manifest-Version")); } } public void testMapAllStrings() throws Exception { Map resourcesMap = resourceFinder.mapAllStrings("serializables"); assertEquals("map size", 3, resourcesMap.size()); assertTrue("map contains key 'one'", resourcesMap.containsKey("one")); assertEquals(One.class.getName(), resourcesMap.get("one")); assertTrue("map contains key 'two'", resourcesMap.containsKey("two")); assertEquals(Two.class.getName(), resourcesMap.get("two")); assertTrue("map contains key 'three'", resourcesMap.containsKey("three")); assertEquals(Three.class.getName(), resourcesMap.get("three")); } public void testMapAvailableStrings() throws Exception { Map resourcesMap = resourceFinder.mapAvailableStrings("serializables"); assertEquals("map size", 3, resourcesMap.size()); assertTrue("map contains key 'one'", resourcesMap.containsKey("one")); assertEquals(One.class.getName(), resourcesMap.get("one")); assertTrue("map contains key 'two'", resourcesMap.containsKey("two")); assertEquals(Two.class.getName(), resourcesMap.get("two")); assertTrue("map contains key 'three'", resourcesMap.containsKey("three")); assertEquals(Three.class.getName(), resourcesMap.get("three")); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Class // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public void testFindClass() throws Exception { Class actual = resourceFinder.findClass("java.io.Serializable"); assertEquals(One.class, actual); try { resourceFinder.findClass("java.io.OutputStream"); fail("ClassNotFoundException should be thrown"); } catch (ClassNotFoundException success) { // pass } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testFindAllClasses() throws Exception { List classes = resourceFinder.findAllClasses("java.io.Serializable"); assertEquals("size", 1, classes.size()); assertEquals(One.class, classes.get(0)); try { resourceFinder.findAllClasses("java.io.OutputStream"); fail("ClassNotFoundException should be thrown"); } catch (ClassNotFoundException success) { // pass } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testFindAvailableClasses() throws Exception { List classes = resourceFinder.findAvailableClasses("java.io.Serializable"); assertEquals("size", 1, classes.size()); assertEquals(One.class, classes.get(0)); classes = resourceFinder.findAvailableClasses("java.io.OutputStream"); assertEquals("size", 0, classes.size()); } public void testMapAllClasses() throws Exception { Map resourcesMap = resourceFinder.mapAllClasses("serializables"); assertEquals("map size", 3, resourcesMap.size()); assertTrue("map contains key 'one'", resourcesMap.containsKey("one")); assertEquals(One.class, resourcesMap.get("one")); assertTrue("map contains key 'two'", resourcesMap.containsKey("two")); assertEquals(Two.class, resourcesMap.get("two")); assertTrue("map contains key 'three'", resourcesMap.containsKey("three")); assertEquals(Three.class, resourcesMap.get("three")); try { resourceFinder.mapAllClasses("externalizables"); fail("ClassNotFoundException should be thrown"); } catch (ClassNotFoundException success) { // pass } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testMapAvailableClasses() throws Exception { Map resourcesMap = resourceFinder.mapAvailableClasses("externalizables"); assertEquals("map size", 2, resourcesMap.size()); assertTrue("map contains key 'one'", resourcesMap.containsKey("one")); assertEquals(One.class, resourcesMap.get("one")); assertTrue("map contains key 'two'", resourcesMap.containsKey("two")); assertEquals(Two.class, resourcesMap.get("two")); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Implementation // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public void testFindImplementation() throws Exception { Class expected = One.class; Class actual = resourceFinder.findImplementation(java.io.Serializable.class); assertEquals(expected, actual); try { resourceFinder.findImplementation(java.io.InputStream.class); fail("ClassCastException should be thrown"); } catch (ClassCastException success) { } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testFindAllImplementations() throws Exception { List classes = resourceFinder.findAllImplementations(java.io.Serializable.class); assertEquals("size", 1, classes.size()); assertEquals(One.class, classes.get(0)); try { resourceFinder.findAllImplementations(java.io.InputStream.class); fail("ClassNotFoundException should be thrown"); } catch (ClassCastException success) { } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testMapAllImplementations() throws Exception { Map resourcesMap = resourceFinder.mapAllImplementations(javax.naming.spi.ObjectFactory.class); assertEquals("map size", 3, resourcesMap.size()); assertTrue("map contains key 'java'", resourcesMap.containsKey("java")); assertEquals(javaURLContextFactory.class, resourcesMap.get("java")); assertTrue("map contains key 'kernel'", resourcesMap.containsKey("kernel")); assertEquals(kernelURLContextFactory.class, resourcesMap.get("kernel")); assertTrue("map contains key 'ldap'", resourcesMap.containsKey("ldap")); assertEquals(ldapURLContextFactory.class, resourcesMap.get("ldap")); try { resourceFinder.mapAllImplementations(java.net.URLStreamHandler.class); fail("ClassNotFoundException should be thrown"); } catch (ClassCastException success) { // pass } catch (Exception e) { fail("Wrong exception type was thrown: " + e.getClass().getName()); } } public void testMapAvailableImplementations() throws Exception { Map resourcesMap = resourceFinder.mapAvailableImplementations(java.net.URLStreamHandler.class); assertEquals("map size", 2, resourcesMap.size()); assertTrue("map contains key 'bar'", resourcesMap.containsKey("bar")); assertEquals(BarUrlHandler.class, resourcesMap.get("bar")); assertTrue("map contains key 'foo'", resourcesMap.containsKey("foo")); assertEquals(FooUrlHandler.class, resourcesMap.get("foo")); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Find Properties // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public void testFindProperties() throws Exception { Properties properties = resourceFinder.findProperties("tvshows/familyguy.properties"); assertNotNull("properties", properties); validateFamilyGuy(properties); properties = resourceFinder.findProperties("tvshows/simpsons.properties"); assertNotNull("properties", properties); validateSimpsons(properties); } public void testFindAllProperties() throws Exception { List propertiesLists = resourceFinder.findAllProperties("tvshows/familyguy.properties"); assertNotNull("properties", propertiesLists); assertEquals("list size", 1, propertiesLists.size()); Properties properties = propertiesLists.get(0); validateFamilyGuy(properties); } public void testFindAvailableProperties() throws Exception { List propertiesLists = resourceFinder.findAvailableProperties("tvshows/familyguy.properties"); assertNotNull("properties", propertiesLists); assertEquals("list size", 1, propertiesLists.size()); Properties properties = propertiesLists.get(0); validateFamilyGuy(properties); } public void testMapAllProperties() throws Exception { Map propertiesMap = resourceFinder.mapAllProperties("tvshows"); assertNotNull("properties", propertiesMap); assertEquals("map size", 2, propertiesMap.size()); assertTrue("contains 'familyguy.properties'", propertiesMap.containsKey("familyguy.properties")); validateFamilyGuy(propertiesMap.get("familyguy.properties")); assertTrue("contains 'simpsons.properties'", propertiesMap.containsKey("simpsons.properties")); validateSimpsons(propertiesMap.get("simpsons.properties")); try { resourceFinder.mapAllProperties("movies"); } catch (Exception success) { } } public void testMapAvailableProperties() throws Exception { Map propertiesMap = resourceFinder.mapAvailableProperties("movies"); assertNotNull("properties", propertiesMap); assertEquals("map size", 2, propertiesMap.size()); assertTrue("contains 'serenity.properties'", propertiesMap.containsKey("serentity.properties")); Properties properties = propertiesMap.get("serentity.properties"); assertEquals("director", "Joss Whedon", properties.getProperty("director")); assertEquals("star", "Nathan Fillion", properties.getProperty("star")); assertEquals("year", "2005", properties.getProperty("year")); assertTrue("contains 'kingkong.properties'", propertiesMap.containsKey("kingkong.properties")); properties = propertiesMap.get("kingkong.properties"); assertEquals("director", "Peter Jackson", properties.getProperty("director")); assertEquals("star", "Naomi Watts", properties.getProperty("star")); assertEquals("year", "2005", properties.getProperty("year")); } private void validateSimpsons(Properties properties) { assertEquals("props size", 6, properties.size()); assertEquals("creator", "Matt Groening", properties.getProperty("creator")); assertEquals("father", "Homer", properties.getProperty("father")); assertEquals("mother", "Marge", properties.getProperty("mother")); assertEquals("son", "Bart", properties.getProperty("son")); assertEquals("daughter", "Lisa", properties.getProperty("daughter")); assertEquals("baby", "Maggie", properties.getProperty("baby")); } private void validateFamilyGuy(Properties properties) { assertEquals("props size", 6, properties.size()); assertEquals("creator", "Seth MacFarlane", properties.getProperty("creator")); assertEquals("father", "Peter", properties.getProperty("father")); assertEquals("mother", "Lois", properties.getProperty("mother")); assertEquals("son", "Chris", properties.getProperty("son")); assertEquals("daughter", "Meg", properties.getProperty("daughter")); assertEquals("baby", "Stewie", properties.getProperty("baby")); } /* * Disable test because it's failing its purpose: * - when running in maven in a clean build, no urls are found * so the test runs with the ResourceFinder using the classloader * instead of urls * - when running on a non clean build in maven, one url is found, * but the test fails public void testUrlConstructor() throws Exception { List all = resourceFinder.findAll("MANIFEST.MF"); List urls = new ArrayList(); for (URL url : all) { if (url.getPath().contains("xbean-finder")){ urls.add(url); } } resourceFinder = new ResourceFinder("META-INF/", urls.toArray(new URL[]{})); testGetResourcesMap1(); testGetResourcesMap2(); testFindString(); testFindAllStrings(); testFindAvailableStrings(); testMapAllStrings(); testMapAvailableStrings(); testFindClass(); testFindAllClasses(); testFindAvailableClasses(); testMapAllClasses(); testMapAvailableClasses(); testFindImplementation(); testFindAllImplementations(); testMapAllImplementations(); testMapAvailableImplementations(); testFindProperties(); testFindAllProperties(); testFindAvailableProperties(); testMapAllProperties(); testMapAvailableProperties(); } */ } xbean-3.7/xbean-finder/src/test/java/org/apache/xbean/finder/ClassFinderTest.java0000644000175000017500000001527511321212102027654 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import junit.framework.TestCase; import org.acme.bar.Get; import org.acme.bar.ParamA; import org.acme.bar.Construct; import org.acme.bar.Type; import org.acme.bar.AnnType; import org.acme.bar.FullyAnnotated; import org.acme.foo.*; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Arrays; /** * @author David Blevins * @version $Rev: 896706 $ $Date: 2010-01-06 23:52:50 +0100 (mer. 06 janv. 2010) $ */ public class ClassFinderTest extends TestCase { private ClassFinder classFinder; public void setUp() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); UrlSet urlSet = new UrlSet(classLoader); if (classLoader.getParent() != null){ urlSet = urlSet.exclude(classLoader.getParent()); } urlSet = urlSet.excludeJavaHome(); classFinder = new ClassFinder(classLoader, urlSet.getUrls()); } public void testFindAnnotatedPackages() throws Exception { List packages = classFinder.findAnnotatedPackages(Deployable.class); assertNotNull(packages); assertEquals(1, packages.size()); assertTrue(packages.contains(Red.class.getPackage())); } public void testFindAnnotatedClasses() throws Exception { Class[] expected = {Halloween.class, Thanksgiving.class, ValentinesDay.class, GenericHoliday.class}; List actual = classFinder.findAnnotatedClasses(Holiday.class); assertNotNull(actual); assertEquals(expected.length, actual.size()); for (Class clazz : expected) { assertTrue(clazz.getName(), actual.contains(clazz)); } Class[] expected2 = {Blue.class, Blue.Navy.class, Blue.Sky.class, Green.class, Green.Emerald.class, Red.class, Red.CandyApple.class, Red.Pink.class}; actual = classFinder.findAnnotatedClasses(Color.class); assertNotNull(actual); assertEquals(expected2.length, actual.size()); for (Class clazz : expected2) { assertTrue(clazz.getName(), actual.contains(clazz)); } Class[] expected3 = {Type.class}; actual = classFinder.findAnnotatedClasses(AnnType.class); assertNotNull(actual); assertEquals(expected3.length, actual.size()); for (Class clazz : expected3) { assertTrue(clazz.getName(), actual.contains(clazz)); } } public void testFindInheritedAnnotatedClassesInherited() throws Exception { Class[] expected = {FunnyFamilyHalloween.class, FamilyHalloween.class, Halloween.class, Thanksgiving.class, ValentinesDay.class, GenericHoliday.class, StringGenericHoliday.class}; List actual = classFinder.findInheritedAnnotatedClasses(Holiday.class); assertNotNull(actual); assertEquals(expected.length, actual.size()); for (Class clazz : expected) { assertTrue(clazz.getName(), actual.contains(clazz)); } expected = new Class[]{Halloween.class, Thanksgiving.class, ValentinesDay.class, GenericHoliday.class}; actual = classFinder.findAnnotatedClasses(Holiday.class); assertNotNull(actual); assertEquals(expected.length, actual.size()); for (Class clazz : expected) { assertTrue(clazz.getName(), actual.contains(clazz)); } } public void testFindAnnotatedMethods() throws Exception { List methods = classFinder.findAnnotatedMethods(Get.class); assertNotNull("methods", methods); assertEquals("methods.size", 5, methods.size()); // Annotated parameters don't count methods = classFinder.findAnnotatedMethods(ParamA.class); assertNotNull("methods", methods); assertEquals("methods.size", 0, methods.size()); // Neither do annotated constructors methods = classFinder.findAnnotatedMethods(Construct.class); assertNotNull("methods", methods); assertEquals("methods.size", 0, methods.size()); } public void testFindAnnotatedConstructors() throws Exception { List constructors = classFinder.findAnnotatedConstructors(Construct.class); assertNotNull("constructors", constructors); assertEquals("constructors.size", 1, constructors.size()); } public void testFindAnnotatedFields() throws Exception { List fields = classFinder.findAnnotatedFields(org.acme.bar.Field.class); assertNotNull("fields", fields); assertEquals("fields.size", 7, fields.size()); } public void testClassListConstructor() throws Exception { Class[] classes = {Blue.class, Blue.Navy.class, Blue.Sky.class, Green.class, Green.Emerald.class, Red.class, Red.CandyApple.class, Red.Pink.class, Halloween.class, Holiday.class, Deployable.class, Primary.class, Property.class, Thanksgiving.class, ValentinesDay.class, FullyAnnotated.class, Type.class, GenericHoliday.class, StringGenericHoliday.class}; classFinder = new ClassFinder(classes); testFindAnnotatedClasses(); testFindAnnotatedConstructors(); testFindAnnotatedFields(); testFindAnnotatedMethods(); testFindAnnotatedPackages(); } public void testFindClassesInPackage() throws Exception{ List classesInPackage = classFinder.findClassesInPackage("org.acme.foo", false); Class[] classesArray = {Blue.class, Blue.Navy.class, Blue.Sky.class, Green.class, Green.Emerald.class, Red.class, Red.CandyApple.class, Red.Pink.class, Halloween.class, Holiday.class, Deployable.class, Primary.class, Property.class, Thanksgiving.class, ValentinesDay.class}; List classes = Arrays.asList(classesArray); assertEquals(true, classesInPackage.containsAll(classes)); } } xbean-3.7/xbean-finder/src/test/java/org/apache/xbean/finder/UrlSetTest.java0000644000175000017500000001417411125253503026706 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.finder; import junit.framework.TestCase; import java.net.URL; import java.util.List; import java.io.File; /** * @version $Rev$ $Date$ */ public class UrlSetTest extends TestCase { private UrlSet urlSet; private URL[] originalUrls; protected void setUp() throws Exception { originalUrls = new URL[]{ new URL("file:/Users/dblevins/work/xbean/trunk/xbean-finder/target/classes/"), new URL("file:/Users/dblevins/work/xbean/trunk/xbean-finder/target/test-classes/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/.compatibility/14compatibility.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/charsets.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/classes.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/dt.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jce.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jconsole.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jsse.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/laf.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/ui.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/deploy.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/apple_provider.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/dnsns.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/localedata.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/sunjce_provider.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/sunpkcs11.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/plugin.jar!/"), new URL("jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/sa-jdi.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/CoreAudio.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/MRJToolkit.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/QTJSupport.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/QTJava.zip!/"), new URL("jar:file:/System/Library/Java/Extensions/dns_sd.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/j3daudio.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/j3dcore.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/j3dutils.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/jai_codec.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/jai_core.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/mlibwrapper_jai.jar!/"), new URL("jar:file:/System/Library/Java/Extensions/vecmath.jar!/"), new URL("jar:file:/Users/dblevins/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar!/"), }; urlSet = new UrlSet(originalUrls); } public void testAll() throws Exception { assertEquals("Urls.size()", 32, urlSet.getUrls().size()); UrlSet homeSet = urlSet.matching(".*Home.*"); assertEquals("HomeSet.getUrls().size()", 8, homeSet.getUrls().size()); // homeSet = urlSet.relative(new File("/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home")); // assertEquals("HomeSet.getUrls().size()", 8, homeSet.getUrls().size()); UrlSet urlSet2 = urlSet.exclude(homeSet); assertEquals("Urls.size()", 24, urlSet2.getUrls().size()); UrlSet xbeanSet = urlSet.matching(".*xbean.*"); assertEquals("XbeanSet.getUrls().size()", 2, xbeanSet.getUrls().size()); UrlSet junitSet = urlSet.matching(".*junit.*"); assertEquals("JunitSet.getUrls().size()", 1, junitSet.getUrls().size()); UrlSet mergedSet = homeSet.include(xbeanSet); assertEquals("MergedSet.getUrls().size()", 10, mergedSet.getUrls().size()); mergedSet.include(junitSet); assertEquals("MergedSet.getUrls().size()", 10, mergedSet.getUrls().size()); UrlSet mergedSet2 = mergedSet.include(junitSet); assertEquals("MergedSet2.getUrls().size()", 11, mergedSet2.getUrls().size()); UrlSet filteredSet = urlSet.exclude(".*System/Library.*"); assertEquals("FilteredSet.getUrls().size()", 3, filteredSet.getUrls().size()); filteredSet.exclude(junitSet); assertEquals("FilteredSet.getUrls().size()", 3, filteredSet.getUrls().size()); UrlSet filteredSet2 = filteredSet.exclude(junitSet); assertEquals("FilteredSet2.getUrls().size()", 2, filteredSet2.getUrls().size()); } } xbean-3.7/xbean-finder/src/test/java/org/apache/xbean/finder/util/0000755000175000017500000000000011610661037024737 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/acme/0000755000175000017500000000000011610661037021102 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/acme/kernelURLContextFactory.java0000644000175000017500000000235010521607162026504 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import javax.naming.spi.ObjectFactory; import javax.naming.Name; import javax.naming.Context; import java.util.Hashtable; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class kernelURLContextFactory implements ObjectFactory { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { return "kernel"; } } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/0000755000175000017500000000000011610661037021646 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/acme/bar/Field.java0000644000175000017500000000213710521607162023536 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.FIELD}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Field { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Optional.java0000644000175000017500000000214610521607162024300 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PARAMETER}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Optional { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Get.java0000644000175000017500000000213610521607162023231 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Get { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/ParamA.java0000644000175000017500000000214410521607162023652 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PARAMETER}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface ParamA { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Set.java0000644000175000017500000000213610521607162023245 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Set { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Variable.java0000644000175000017500000000215310521607162024236 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.LOCAL_VARIABLE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Variable { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Package.java0000644000175000017500000000214310521607162024043 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PACKAGE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Package { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/ParamB.java0000644000175000017500000000214410521607162023653 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PARAMETER}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface ParamB { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/AnnType.java0000644000175000017500000000215310521607162024067 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.ANNOTATION_TYPE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface AnnType { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Method.java0000644000175000017500000000214110521607162023726 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Method { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Type.java0000644000175000017500000000214610521607162023434 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.TYPE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) @AnnType public @interface Type { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/Construct.java0000644000175000017500000000215110521607162024473 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.CONSTRUCTOR}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Construct { } xbean-3.7/xbean-finder/src/test/java/org/acme/bar/FullyAnnotated.java0000644000175000017500000000630210521607162025442 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.bar; import java.util.List; import java.util.ArrayList; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Type public class FullyAnnotated,Beeer> { @Field private String field; @Field private char[] characters; @Field private String[] strings; @Field private String[][] moreStrings; @Field private List stringList; @Field private Cheese spam; @Field private Direction direction; @Construct public FullyAnnotated(@ParamA String constructorParam, @ParamB @Optional int anInt) { this.field = constructorParam; this.stringList = new ArrayList(); } @Method public void doIt(int i, boolean b, double d, short s){} @Method public void doMore(Cheese cheese, Fun fun){} @Type enum Direction { NORTH, SOUTH, EAST, WEST } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } public Cheese getSpam() { return spam; } public void setSpam(Cheese spam) { this.spam = spam; } public void setSpam(Object spam) { this.spam = (Cheese)spam; } @Get @Method public String getField() { @Variable String theField = this.field; return theField; } @Set @Method public void setField(@ParamB String methodParam) { this.field = methodParam; } @Get @Method public char[] getCharacters() { return characters; } @Set @Method public void setCharacters(char[] characters) { this.characters = characters; } @Get @Method public String[] getStrings() { return strings; } @Set @Method public void setStrings(String[] strings) { this.strings = strings; } @Get @Method public String[][] getMoreStrings() { return moreStrings; } @Set @Method public void setMoreStrings(@ParamA String[][] moreStrings) { this.moreStrings = moreStrings; } @Get @Method public List getStringList() { return stringList; } @Set @Method public void setStringList(List stringList) { this.stringList = stringList; } @Set @Method public void setStringList(ArrayList stringList) { this.stringList = stringList; } } xbean-3.7/xbean-finder/src/test/java/org/acme/BarUrlHandler.java0000644000175000017500000000223310521607162024431 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import java.net.URLConnection; import java.net.URL; import java.io.IOException; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class BarUrlHandler extends java.net.URLStreamHandler { protected URLConnection openConnection(URL u) throws IOException { throw new IOException("bar"); } } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/0000755000175000017500000000000011610661037021665 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/test/java/org/acme/foo/Thanksgiving.java0000644000175000017500000000170410521607162025165 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Holiday public class Thanksgiving {} xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Property.java0000644000175000017500000000214310521607162024353 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Property { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/package-info.java0000644000175000017500000000151210541574201025051 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ @Deployable package org.acme.foo; xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Color.java0000644000175000017500000000213610521607162023607 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.TYPE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Color { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Primary.java0000644000175000017500000000167210521607162024160 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public interface Primary {} xbean-3.7/xbean-finder/src/test/java/org/acme/foo/FamilyHalloween.java0000644000175000017500000000165211125254275025617 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Rev$ $Date$ */ public class FamilyHalloween extends Halloween { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Blue.java0000644000175000017500000000203110521607162023412 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Color public class Blue implements Primary { @Color public static class Navy{} @Color public static class Sky{} } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/GenericHoliday.java0000644000175000017500000000171511321212102025402 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (Tue, 31 Oct 2006) $ */ @Holiday public interface GenericHoliday { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Holiday.java0000644000175000017500000000225211125254275024125 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @version $Revision: 729546 $ $Date: 2008-12-26 23:20:45 +0100 (ven. 26 déc. 2008) $ */ @Target(value = {java.lang.annotation.ElementType.TYPE}) @Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Holiday { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Red.java0000644000175000017500000000203710521607162023243 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Color public class Red implements Primary { @Color public static class CandyApple{} @Color public static class Pink{} } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/ValentinesDay.java0000644000175000017500000000170510521607162025300 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Holiday public class ValentinesDay {} xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Halloween.java0000644000175000017500000000170210521607162024445 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Holiday public class Halloween {} xbean-3.7/xbean-finder/src/test/java/org/acme/foo/FunnyFamilyHalloween.java0000644000175000017500000000166511130664160026635 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Rev$ $Date$ */ public class FunnyFamilyHalloween extends FamilyHalloween { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/StringGenericHoliday.java0000644000175000017500000000165011321212102026567 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Rev$ $Date$ */ public class StringGenericHoliday implements GenericHoliday { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Deployable.java0000644000175000017500000000214610521607162024612 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PACKAGE}) @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Deployable { } xbean-3.7/xbean-finder/src/test/java/org/acme/foo/Green.java0000644000175000017500000000206410521607162023571 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme.foo; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ @Color public class Green implements Primary { @Color public static class Emerald extends Green {} @Property public void myMethod(){ } } xbean-3.7/xbean-finder/src/test/java/org/acme/One.java0000644000175000017500000000243510521607162022471 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; /** * @version $Rev: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class One implements Externalizable { public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } public String toString() { return "one"; } } xbean-3.7/xbean-finder/src/test/java/org/acme/Two.java0000644000175000017500000000244110521607162022516 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class Two implements Externalizable { public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } public String toString() { return "two"; } } xbean-3.7/xbean-finder/src/test/java/org/acme/javaURLContextFactory.java0000644000175000017500000000234410521607162026150 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import javax.naming.spi.ObjectFactory; import javax.naming.Name; import javax.naming.Context; import java.util.Hashtable; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class javaURLContextFactory implements ObjectFactory { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { return "java"; } } xbean-3.7/xbean-finder/src/test/java/org/acme/ldapURLContextFactory.java0000644000175000017500000000234410521607162026147 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import javax.naming.spi.ObjectFactory; import javax.naming.Name; import javax.naming.Context; import java.util.Hashtable; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class ldapURLContextFactory implements ObjectFactory { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { return "ldap"; } } xbean-3.7/xbean-finder/src/test/java/org/acme/FooUrlHandler.java0000644000175000017500000000223310521607162024450 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; import java.net.URLConnection; import java.net.URL; import java.io.IOException; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class FooUrlHandler extends java.net.URLStreamHandler { protected URLConnection openConnection(URL u) throws IOException { throw new IOException("foo"); } } xbean-3.7/xbean-finder/src/test/java/org/acme/Three.java0000644000175000017500000000175210521607162023020 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.acme; /** * @version $Revision: 469417 $ $Date: 2006-10-31 09:50:58 +0100 (mar. 31 oct. 2006) $ */ public class Three { public String toString() { return "three"; } } xbean-3.7/xbean-finder/src/site/0000755000175000017500000000000011610661040016444 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/site/apt/0000755000175000017500000000000011610661040017230 5ustar drazzibdrazzibxbean-3.7/xbean-finder/src/site/site.xml0000644000175000017500000000210010521607162020130 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/xbean-finder-shaded/0000755000175000017500000000000011610661034016142 5ustar drazzibdrazzibxbean-3.7/xbean-finder-shaded/pom.xml0000755000175000017500000001217011373256143017472 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-finder-shaded jar Apache XBean :: Finder shaded (repackaged) org.apache.xbean.finder;version=${pom.version} org.apache.xbean.finder;version=${pom.version},org.apache.xbean.asm;version=3.1,org.apache.xbean.asm.commons;version=3.1 org.apache.maven.plugins maven-shade-plugin package shade org.objectweb.asm org.apache.xbean.asm org.apache.xbean:xbean-finder org.apache.xbean:xbean-asm-shaded junit:junit org.apache.maven.plugins maven-antrun-plugin package run org.apache.felix maven-bundle-plugin true !org.objectweb.asm.*,!org.apache.xbean.finder.*,org.apache.xbean.asm,*;resolution:=optional <_nouses>true bundle-manifest package bundle org.apache.xbean xbean-finder ${version} org.apache.xbean xbean-asm-shaded ${version} xbean-3.7/xbean-telnet/0000755000175000017500000000000011610661034014740 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/pom.xml0000644000175000017500000000312211373256143016262 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-telnet bundle Apache XBean :: Telnet groovy groovy xbean-3.7/xbean-telnet/src/0000755000175000017500000000000011610661034015527 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/0000755000175000017500000000000011610661034016453 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/resources/0000755000175000017500000000000011610661034020465 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/resources/META-INF/0000755000175000017500000000000011610661034021625 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/0000755000175000017500000000000011610661034017374 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/0000755000175000017500000000000011610661034020163 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/0000755000175000017500000000000011610661034021404 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661034022501 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/0000755000175000017500000000000011610661034024117 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Lookup.java0000755000175000017500000000707410473277125026260 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameClassPair; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; public class Lookup implements Command { private final javax.naming.Context ctx; public Lookup() throws Exception { this(new InitialContext()); } public Lookup(Context ctx) { this.ctx = ctx; } public static void register() { try { Lookup cmd = new Lookup(); CommandRegistry.register("lookup", cmd); } catch (Exception e) { } } private static String PWD = ""; // execute jndi lookups public int main(String[] args, InputStream in, PrintStream out) { try { String name = ""; if (args == null || args.length == 0) { name = PWD; } else { name = args[0]; } Object obj = null; try { obj = ctx.lookup(name); } catch (NameNotFoundException e) { out.print("lookup: "); out.print(name); out.println(": No such object or subcontext"); return -1; } catch (Throwable e) { out.print("lookup: error: "); e.printStackTrace(new PrintStream(out)); return -1; } if (obj instanceof Context) { list(name, in, out); return 0; } // TODO:1: Output the different data types differently out.println("" + obj); return 0; } catch (Exception e) { e.printStackTrace(new PrintStream(out)); return -2; } } public void list(String name, InputStream in, PrintStream out) throws IOException { try { NamingEnumeration names = null; try { names = ctx.list(name); } catch (NameNotFoundException e) { out.print("lookup: "); out.print(name); out.println(": No such object or subcontext"); return; } catch (Throwable e) { out.print("lookup: error: "); e.printStackTrace(new PrintStream(out)); return; } if (names == null) { return; } while (names.hasMore()) { NameClassPair entry = (NameClassPair) names.next(); out.println(entry.getName()); } } catch (Exception e) { e.printStackTrace(new PrintStream(out)); } } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Test.java0000755000175000017500000000303510473277125025717 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; /** * @author David Blevins */ public class Test implements Command { public static void _DONT_register() { CommandRegistry.register("test", Test.class); } public int main(String[] args, InputStream in, PrintStream out) { try { InputStream file = new FileInputStream("print.txt"); int b = file.read(); while (b != -1) { out.write(b); b = file.read(); } } catch (Exception e) { e.printStackTrace(); return -1; } return 0; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/GroovySh.java0000755000175000017500000000565210473277125026567 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import groovy.lang.GroovyShell; import org.codehaus.groovy.runtime.InvokerHelper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; public class GroovySh implements Command { public static void register() { CommandRegistry.register("groovysh", GroovySh.class); } public int main(String[] args, InputStream in, PrintStream out) { GroovyShell shell = new GroovyShell(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String version = InvokerHelper.getVersion(); out.println("Lets get Groovy!"); out.println("================"); out.println("Version: " + version + " JVM: " + System.getProperty("java.vm.version")); out.println("Hit carriage return twice to execute a command"); out.println("The command 'quit' will terminate the shell"); int counter = 1; while (true) { StringBuffer buffer = new StringBuffer(); while (true) { out.print("groovy> "); String line; try { line = reader.readLine(); } catch (IOException e) { out.println("Caught: " + e); e.printStackTrace(); return -1; } if (line != null) { buffer.append(line); buffer.append('\n'); } if (line == null || line.trim().length() == 0) { break; } } String command = buffer.toString().trim(); if (command == null || command.equals("quit")) { break; } try { Object answer = shell.evaluate(command, "CommandLine" + counter++ + ".groovy"); out.println(InvokerHelper.inspect(answer)); } catch (Exception e) { out.println("Caught: " + e); e.printStackTrace(); } } return 0; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/CommandRegistry.java0000644000175000017500000000503110473277125030102 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class CommandRegistry { protected static final HashMap commands = new HashMap(); static { loadCommandList(); } protected static final CommandRegistry unknownCommand = new CommandRegistry(); public static Map getCommandMap() { HashMap rc = new HashMap(); for (Iterator iter = commands.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); Command command = getCommand(name); rc.put(name, command); } return rc; } public static void register(String name, Command cmd) { commands.put(name, cmd); } public static void register(String name, Class cmd) { commands.put(name, cmd); } public static Command getCommand(String name) { Object cmd = commands.get(name); if (cmd instanceof Class) { cmd = loadCommand((Class) cmd); register(name, (Command) cmd); } return (Command) cmd; } // - Protected methods - // protected static Command loadCommand(Class commandClass) { Command cmd = null; try { cmd = (Command) commandClass.newInstance(); } catch (Exception e) { //throw new IOException("Cannot instantiate command class "+commandClass+"\n"+e.getClass().getName()+":\n"+e.getMessage()); } return cmd; } /** * TODO: Replace this part with the classpath magic */ protected static void loadCommandList() { Exit.register(); Help.register(); Lookup.register(); Version.register(); GroovySh.register(); } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/CommandShell.java0000755000175000017500000001057510473277125027355 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.StringTokenizer; import java.util.Vector; public class CommandShell implements Command { private final String prompt; public CommandShell(String serverName) { serverName = serverName.toLowerCase(); prompt = TTY_Reset + TTY_Bright + "["+serverName+"]$ " + TTY_Reset; } private boolean stop = false; private int rc = 0; public static final char ESC = (char) 27; public static final String TTY_Reset = ESC + "[0m"; public static final String TTY_Bright = ESC + "[1m"; public static final String TTY_Dim = ESC + "[2m"; public static final String TTY_Underscore = ESC + "[4m"; public static final String TTY_Blink = ESC + "[5m"; public static final String TTY_Reverse = ESC + "[7m"; public static final String TTY_Hidden = ESC + "[8m"; /* Foreground Colors */ public static final String TTY_FG_Black = ESC + "[30m"; public static final String TTY_FG_Red = ESC + "[31m"; public static final String TTY_FG_Green = ESC + "[32m"; public static final String TTY_FG_Yellow = ESC + "[33m"; public static final String TTY_FG_Blue = ESC + "[34m"; public static final String TTY_FG_Magenta = ESC + "[35m"; public static final String TTY_FG_Cyan = ESC + "[36m"; public static final String TTY_FG_White = ESC + "[37m"; /* Background Colors */ public static final String TTY_BG_Black = ESC + "[40m"; public static final String TTY_BG_Red = ESC + "[41m"; public static final String TTY_BG_Green = ESC + "[42m"; public static final String TTY_BG_Yellow = ESC + "[43m"; public static final String TTY_BG_Blue = ESC + "[44m"; public static final String TTY_BG_Magenta = ESC + "[45m"; public static final String TTY_BG_Cyan = ESC + "[46m"; public static final String TTY_BG_White = ESC + "[47m"; public int main(String[] args, InputStream input, PrintStream out) { DataInputStream in = new DataInputStream(input); while (!stop) { prompt(in, out); } return rc; } protected void prompt(DataInputStream in, PrintStream out) { try { out.print(prompt); out.flush(); String commandline = in.readLine(); if( commandline == null ) { this.stop = true; return; } commandline = commandline.trim(); if (commandline.length() < 1) { return; } String command = commandline; StringTokenizer cmdstr = new StringTokenizer(command); command = cmdstr.nextToken(); // Get parameters Vector p = new Vector(); while ( cmdstr.hasMoreTokens() ) { p.add(cmdstr.nextToken()); } String[] args = new String[p.size()]; p.copyInto(args); Command cmd = CommandRegistry.getCommand(command); if (cmd == null) { out.print(command); out.println(": command not found"); } else { cmd.main(args, in, out); } } catch (UnsupportedOperationException e) { this.rc=-1; this.stop = true; } catch (Throwable e) { e.printStackTrace(out); this.rc=-1; this.stop = true; } } protected void badCommand(DataInputStream in, PrintStream out) throws IOException { //asdf: command not found } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Exit.java0000755000175000017500000000221610473277125025711 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.InputStream; import java.io.PrintStream; public class Exit implements Command { public static void register() { CommandRegistry.register("exit", Exit.class); } public int main(String[] args, InputStream in, PrintStream out) { throw new UnsupportedOperationException(); } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Command.java0000755000175000017500000000240010473277125026351 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.InputStream; import java.io.PrintStream; public interface Command { /** * HRC: if we really want to simulate a command line style environment, * I think think entry point needs more context data: an std error print stream and * a environment map. * * @param args * @param in * @param out * @return */ public int main(String[] args, InputStream in, PrintStream out); } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Version.java0000755000175000017500000000340410473277125026425 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.InputStream; import java.io.PrintStream; import java.net.URL; import java.util.Properties; public class Version implements Command { public static void register() { CommandRegistry.register("version", Version.class); } public int main(String[] args, InputStream in, PrintStream out) { /* * Output startup message */ Properties versionInfo = new Properties(); try { versionInfo.load(new URL("resource:/openejb-version.properties").openConnection().getInputStream()); } catch (java.io.IOException e) { } out.print("OpenEJB Remote Server "); out.print(versionInfo.getProperty("version")); out.print(" build: "); out.print(versionInfo.getProperty("date")); out.print("-"); out.println(versionInfo.getProperty("time")); out.println(versionInfo.getProperty("url")); return 0; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/command/Help.java0000755000175000017500000000263710473277125025677 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.command; import java.io.InputStream; import java.io.PrintStream; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Help implements Command { public static void register() { CommandRegistry.register("help", Help.class); } public int main(String[] args, InputStream in, PrintStream out) { Map hash = CommandRegistry.getCommandMap();; Set set = hash.keySet(); Iterator cmds = set.iterator(); while (cmds.hasNext()) { out.print(" " + cmds.next()); out.println(""); } return 0; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/0000755000175000017500000000000011610661034024314 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/console/0000755000175000017500000000000011610661034025756 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/console/Main.java0000644000175000017500000000211510473277125027516 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.console; import org.apache.xbean.command.CommandShell; public class Main { public static void main(String[] args) { CommandShell shell = new CommandShell("localhost"); System.exit(shell.main(new String[]{}, System.in, System.out)); } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/0000755000175000017500000000000011610661034025607 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetOption.java0000755000175000017500000000364210473277125031120 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; public class TelnetOption { private int optionCode; private boolean supported; private boolean enabled; private boolean negotiated; private boolean inNegotiation; public TelnetOption(int optionCode) { this.optionCode = optionCode; } public int getOptionId() { return optionCode; } public boolean isEnabled() { return enabled; } public void enable() { enabled = true; negotiated = true; } public void disable() { enabled = false; negotiated = true; } public boolean isSupported() { return supported; } public boolean isInNegotiation() { return inNegotiation; } public void isInNegotiation(boolean inNegotiation) { this.inNegotiation = inNegotiation; } public boolean hasBeenNegotiated() { return negotiated; } public void hasBeenNegotiated(boolean negotiated) { this.negotiated = negotiated; this.inNegotiation = false; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetShell.java0000755000175000017500000000460210473277125030714 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import org.apache.xbean.command.CommandShell; public class TelnetShell { private final String serverName; public TelnetShell(String serverName) { this.serverName = serverName; } public void service(Socket socket) throws IOException { try { service(socket.getInputStream(), socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) socket.close(); } } public void service(InputStream in, OutputStream out) throws IOException { InputStream telnetIn = null; PrintStream telnetOut = null; try { telnetIn = new TelnetInputStream(in, out); telnetOut = new TelnetPrintStream(out); telnetOut.println(serverName + " Console"); telnetOut.println("type \'help\' for a list of commands"); // TODO:1: Login //...need a security service first CommandShell shell = new CommandShell(serverName); shell.main(new String[]{}, telnetIn, telnetOut); } catch (Throwable t) { // TODO: log this } finally { if (telnetIn != null){ telnetIn.close(); } if (telnetOut != null) { telnetOut.close(); } } } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetInputStream.java0000755000175000017500000001665210473277125032130 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class TelnetInputStream extends FilterInputStream implements TelnetCodes { // state table for what options have been negotiated private TelnetOption[] options = new TelnetOption[256]; private OutputStream out = null; /** * We haven yet implemented any Telnet options, so we just explicitly * disable some common options for safety sake. *

* Certain Telnet clients (MS Windows Telnet) are enabling options without * asking first. Shame, shame, shame. * * @throws IOException */ public TelnetInputStream(InputStream in, OutputStream out) throws IOException { super(in); this.out = out; negotiateOption(DONT, 1); negotiateOption(DONT, 6); negotiateOption(DONT, 24); negotiateOption(DONT, 33); negotiateOption(DONT, 34); } public int read() throws IOException { int b = super.read(); if (b == IAC) { // The cosole has a reference // to this input stream processCommand(); // Call read recursively as // the next character could // also be a command b = this.read(); } //System.out.println("B="+b); return b; } /** * This is only called by TelnetInputStream * it is assumed that the IAC byte has already been read from the stream. * * @throws IOException */ private void processCommand() throws IOException { // Debug statement print("C: IAC "); int command = super.read(); switch (command) { case WILL: senderWillEnableOption(super.read()); break; case DO: pleaseDoEnableOption(super.read()); break; case WONT: senderWontEnableOption(super.read()); break; case DONT: pleaseDontEnableOption(super.read()); break; default: unimplementedCommand(command); break; } } private void unimplementedCommand(int command) { println(command + ": command not found"); } /** * Client says: I will enable OptionX *

* If the sender initiated the negotiation of the * option, we must send a reply. Replies can be DO or DON'T. * * @param optionID * @throws IOException */ private void senderWillEnableOption(int optionID) throws IOException { // Debug statement println("WILL " + optionID); TelnetOption option = getOption(optionID); if (option.hasBeenNegotiated()) return; if (option.isInNegotiation()) { option.enable(); } else if (!option.isInNegotiation() && option.isSupported()) { negotiateOption(DO, optionID); option.enable(); } else if (!option.isInNegotiation() && !option.isSupported()) { negotiateOption(DONT, optionID); option.disable(); } } /** * Client says: Please, do enable OptionX *

* If the sender initiated the negotiation of the * option, we must send a reply. *

* Replies can be WILL or WON'T. * * @param optionID * @throws IOException */ private void pleaseDoEnableOption(int optionID) throws IOException { // Debug statement println("DO " + optionID); TelnetOption option = getOption(optionID); if (option.hasBeenNegotiated()) return; if (option.isInNegotiation()) { option.enable(); } else if (!option.isInNegotiation() && option.isSupported()) { negotiateOption(WILL, optionID); option.enable(); } else if (!option.isInNegotiation() && !option.isSupported()) { negotiateOption(WONT, optionID); option.disable(); } } /** * Client says: I won't enable OptionX *

*

* If the sender initiated the negotiation of the * option, we must send a reply. *

* Replies can only be DON'T. * * @param optionID * @throws IOException */ private void senderWontEnableOption(int optionID) throws IOException { println("WONT " + optionID); TelnetOption option = getOption(optionID); if (option.hasBeenNegotiated()) return; if (!option.isInNegotiation()) { negotiateOption(DONT, optionID); } option.disable(); } /** * Client says: Please, don't enable OptionX *

* If the sender initiated the negotiation of the * option, we must send a reply. *

* Replies can only be WON'T. * * @param optionID * @throws IOException */ private void pleaseDontEnableOption(int optionID) throws IOException { // Debug statement println("DONT " + optionID); TelnetOption option = getOption(optionID); if (option.hasBeenNegotiated()) return; if (!option.isInNegotiation()) { negotiateOption(WONT, optionID); } option.disable(); } // TODO:0: Replace with actual logging private void println(String s) { // System.out.println(s); } // TODO:0: Replace with actual logging private void print(String s) { // System.out.print(s); } /** * Send an option negitiation command to the client * * @param negotiate * @param optionID * @throws IOException */ private void negotiateOption(int negotiate, int optionID) throws IOException { TelnetOption option = getOption(optionID); option.isInNegotiation(true); String n = null; switch (negotiate) { case WILL: n = "WILL "; break; case DO: n = "DO "; break; case WONT: n = "WONT "; break; case DONT: n = "DONT "; break; } // Debug statement println("S: IAC " + n + optionID); synchronized (out) { out.write(IAC); out.write(negotiate); out.write(optionID); } } private TelnetOption getOption(int optionID) { TelnetOption opt = options[optionID]; if (opt == null) { opt = new TelnetOption(optionID); options[optionID] = opt; } return opt; } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetDaemon.java0000644000175000017500000000626010473277125031047 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TelnetDaemon implements Runnable { private final TelnetShell shell; private final int port; private ServerSocket serverSocket; /** * We start out in a "stopped" state until someone calls the start method. */ private boolean stop = true; public TelnetDaemon(String serverName, int port) { this.port = port; this.shell = new TelnetShell(serverName); } public void start() throws Exception { synchronized (this) { // Don't bother if we are already started/starting if (!stop) return; stop = false; // Do our stuff try { serverSocket = new ServerSocket(port, 20); Thread d = new Thread(this); d.setName("service.shell@" + d.hashCode()); d.setDaemon(true); d.start(); } catch (Exception e) { throw new Exception("Service failed to start.", e); } } } public void stop() throws Exception { synchronized (this) { if (stop) { return; } stop = true; try { this.notifyAll(); } catch (Throwable t) { t.printStackTrace(); } } } public synchronized void service(final Socket socket) throws IOException { Thread d = new Thread(new Runnable() { public void run() { try { shell.service(socket); } catch (SecurityException e) { } catch (Throwable e) { } finally { try { if (socket != null) socket.close(); } catch (Throwable t) { } } } }); d.setDaemon(true); d.start(); } public void run() { Socket socket = null; while (!stop) { try { socket = serverSocket.accept(); socket.setTcpNoDelay(true); if (!stop) service(socket); } catch (SecurityException e) { } catch (Throwable e) { } } } } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetCodes.java0000755000175000017500000000730610473277125030706 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; public interface TelnetCodes { /** * End of subnegotiation parameters. *

* Name: SE * Code: 240 */ public static final int SE = 240; /** * No operation. *

* Name: NOP * Code: 241 */ public static final int NOP = 241; /** * The data stream portion of a Synch. * This should always be accompanied * by a TCP Urgent notification. *

* Name: Data Mark * Code: 242 */ public static final int Data_Mark = 242; /** * NVT character BRK. *

* Name: Break * Code: 243 */ public static final int Break = 243; /** * The function IP. *

* Name: Interrupt Process * Code: 244 */ public static final int Interrupt_Process = 244; /** * The function AO. *

* Name: Abort output * Code: 245 */ public static final int Abort_output = 245; /** * The function AYT. *

* Name: Are You There * Code: 246 */ public static final int Are_You_There = 246; /** * The function EC. *

* Name: Erase character * Code: 247 */ public static final int Erase_character = 247; /** * The function EL. *

* Name: Erase Line * Code: 248 */ public static final int Erase_Line = 248; /** * The GA signal. *

* Name: Go ahead * Code: 249 */ public static final int Go_ahead = 249; /** * Indicates that what follows is * subnegotiation of the indicated * option. *

* Name: SB * Code: 250 */ public static final int SB = 250; /** * Indicates the desire to begin * performing, or confirmation that * you are now performing, the * indicated option. *

* Name: WILL (option code) * Code: 251 */ public static final int WILL = 251; /** * Indicates the refusal to perform, * or continue performing, the * indicated option. *

* Name: WON'T (option code) * Code: 252 */ public static final int WONT = 252; /** * Indicates the request that the * other party perform, or * confirmation that you are expecting * he other party to perform, the * ndicated option. *

* Name: DO (option code) * Code: 253 */ public static final int DO = 253; /** * Indicates the demand that the * other party stop performing, * or confirmation that you are no * longer expecting the other party * to perform, the indicated option. *

* Name: DON'T (option code) * Code: 254 */ public static final int DONT = 254; /** * Interpret as command * aka Data Byte *

* Name: IAC * Code: 255 */ public static final int IAC = 255; } xbean-3.7/xbean-telnet/src/main/java/org/apache/xbean/terminal/telnet/TelnetPrintStream.java0000755000175000017500000000437310473277125032122 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.terminal.telnet; import java.io.OutputStream; import java.io.PrintStream; public class TelnetPrintStream extends PrintStream { private final byte[] CRLF = new byte[]{(byte) '\r', (byte) '\n'}; public TelnetPrintStream(OutputStream out) { super(out); } public void println() { newLine(); } public void println(String x) { synchronized (this) { print(x); newLine(); } } public void println(long x) { synchronized (this) { print(x); newLine(); } } public void println(char x) { synchronized (this) { print(x); newLine(); } } public void println(boolean x) { synchronized (this) { print(x); newLine(); } } public void println(float x) { synchronized (this) { print(x); newLine(); } } public void println(double x) { synchronized (this) { print(x); newLine(); } } public void println(int x) { synchronized (this) { print(x); newLine(); } } public void println(char x[]) { synchronized (this) { print(x); newLine(); } } private void newLine() { try { this.write(CRLF); } catch (Exception e) { } } } xbean-3.7/xbean-telnet/src/test/0000755000175000017500000000000011610661034016506 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/0000755000175000017500000000000011610661034017427 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/org/0000755000175000017500000000000011610661034020216 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/org/apache/0000755000175000017500000000000011610661034021437 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661034022534 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/org/apache/xbean/telnet/0000755000175000017500000000000011610661034024027 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/test/java/org/apache/xbean/telnet/TelnetShellTest.java0000644000175000017500000000373710473277125030001 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.telnet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintStream; import junit.framework.TestCase; import org.apache.xbean.command.Command; import org.apache.xbean.command.CommandRegistry; import org.apache.xbean.terminal.telnet.TelnetShell; public class TelnetShellTest extends TestCase { public void testService() throws Exception { TestCommand.register(); TelnetShell telnetShell = new TelnetShell("acme"); ByteArrayInputStream in = new ByteArrayInputStream("test hello world\r\n".getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); telnetShell.service(in, out); // TODO test case still needs work System.out.println(new String(out.toByteArray())); } public static class TestCommand implements Command { public static void register() { CommandRegistry.register("test", TestCommand.class); } public int main(String[] args, InputStream in, PrintStream out) { out.print(args[0].length()); out.print(args[1].length()); return 0; } } } xbean-3.7/xbean-telnet/src/site/0000755000175000017500000000000011610661034016473 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/site/apt/0000755000175000017500000000000011610661034017257 5ustar drazzibdrazzibxbean-3.7/xbean-telnet/src/site/site.xml0000644000175000017500000000210010473277125020164 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/maven-xbean-plugin/0000755000175000017500000000000011610661034016047 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/pom.xml0000644000175000017500000000743011373256143017377 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 maven-xbean-plugin Apache XBean :: Maven Plugin maven-plugin ${pom.groupId} xbean-spring ${pom.version} org.springframework spring-beans 2.0.5 org.springframework spring-context 2.0.5 org.apache.maven maven-project 2.0 org.codehaus.plexus plexus-archiver 1.0-alpha-5 org.apache.maven maven-archiver 2.0 org.apache.maven maven-plugin-api 2.0 ant ant true com.thoughtworks.qdox qdox org.codehaus.plexus plexus-utils 1.1 org.apache.maven maven-artifact 2.0 org.apache.maven.plugins maven-plugin-plugin 2.2 xbean-3.7/maven-xbean-plugin/src/0000755000175000017500000000000011610661034016636 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/0000755000175000017500000000000011610661034017562 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/resources/0000755000175000017500000000000011610661034021574 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/resources/META-INF/0000755000175000017500000000000011610661034022734 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/0000755000175000017500000000000011610661034020503 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/org/0000755000175000017500000000000011610661034021272 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/org/apache/0000755000175000017500000000000011610661034022513 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661034023610 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/0000755000175000017500000000000011610661034024716 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/XBeanMojo.java0000644000175000017500000002314210670277373027423 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.maven; import java.beans.PropertyEditorManager; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.tools.ant.BuildException; import org.apache.xbean.spring.generator.DocumentationGenerator; import org.apache.xbean.spring.generator.GeneratorPlugin; import org.apache.xbean.spring.generator.LogFacade; import org.apache.xbean.spring.generator.MappingLoader; import org.apache.xbean.spring.generator.NamespaceMapping; import org.apache.xbean.spring.generator.QdoxMappingLoader; import org.apache.xbean.spring.generator.WikiDocumentationGenerator; import org.apache.xbean.spring.generator.XmlMetadataGenerator; import org.apache.xbean.spring.generator.XsdGenerator; /** * @author Guillaume Nodet * @version $Id: GenerateApplicationXmlMojo.java 314956 2005-10-12 16:27:15Z brett $ * @goal mapping * @description Creates xbean mapping file * @phase generate-sources * @requiresDependencyResolution compile */ public class XBeanMojo extends AbstractMojo implements LogFacade { /** * @parameter expression="${project}" * @required */ private MavenProject project; /** * Maven ProjectHelper * * @component */ protected MavenProjectHelper projectHelper; /** * @parameter * @required */ private String namespace; /** * @parameter expression="${basedir}/src/main/java" * @required */ private File srcDir; /** * @parameter */ private String excludedClasses; /** * @parameter expression="${basedir}/target/xbean/" * @required */ private File outputDir; /** * @parameter */ private File schema; /** * @parameter expression="org.apache.xbean.spring.context.impl" */ private String propertyEditorPaths; /** * @parameter schemaAsArtifact */ private boolean schemaAsArtifact = true; /** * @parameter */ private boolean generateSpringSchemasFile = true; /** * @parameter */ private boolean generateSpringHandlersFile = true; /** * A list of additional GeneratorPlugins that should get used executed * when generating output. * * @parameter */ private List generatorPlugins = Collections.emptyList(); public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug( " ======= XBeanMojo settings =======" ); getLog().debug( "namespace[" + namespace + "]" ); getLog().debug( "srcDir[" + srcDir + "]" ); getLog().debug( "schema[" + schema + "]" ); getLog().debug( "excludedClasses[" + excludedClasses + "]"); getLog().debug( "outputDir[" + outputDir + "]" ); getLog().debug( "propertyEditorPaths[" + propertyEditorPaths + "]" ); getLog().debug( "schemaAsArtifact[" + schemaAsArtifact + "]"); getLog().debug( "generateSpringSchemasFile[" + generateSpringSchemasFile + "]"); getLog().debug( "generateSpringHandlersFile[" + generateSpringHandlersFile + "]"); if (schema == null) { schema = new File(outputDir, project.getArtifactId() + ".xsd"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); for (StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); paths.hasMoreElements(); ) { //StringTokenizer implements Enumeration, not Enumeration !! editorSearchPath.add((String) paths.nextElement()); } PropertyEditorManager.setEditorSearchPath( editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { schema.getParentFile().mkdirs(); String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } Set dependencies = project.getDependencyArtifacts(); List sourceJars = new ArrayList(); sourceJars.add(srcDir); for (Artifact dependency : dependencies) { if ("sources".equals(dependency.getClassifier())) { File file = dependency.getFile(); sourceJars.add(file); } } File[] srcJars = sourceJars.toArray(new File[sourceJars.size()]); MappingLoader mappingLoader = new QdoxMappingLoader(namespace, srcJars, excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(outputDir.getAbsolutePath(), schema, generateSpringSchemasFile, generateSpringHandlersFile), new DocumentationGenerator(schema), new XsdGenerator(schema), new WikiDocumentationGenerator(schema), }; // load the mappings Thread.currentThread().setContextClassLoader(getClassLoader()); Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (NamespaceMapping namespaceMapping : namespaces) { for (GeneratorPlugin plugin : plugins) { plugin.setLog(this); plugin.generate(namespaceMapping); } for (GeneratorPlugin plugin : generatorPlugins) { plugin.setLog(this); plugin.generate(namespaceMapping); } } // Attach them as artifacts if (schemaAsArtifact) { projectHelper.attachArtifact(project, "xsd", null, schema); projectHelper.attachArtifact(project, "html", "schema", new File(schema.getAbsolutePath() + ".html")); } Resource res = new Resource(); res.setDirectory(outputDir.toString()); project.addResource(res); log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } public void log(String message) { getLog().info(message); } public void log(String message, int level) { getLog().info(message); } protected URLClassLoader getClassLoader() throws MojoExecutionException { try { Set urls = new HashSet(); URL mainClasses = new File(project.getBuild().getOutputDirectory()) .toURL(); getLog().debug("Adding to classpath : " + mainClasses); urls.add(mainClasses); URL testClasses = new File(project.getBuild() .getTestOutputDirectory()).toURL(); getLog().debug("Adding to classpath : " + testClasses); urls.add(testClasses); Set dependencies = project.getArtifacts(); Iterator iter = dependencies.iterator(); for (Artifact classPathElement : dependencies) { getLog().debug( "Adding artifact: " + classPathElement.getFile() + " to classpath"); urls.add(classPathElement.getFile().toURL()); } URLClassLoader appClassloader = new URLClassLoader(urls.toArray(new URL[urls.size()]), this.getClass().getClassLoader()); return appClassloader; } catch (MalformedURLException e) { throw new MojoExecutionException( "Error during setting up classpath", e); } } } xbean-3.7/maven-xbean-plugin/src/site/0000755000175000017500000000000011610661034017602 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/site/apt/0000755000175000017500000000000011610661034020366 5ustar drazzibdrazzibxbean-3.7/maven-xbean-plugin/src/site/site.xml0000644000175000017500000000210010473277125021273 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/NOTICE0000644000175000017500000000025011373255046013263 0ustar drazzibdrazzibApache XBean Copyright 2005-20010 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). xbean-3.7/xbean-bundleutils/0000755000175000017500000000000011610661034015777 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/pom.xml0000644000175000017500000000345411373256143017331 0ustar drazzibdrazzib 4.0.0 org.apache.xbean xbean 3.7 xbean-bundleutils bundle Apache XBean OSGI Bundle Utilitiess org.slf4j slf4j-api org.osgi org.osgi.core 4.2.0 provided xbean-3.7/xbean-bundleutils/src/0000755000175000017500000000000011610661033016565 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/0000755000175000017500000000000011610661033017511 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/0000755000175000017500000000000011610661033020432 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/0000755000175000017500000000000011610661033021221 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/0000755000175000017500000000000011610661033022442 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661033023537 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/0000755000175000017500000000000011610661033024500 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/0000755000175000017500000000000011610661033025751 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/0000755000175000017500000000000011610661034026727 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/jar/0000755000175000017500000000000011610661034027503 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/jar/BundleJarEntry.java0000644000175000017500000000703111365244010033235 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.osgi.bundle.util.jar; import java.io.IOException; import java.net.URL; import java.security.cert.Certificate; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.Manifest; import java.util.zip.ZipEntry; /** * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class BundleJarEntry extends JarEntry { private final URL entryURL; private final Manifest manifest; public BundleJarEntry(String name, URL entryURL, Manifest manifest) { super(removeSlash(name)); this.entryURL = entryURL; this.manifest = manifest; } private static String removeSlash(String name) { if (name.startsWith("/")) { name = name.substring(1); } return name; } public URL getEntryURL() { return entryURL; } public Attributes getAttributes() throws IOException { if (manifest == null) { return null; } return manifest.getAttributes(getName()); } public Certificate[] getCertificates() { return null; } public void setTime(long time) throws UnsupportedOperationException { throw new UnsupportedOperationException("Can not change the time of unpacked jar entry"); } public long getTime() { return -1; } public void setSize(long size) throws UnsupportedOperationException { throw new UnsupportedOperationException("Can not change the size of unpacked jar entry"); } public long getSize() { return -1; } public long getCompressedSize() { return getSize(); } public void setCompressedSize(long compressedSize) { throw new UnsupportedOperationException("Can not change the compressed size of unpacked jar entry"); } public long getCrc() { return super.getCrc(); } public void setCrc(long crc) { throw new UnsupportedOperationException("Can not change the crc of unpacked jar entry"); } public int getMethod() { return ZipEntry.STORED; } public void setMethod(int method) { throw new UnsupportedOperationException("Can not change the method of unpacked jar entry"); } public byte[] getExtra() { return null; } public void setExtra(byte[] extra) { throw new UnsupportedOperationException("Can not change the extra data of unpacked jar entry"); } public String getComment() { return null; } public void setComment(String comment) { throw new UnsupportedOperationException("Can not change the comment of unpacked jar entry"); } public boolean isDirectory() { return entryURL.getPath().endsWith("/"); } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/jar/BundleJarFile.java0000644000175000017500000001306011365244010033012 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.osgi.bundle.util.jar; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedList; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.osgi.framework.Bundle; /** * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class BundleJarFile extends JarFile { private static final File DUMMY_JAR_FILE; static { try { DUMMY_JAR_FILE = createTempFile(); new JarOutputStream(new FileOutputStream(BundleJarFile.DUMMY_JAR_FILE), new Manifest()).close(); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } private final Bundle bundle; private boolean manifestLoaded = false; private Manifest manifest; public BundleJarFile(Bundle bundle) throws IOException { super(DUMMY_JAR_FILE); this.bundle = bundle; } public Bundle getBundle() { return bundle; } public Manifest getManifest() throws IOException { if (!manifestLoaded) { URL manifestURL = bundle.getEntry("META-INF/MANIFEST.MF"); if (manifestURL != null) { InputStream in = null; try { in = manifestURL.openStream(); manifest = new Manifest(in); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } } } manifestLoaded = true; } return manifest; } public BundleJarEntry getBundleJarEntry(String name) { URL url = bundle.getEntry(name); if (url == null) { return null; } return new BundleJarEntry(name, url, getManifestSafe()); } public JarEntry getJarEntry(String name) { return getBundleJarEntry(name); } public ZipEntry getEntry(String name) { return getBundleJarEntry(name); } public Enumeration entries() { Manifest manifest = getManifestSafe(); Enumeration e = bundle.findEntries("/", "*", true); LinkedList entries = new LinkedList(); while (e.hasMoreElements()) { URL entryURL = (URL) e.nextElement(); entries.add(new BundleJarEntry(entryURL.getPath(), entryURL, manifest)); } return Collections.enumeration(entries); } public InputStream getInputStream(ZipEntry zipEntry) throws IOException { BundleJarEntry entry; if (zipEntry instanceof BundleJarEntry) { entry = (BundleJarEntry) zipEntry; } else { entry = getBundleJarEntry(zipEntry.getName()); } if (entry == null) { throw new IOException("Entry not found: name=" + zipEntry.getName()); } else if (entry.isDirectory()) { return new EmptyInputStream(); } else { return entry.getEntryURL().openStream(); } } public String getName() { return bundle.getSymbolicName(); } public int size() { return -1; } public void close() throws IOException { } private Manifest getManifestSafe() { Manifest manifest = null; try { manifest = getManifest(); } catch (IOException e) { // ignore } return manifest; } // be careful to clean up the temp file... we tell the vm to delete this on exit // but VMs can't be trusted to acutally delete the file private static File createTempFile() throws IOException { File tempFile = File.createTempFile("geronimo-fileutils", ".tmpfile"); tempFile.deleteOnExit(); return tempFile; } private static final class EmptyInputStream extends InputStream { public int read() { return -1; } public int read(byte b[]) { return -1; } public int read(byte b[], int off, int len) { return -1; } public long skip(long n) { return 0; } public int available() { return 0; } public void close() { } public synchronized void mark(int readlimit) { } public synchronized void reset() { } public boolean markSupported() { return false; } } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleDescription.java0000644000175000017500000002665211365244010033220 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.xbean.osgi.bundle.util.HeaderParser.HeaderElement; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * @version $Rev: 937957 $, $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class BundleDescription { private Map headers; public BundleDescription(Manifest manifest) { this.headers = manifestToMap(manifest); } public BundleDescription(Dictionary dictionary) { this.headers = new DictionaryMap(dictionary); } public BundleDescription(Map headers) { this.headers = headers; } /** * Returns a list of packages that are listed in Import-Package header. */ public List getImportPackage() { String headerValue = (String) headers.get(Constants.IMPORT_PACKAGE); List imports = new ArrayList(); List elements = HeaderParser.parseHeader(headerValue); for (HeaderElement element : elements) { ImportPackage p = new ImportPackage(element.getName(), element.getAttributes(), element.getDirectives()); imports.add(p); } return imports; } /** * Returns a list of packages that are listed in Export-Package header. */ public List getExportPackage() { String headerValue = (String) headers.get(Constants.EXPORT_PACKAGE); List exports = new ArrayList(); List elements = HeaderParser.parseHeader(headerValue); for (HeaderElement element : elements) { ExportPackage p = new ExportPackage(element.getName(), element.getAttributes(), element.getDirectives()); exports.add(p); } return exports; } /** * Returns a list of packages that are listed in Import-Package header * and are not listed in Export-Package header. */ public List getExternalImports() { List imports = getImportPackage(); List exports = getExportPackage(); List realImports = new ArrayList(); for (ImportPackage p : imports) { if (!isExported(exports, p)) { realImports.add(p); } } return realImports; } private static boolean isExported(List exports, ImportPackage p) { for (ExportPackage export : exports) { if (export.getName().equals(p.getName())) { return true; } } return false; } /** * Returns a list of bundle names that are listed in Require-Bundle header. */ public List getRequireBundle() { String headerValue = (String) headers.get(Constants.REQUIRE_BUNDLE); List requireBundles = new ArrayList(); List elements = HeaderParser.parseHeader(headerValue); for (HeaderElement element : elements) { RequireBundle p = new RequireBundle(element.getName(), element.getAttributes(), element.getDirectives()); requireBundles.add(p); } return requireBundles; } /** * Returns Fragment-Host header. */ public FragmentHost getFragmentHost() { String headerValue = (String) headers.get(Constants.FRAGMENT_HOST); List elements = HeaderParser.parseHeader(headerValue); if (elements.size() == 1) { HeaderElement element = elements.get(0); return new FragmentHost(element.getName(), element.getAttributes(), element.getDirectives()); } return null; } /** * Returns a list of packages that are listed in DynamicImport-Package header. */ public List getDynamicImportPackage() { String headerValue = (String) headers.get(Constants.DYNAMICIMPORT_PACKAGE); return parseStandardHeader(headerValue); } /** * Returns a list of paths that are listed in Bundle-ClassPath header. */ public List getBundleClassPath() { String headerValue = (String) headers.get(Constants.BUNDLE_CLASSPATH); return parseStandardHeader(headerValue); } public SymbolicName getSymbolicName() { String headerValue = (String) headers.get(Constants.BUNDLE_SYMBOLICNAME); List elements = HeaderParser.parseHeader(headerValue); if (elements.size() == 1) { HeaderElement element = elements.get(0); return new SymbolicName(element.getName(), element.getAttributes(), element.getDirectives()); } return null; } public Version getVersion() { String headerValue = (String) headers.get(Constants.BUNDLE_VERSION); return getVersionRange(headerValue).getLow(); } public Map getHeaders() { return headers; } private List parseStandardHeader(String headerValue) { List imports = new ArrayList(); List elements = HeaderParser.parseHeader(headerValue); for (HeaderElement element : elements) { HeaderEntry p = new HeaderEntry(element.getName(), element.getAttributes(), element.getDirectives()); imports.add(p); } return imports; } private static Map manifestToMap(Manifest manifest) { Attributes attributes = manifest.getMainAttributes(); Map headers = new HashMap(); for (Map.Entry entry : attributes.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); headers.put(key, value); } return headers; } private static VersionRange getVersionRange(String version) { if (version == null) { version = "0.0.0"; } return VersionRange.parse(version); } public static class HeaderEntry { private String name; private Map attributes; private Map directives; public HeaderEntry(String name, Map attributes, Map directives) { this.name = name; this.attributes = attributes; this.directives = directives; } public String getName() { return name; } public Map getAttributes() { return attributes; } public Map getDirectives() { return directives; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Name: ").append(name); builder.append(", Attributes: ").append(attributes); builder.append(", Directives: ").append(directives); return builder.toString(); } } public static class ExportPackage extends HeaderEntry { private Version version; public ExportPackage(String name, Map attributes, Map directives) { super(name, attributes, directives); version = BundleDescription.getVersionRange(attributes.get(Constants.VERSION_ATTRIBUTE)).getLow(); } public Version getVersion() { return version; } } public static class ImportPackage extends HeaderEntry { private boolean optional; private VersionRange versionRange; public ImportPackage(String name, Map attributes, Map directives) { super(name, attributes, directives); String resolution = directives.get(Constants.RESOLUTION_DIRECTIVE); optional = Constants.RESOLUTION_OPTIONAL.equals(resolution); versionRange = BundleDescription.getVersionRange(attributes.get(Constants.VERSION_ATTRIBUTE)); } public boolean isOptional() { return optional; } public boolean isMandatory() { return !optional; } public VersionRange getVersionRange() { return versionRange; } } public static class SymbolicName extends HeaderEntry { public SymbolicName(String name, Map attributes, Map directives) { super(name, attributes, directives); } } public static class RequireBundle extends HeaderEntry { private boolean optional; private VersionRange versionRange; public RequireBundle(String name, Map attributes, Map directives) { super(name, attributes, directives); String resolution = directives.get(Constants.RESOLUTION_DIRECTIVE); optional = Constants.RESOLUTION_OPTIONAL.equals(resolution); versionRange = BundleDescription.getVersionRange(attributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE)); } public boolean isOptional() { return optional; } public boolean isMandatory() { return !optional; } public VersionRange getVersionRange() { return versionRange; } } public static class FragmentHost extends HeaderEntry { private VersionRange versionRange; public FragmentHost(String name, Map attributes, Map directives) { super(name, attributes, directives); versionRange = BundleDescription.getVersionRange(attributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE)); } public VersionRange getVersionRange() { return versionRange; } } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleClassLoader.java0000644000175000017500000001574111365441602033134 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleReference; /** * ClassLoader for a {@link Bundle}. *
* In OSGi, resource lookup on resources in the META-INF directory using {@link Bundle#getResource(String)} or * {@link Bundle#getResources(String)} does not return the resources found in the wired bundles of the bundle * (wired via Import-Package or DynamicImport-Package). This class loader implementation provides * {@link #getResource(String) and {@link #getResources(String)} methods that do delegate such resource lookups to * the wired bundles. * * @version $Rev: 938291 $ $Date: 2010-04-27 03:53:06 +0200 (mar. 27 avril 2010) $ */ public class BundleClassLoader extends ClassLoader implements BundleReference { private final static String META_INF_1 = "META-INF/"; private final static String META_INF_2 = "/META-INF/"; private final Bundle bundle; private boolean searchWiredBundles; public BundleClassLoader(Bundle bundle) { this(bundle, true); } public BundleClassLoader(Bundle bundle, boolean searchWiredBundles) { this.bundle = bundle; this.searchWiredBundles = searchWiredBundles; } @Override public Class loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class clazz = bundle.loadClass(name); if (resolve) { resolveClass(clazz); } return clazz; } @Override public String toString() { return "[BundleClassLoader] " + bundle; } @Override public URL getResource(String name) { URL resource = bundle.getResource(name); if (resource == null && isMetaInfResource(name)) { LinkedHashSet wiredBundles = BundleUtils.getWiredBundles(bundle); Iterator iterator = wiredBundles.iterator(); while (iterator.hasNext() && resource == null) { resource = iterator.next().getResource(name); } } return resource; } @SuppressWarnings("unchecked") @Override public Enumeration getResources(String name) throws IOException { Enumeration e = (Enumeration) bundle.getResources(name); if (isMetaInfResource(name)) { ArrayList allResources = new ArrayList(); addToList(allResources, e); LinkedHashSet wiredBundles = BundleUtils.getWiredBundles(bundle); for (Bundle wiredBundle : wiredBundles) { Enumeration resources = wiredBundle.getResources(name); addToList(allResources, resources); } return Collections.enumeration(allResources); } else { if (e == null) { return Collections.enumeration(Collections.EMPTY_LIST); } else { return e; } } } public void setSearchWiredBundles(boolean search) { searchWiredBundles = search; } public boolean getSearchWiredBundles() { return searchWiredBundles; } private boolean isMetaInfResource(String name) { return searchWiredBundles && name != null && (name.startsWith(META_INF_1) || name.startsWith(META_INF_2)); } private void addToList(List list, Enumeration enumeration) { if (enumeration != null) { while (enumeration.hasMoreElements()) { list.add(enumeration.nextElement()); } } } /** * Return the bundle associated with this classloader. * * In most cases the bundle associated with the classloader is a regular framework bundle. * However, in some cases the bundle associated with the classloader is a {@link DelegatingBundle}. * In such cases, the unwrap parameter controls whether this function returns the * {@link DelegatingBundle} instance or the main application bundle backing with the {@link DelegatingBundle}. * * @param unwrap If true and if the bundle associated with this classloader is a {@link DelegatingBundle}, * this function will return the main application bundle backing with the {@link DelegatingBundle}. * Otherwise, the bundle associated with this classloader is returned as is. * @return The bundle associated with this classloader. */ public Bundle getBundle(boolean unwrap) { if (unwrap && bundle instanceof DelegatingBundle) { return ((DelegatingBundle) bundle).getMainBundle(); } return bundle; } /** * Return the bundle associated with this classloader. * * This method calls {@link #getBundle(boolean) getBundle(true)} and therefore always returns a regular * framework bundle. *

* Note: Some libraries use {@link BundleReference#getBundle()} to obtain a bundle for the given * classloader and expect the returned bundle instance to be work with any OSGi API. Some of these API might * not work if {@link DelegatingBundle} is returned. That is why this function will always return * a regular framework bundle. See {@link #getBundle(boolean)} for more information. * * @return The bundle associated with this classloader. */ public Bundle getBundle() { return getBundle(true); } @Override public int hashCode() { return bundle.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || !other.getClass().equals(getClass())) { return false; } BundleClassLoader otherBundleClassLoader = (BundleClassLoader) other; return this.bundle == otherBundleClassLoader.bundle; } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleUtils.java0000644000175000017500000001643411365244010032032 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.net.URL; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleReference; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; /** * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class BundleUtils { public static boolean canStart(Bundle bundle) { return (bundle.getState() != Bundle.UNINSTALLED) && (bundle.getState() != Bundle.STARTING) && (!isFragment(bundle)); } public static boolean canStop(Bundle bundle) { return (bundle.getState() != Bundle.UNINSTALLED) && (bundle.getState() != Bundle.STOPPING) && (!isFragment(bundle)); } public static boolean canUninstall(Bundle bundle) { return bundle.getState() != Bundle.UNINSTALLED; } public static boolean isFragment(Bundle bundle) { Dictionary headers = bundle.getHeaders(); return (headers != null && headers.get(Constants.FRAGMENT_HOST) != null); } /** * Returns bundle (if any) associated with current thread's context classloader. * * @param unwrap if true and if the bundle associated with the context classloader is a * {@link DelegatingBundle}, this function will return the main application bundle * backing with the {@link DelegatingBundle}. Otherwise, the bundle associated with * the context classloader is returned as is. See {@link BundleClassLoader#getBundle(boolean)} * for more information. * @return The bundle associated with the current thread's context classloader. Might be null. */ public static Bundle getContextBundle(boolean unwrap) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader instanceof BundleClassLoader) { return ((BundleClassLoader) classLoader).getBundle(unwrap); } else if (classLoader instanceof BundleReference) { return ((BundleReference) classLoader).getBundle(); } else { return null; } } /** * Works like {@link Bundle#getEntryPaths(String)} but also returns paths * in attached fragment bundles. * * @param bundle * @param name * @return */ public static Enumeration getEntryPaths(Bundle bundle, String name) { Enumeration entries = bundle.findEntries(name, null, false); if (entries == null) { return null; } LinkedHashSet paths = new LinkedHashSet(); while (entries.hasMoreElements()) { URL url = entries.nextElement(); String path = url.getPath(); if (path.startsWith("/")) { path = path.substring(1); } paths.add(path); } return Collections.enumeration(paths); } /** * Works like {@link Bundle#getEntry(String)} but also checks * attached fragment bundles for the given entry. * * @param bundle * @param name * @return */ public static URL getEntry(Bundle bundle, String name) { if (name.equals("/")) { return bundle.getEntry(name); } else if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } String path; String pattern; int pos = name.lastIndexOf("/"); if (pos == -1) { path = "/"; pattern = name; } else if (pos == 0) { path = "/"; pattern = name.substring(1); } else { path = name.substring(0, pos); pattern = name.substring(pos + 1); } Enumeration entries = bundle.findEntries(path, pattern, false); if (entries != null && entries.hasMoreElements()) { return entries.nextElement(); } else { return null; } } public static LinkedHashSet getWiredBundles(Bundle bundle) { ServiceReference reference = bundle.getBundleContext().getServiceReference(PackageAdmin.class.getName()); PackageAdmin packageAdmin = (PackageAdmin) bundle.getBundleContext().getService(reference); try { return getWiredBundles(packageAdmin, bundle); } finally { bundle.getBundleContext().ungetService(reference); } } public static LinkedHashSet getWiredBundles(PackageAdmin packageAdmin, Bundle bundle) { BundleDescription description = new BundleDescription(bundle.getHeaders()); // handle static wire via Import-Package List imports = description.getExternalImports(); LinkedHashSet wiredBundles = new LinkedHashSet(); for (BundleDescription.ImportPackage packageImport : imports) { ExportedPackage[] exports = packageAdmin.getExportedPackages(packageImport.getName()); Bundle wiredBundle = getWiredBundle(bundle, exports); if (wiredBundle != null) { wiredBundles.add(wiredBundle); } } // handle dynamic wire via DynamicImport-Package if (!description.getDynamicImportPackage().isEmpty()) { for (Bundle b : bundle.getBundleContext().getBundles()) { if (!wiredBundles.contains(b)) { ExportedPackage[] exports = packageAdmin.getExportedPackages(b); Bundle wiredBundle = getWiredBundle(bundle, exports); if (wiredBundle != null) { wiredBundles.add(wiredBundle); } } } } return wiredBundles; } private static Bundle getWiredBundle(Bundle bundle, ExportedPackage[] exports) { if (exports != null) { for (ExportedPackage exportedPackage : exports) { Bundle[] importingBundles = exportedPackage.getImportingBundles(); if (importingBundles != null) { for (Bundle importingBundle : importingBundles) { if (importingBundle == bundle) { return exportedPackage.getExportingBundle(); } } } } } return null; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/ResourceDiscoveryFilter.javaxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/ResourceDiscoveryFilter.0000644000175000017500000000224211367010247033560 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.osgi.bundle.util; /** * @version $Rev: 939977 $ $Date: 2010-05-01 13:29:43 +0200 (sam. 01 mai 2010) $ */ public interface ResourceDiscoveryFilter { public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange); public boolean zipFileDiscoveryRequired(String url); public boolean directoryDiscoveryRequired(String url); } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/HeaderParser.java0000644000175000017500000001304011365244010032133 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility class to parse standard OSGi headers. * * @version $Rev: 937957 $, $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class HeaderParser { /** * Parse a given OSGi header into a list of header elements. * * @param header the OSGi header to parse * @return the list of header elements extracted from this header */ public static List parseHeader(String header) { List elements = new ArrayList(); if (header == null || header.trim().length() == 0) { return elements; } List clauses = parseDelimitedString(header, ",", false); for (String clause : clauses) { String[] tokens = clause.split(";"); if (tokens.length < 1) { throw new IllegalArgumentException("Invalid header clause: " + clause); } HeaderElement elem = new HeaderElement(tokens[0].trim()); elements.add(elem); for (int i = 1; i < tokens.length; i++) { int pos = tokens[i].indexOf('='); if (pos != -1) { if (pos > 0 && tokens[i].charAt(pos - 1) == ':') { String name = tokens[i].substring(0, pos - 1).trim(); String value = tokens[i].substring(pos + 1).trim(); elem.addDirective(name, value); } else { String name = tokens[i].substring(0, pos).trim(); String value = tokens[i].substring(pos + 1).trim(); elem.addAttribute(name, value); } } else { elem = new HeaderElement(tokens[i].trim()); elements.add(elem); } } } return elements; } private static List parseDelimitedString(String value, String delim, boolean includeQuotes) { if (value == null) { value = ""; } List list = new ArrayList(); int CHAR = 1; int DELIMITER = 2; int STARTQUOTE = 4; int ENDQUOTE = 8; StringBuffer sb = new StringBuffer(); int expecting = (CHAR | DELIMITER | STARTQUOTE); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); boolean isDelimiter = (delim.indexOf(c) >= 0); boolean isQuote = (c == '"'); if (isDelimiter && ((expecting & DELIMITER) > 0)) { list.add(sb.toString().trim()); sb.delete(0, sb.length()); expecting = (CHAR | DELIMITER | STARTQUOTE); } else if (isQuote && ((expecting & STARTQUOTE) > 0)) { if (includeQuotes) { sb.append(c); } expecting = CHAR | ENDQUOTE; } else if (isQuote && ((expecting & ENDQUOTE) > 0)) { if (includeQuotes) { sb.append(c); } expecting = (CHAR | STARTQUOTE | DELIMITER); } else if ((expecting & CHAR) > 0) { sb.append(c); } else { throw new IllegalArgumentException("Invalid delimited string: " + value); } } if (sb.length() > 0) { list.add(sb.toString().trim()); } return list; } public static class HeaderElement { private String path; private Map attributes; private Map directives; public HeaderElement(String path) { this.path = path; this.attributes = new HashMap(); this.directives = new HashMap(); } public String getName() { return this.path; } public Map getAttributes() { return attributes; } public String getAttribute(String name) { return attributes.get(name); } public void addAttribute(String name, String value) { attributes.put(name, value); } public Map getDirectives() { return directives; } public String getDirective(String name) { return directives.get(name); } public void addDirective(String name, String value) { directives.put(name, value); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/DelegatingBundleContext.javaxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/DelegatingBundleContext.0000644000175000017500000001100311365244010033463 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.io.File; import java.io.InputStream; import java.util.Dictionary; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.BundleListener; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkListener; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; /** * BundleContext for DelegatingBundle. * * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class DelegatingBundleContext implements BundleContext { private DelegatingBundle bundle; private BundleContext bundleContext; public DelegatingBundleContext(DelegatingBundle bundle, BundleContext bundleContext) { this.bundle = bundle; this.bundleContext = bundleContext; } public Bundle getBundle() { return bundle; } public void addBundleListener(BundleListener arg0) { bundleContext.addBundleListener(arg0); } public void addFrameworkListener(FrameworkListener arg0) { bundleContext.addFrameworkListener(arg0); } public void addServiceListener(ServiceListener arg0, String arg1) throws InvalidSyntaxException { bundleContext.addServiceListener(arg0, arg1); } public void addServiceListener(ServiceListener arg0) { bundleContext.addServiceListener(arg0); } public Filter createFilter(String arg0) throws InvalidSyntaxException { return bundleContext.createFilter(arg0); } public ServiceReference[] getAllServiceReferences(String arg0, String arg1) throws InvalidSyntaxException { return bundleContext.getAllServiceReferences(arg0, arg1); } public Bundle getBundle(long arg0) { return bundleContext.getBundle(arg0); } public Bundle[] getBundles() { return bundleContext.getBundles(); } public File getDataFile(String arg0) { return bundleContext.getDataFile(arg0); } public String getProperty(String arg0) { return bundleContext.getProperty(arg0); } public Object getService(ServiceReference arg0) { return bundleContext.getService(arg0); } public ServiceReference getServiceReference(String arg0) { return bundleContext.getServiceReference(arg0); } public ServiceReference[] getServiceReferences(String arg0, String arg1) throws InvalidSyntaxException { return bundleContext.getServiceReferences(arg0, arg1); } public Bundle installBundle(String arg0, InputStream arg1) throws BundleException { return bundleContext.installBundle(arg0, arg1); } public Bundle installBundle(String arg0) throws BundleException { return bundleContext.installBundle(arg0); } public ServiceRegistration registerService(String arg0, Object arg1, Dictionary arg2) { return bundleContext.registerService(arg0, arg1, arg2); } public ServiceRegistration registerService(String[] arg0, Object arg1, Dictionary arg2) { return bundleContext.registerService(arg0, arg1, arg2); } public void removeBundleListener(BundleListener arg0) { bundleContext.removeBundleListener(arg0); } public void removeFrameworkListener(FrameworkListener arg0) { bundleContext.removeFrameworkListener(arg0); } public void removeServiceListener(ServiceListener arg0) { bundleContext.removeServiceListener(arg0); } public boolean ungetService(ServiceReference arg0) { return bundleContext.ungetService(arg0); } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/DiscoveryRange.java0000644000175000017500000000203711365244010032516 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.osgi.bundle.util; /** * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public enum DiscoveryRange { REQUIRED_BUNDLES, IMPORT_PACKAGES, BUNDLE_CLASSPATH, FRAGMENT_BUNDLES } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/VersionRange.java0000644000175000017500000000662311365244010032201 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import org.osgi.framework.Version; public class VersionRange { private Version low = null; private boolean isLowInclusive = false; private Version high = null; private boolean isHighInclusive = false; public static final VersionRange infiniteRange = new VersionRange(Version.emptyVersion, true, null, true); public VersionRange(Version low, boolean isLowInclusive, Version high, boolean isHighInclusive) { this.low = low; this.isLowInclusive = isLowInclusive; this.high = high; this.isHighInclusive = isHighInclusive; } public Version getLow() { return low; } public boolean isLowInclusive() { return isLowInclusive; } public Version getHigh() { return high; } public boolean isHighInclusive() { return isHighInclusive; } public boolean isInRange(Version version) { // We might not have an upper end to the range. if (high == null) { return (version.compareTo(low) >= 0); } else if (isLowInclusive() && isHighInclusive()) { return (version.compareTo(low) >= 0) && (version.compareTo(high) <= 0); } else if (isHighInclusive()) { return (version.compareTo(low) > 0) && (version.compareTo(high) <= 0); } else if (isLowInclusive()) { return (version.compareTo(low) >= 0) && (version.compareTo(high) < 0); } return (version.compareTo(low) > 0) && (version.compareTo(high) < 0); } public static VersionRange parse(String range) { // Check if the version is an interval. if (range.indexOf(',') >= 0) { String s = range.substring(1, range.length() - 1); String vlo = s.substring(0, s.indexOf(',')).trim(); String vhi = s.substring(s.indexOf(',') + 1, s.length()).trim(); return new VersionRange ( new Version(vlo), (range.charAt(0) == '['), new Version(vhi), (range.charAt(range.length() - 1) == ']')); } else { return new VersionRange(new Version(range), true, null, false); } } public String toString() { if (high != null) { StringBuffer sb = new StringBuffer(); sb.append(isLowInclusive ? '[' : '('); sb.append(low.toString()); sb.append(','); sb.append(high.toString()); sb.append(isHighInclusive ? ']' : ')'); return sb.toString(); } else { return low.toString(); } } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/DelegatingBundle.java0000644000175000017500000001272211365244010032771 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.List; import java.util.Map; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; /** * Bundle that delegates ClassLoader operations to a collection of {@link Bundle} objects. * * @version $Rev: 937957 $ $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class DelegatingBundle implements Bundle { private Collection bundles; private Bundle bundle; private BundleContext bundleContext; public DelegatingBundle(Collection bundles) { this.bundles = bundles; if (bundles.isEmpty()) { throw new IllegalArgumentException("At least one bundle is required"); } // assume first Bundle is the main bundle this.bundle = bundles.iterator().next(); this.bundleContext = new DelegatingBundleContext(this, bundle.getBundleContext()); } public Bundle getMainBundle() { return bundle; } public Class loadClass(String name) throws ClassNotFoundException { for (Bundle bundle : bundles) { try { return bundle.loadClass(name); } catch (ClassNotFoundException ex) { // ignore } } throw new ClassNotFoundException(name); } public URL getResource(String name) { URL resource = null; for (Bundle bundle : bundles) { resource = bundle.getResource(name); if (resource != null) { return resource; } } return null; } public Enumeration getResources(String name) throws IOException { ArrayList allResources = new ArrayList(); for (Bundle bundle : bundles) { Enumeration e = (Enumeration) bundle.getResources(name); addToList(allResources, e); } return Collections.enumeration(allResources); } private static void addToList(List list, Enumeration enumeration) { if (enumeration != null) { while (enumeration.hasMoreElements()) { list.add(enumeration.nextElement()); } } } public BundleContext getBundleContext() { return bundleContext; } public Enumeration findEntries(String arg0, String arg1, boolean arg2) { return bundle.findEntries(arg0, arg1, arg2); } public long getBundleId() { return bundle.getBundleId(); } public URL getEntry(String arg0) { return bundle.getEntry(arg0); } public Enumeration getEntryPaths(String arg0) { return bundle.getEntryPaths(arg0); } public Dictionary getHeaders() { return bundle.getHeaders(); } public Dictionary getHeaders(String arg0) { return bundle.getHeaders(arg0); } public long getLastModified() { return bundle.getLastModified(); } public String getLocation() { return bundle.getLocation(); } public ServiceReference[] getRegisteredServices() { return bundle.getRegisteredServices(); } public ServiceReference[] getServicesInUse() { return bundle.getServicesInUse(); } public Map getSignerCertificates(int arg0) { return bundle.getSignerCertificates(arg0); } public int getState() { return bundle.getState(); } public String getSymbolicName() { return bundle.getSymbolicName(); } public Version getVersion() { return bundle.getVersion(); } public boolean hasPermission(Object arg0) { return bundle.hasPermission(arg0); } public void start() throws BundleException { bundle.start(); } public void start(int arg0) throws BundleException { bundle.start(arg0); } public void stop() throws BundleException { bundle.stop(); } public void stop(int arg0) throws BundleException { bundle.stop(arg0); } public void uninstall() throws BundleException { bundle.uninstall(); } public void update() throws BundleException { bundle.update(); } public void update(InputStream arg0) throws BundleException { bundle.update(arg0); } public String toString() { return "[DelegatingBundle: " + bundles + "]"; } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/DictionaryMap.java0000644000175000017500000000374611365244010032345 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.util.AbstractMap; import java.util.Dictionary; import java.util.Set; /** * Simple wrapper that exposes {@link Dictionary} class as a {@link Map}. * * @version $Rev: 937957 $, $Date: 2010-04-26 10:00:08 +0200 (lun. 26 avril 2010) $ */ public class DictionaryMap extends AbstractMap { private final Dictionary dictionary; public DictionaryMap(Dictionary dictionary) { this.dictionary = dictionary; } @Override public Object get(Object key) { return dictionary.get(key); } @Override public Object put(Object key, Object value) { return dictionary.put(key, value); } @Override public Object remove(Object key) { return dictionary.remove(key); } @Override public int size() { return dictionary.size(); } @Override public boolean isEmpty() { return dictionary.isEmpty(); } @Override public Set entrySet() { // TODO: implement throw new UnsupportedOperationException(); } @Override public Set keySet() { // TODO: implement throw new UnsupportedOperationException(); } } xbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleClassFinder.java0000644000175000017500000004033311371713340033126 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.xbean.osgi.bundle.util.BundleDescription.ExportPackage; import org.apache.xbean.osgi.bundle.util.BundleDescription.HeaderEntry; import org.apache.xbean.osgi.bundle.util.BundleDescription.RequireBundle; import org.osgi.framework.Bundle; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.packageadmin.RequiredBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Finds all available classes to a bundle by scanning Bundle-ClassPath, * Import-Package, and Require-Bundle headers of the given bundle and its fragments. * DynamicImport-Package header is not considered during scanning. * * @version $Rev: 942661 $ $Date: 2010-05-10 07:17:20 +0200 (lun. 10 mai 2010) $ */ public class BundleClassFinder { private static final Logger logger = LoggerFactory.getLogger(BundleClassFinder.class); public static final ClassDiscoveryFilter FULL_CLASS_DISCOVERY_FILTER = new DummyDiscoveryFilter(); public static final ClassDiscoveryFilter IMPORTED_PACKAGE_EXCLUSIVE_FILTER = new NonImportedPackageDiscoveryFilter(); protected static final String EXT = ".class"; protected static final String PATTERN = "*.class"; protected Bundle bundle; protected PackageAdmin packageAdmin; private Map> classMap; protected ClassDiscoveryFilter discoveryFilter; public BundleClassFinder(PackageAdmin packageAdmin, Bundle bundle) { this(packageAdmin, bundle, FULL_CLASS_DISCOVERY_FILTER); } public BundleClassFinder(PackageAdmin packageAdmin, Bundle bundle, ClassDiscoveryFilter discoveryFilter) { this.packageAdmin = packageAdmin; this.bundle = bundle; this.discoveryFilter = discoveryFilter; } public List loadClasses(Set classes) { List loadedClasses = new ArrayList(classes.size()); for (String clazz : classes) { try { loadedClasses.add(bundle.loadClass(clazz)); } catch (Exception ignore) { // ignore } } return loadedClasses; } /** * Finds all available classes to the bundle. Some of the classes in the returned set * might not be loadable. * * @return classes visible to the bundle. Not all classes returned might be loadable. */ public Set find() { Set classes = new LinkedHashSet(); classMap = new HashMap>(); if (discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.IMPORT_PACKAGES)) { scanImportPackages(classes, bundle, bundle); } if (discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.REQUIRED_BUNDLES)) { scanRequireBundles(classes, bundle); } if (discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.BUNDLE_CLASSPATH)) { scanBundleClassPath(classes, bundle); } if (discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.FRAGMENT_BUNDLES)) { Bundle[] fragments = packageAdmin.getFragments(bundle); if (fragments != null) { for (Bundle fragment : fragments) { scanImportPackages(classes, bundle, fragment); scanRequireBundles(classes, fragment); scanBundleClassPath(classes, fragment); } } } classMap.clear(); return classes; } protected boolean isClassAcceptable(String name, InputStream in) throws IOException { return true; } protected boolean isClassAcceptable(URL url) { return true; } protected BundleClassFinder createSubBundleClassFinder(PackageAdmin packageAdmin, Bundle bundle, ClassDiscoveryFilter classDiscoveryFilter) { return new BundleClassFinder(packageAdmin, bundle, classDiscoveryFilter); } protected String toJavaStyleClassName(String name) { if (name.endsWith(EXT)) { name = name.substring(0, name.length() - EXT.length()); } name = name.replace('/', '.'); return name; } /** * Get the normal Java style package name from the parameter className. * If the className is ended with .class extension, e.g. /org/apache/geronimo/TestCass.class or org.apache.geronimo.TestClass.class, * then org/apache/geronimo is returned * If the className is not ended with .class extension, e.g. /org/apache/geronimo/TestCass or org.apache.geronimo.TestClass, * then org/apache/geronimo is returned * @return Normal Java style package name, should be like org.apache.geronimo */ protected String toJavaStylePackageName(String className) { if (className.endsWith(EXT)) { className = className.substring(0, className.length() - EXT.length()); } className = className.replace('/', '.'); int iLastDotIndex = className.lastIndexOf('.'); if (iLastDotIndex != -1) { return className.substring(0, iLastDotIndex); } else { return ""; } } private Set findAllClasses(Bundle bundle, ClassDiscoveryFilter userClassDiscoveryFilter, Set exportedPackageNames) { Set allClasses = classMap.get(bundle); if (allClasses == null) { BundleClassFinder finder = createSubBundleClassFinder(packageAdmin, bundle, new ImportExclusivePackageDiscoveryFilterAdapter(userClassDiscoveryFilter, exportedPackageNames)); allClasses = finder.find(); classMap.put(bundle, allClasses); } return allClasses; } private Set findAllClasses(Bundle bundle, String packageName) { Set allClasses = classMap.get(bundle); if (allClasses == null) { BundleClassFinder finder = createSubBundleClassFinder(packageAdmin, bundle, new ImportExclusivePackageDiscoveryFilter(packageName)); allClasses = finder.find(); classMap.put(bundle, allClasses); } return allClasses; } private void scanImportPackages(Collection classes, Bundle host, Bundle fragment) { BundleDescription description = new BundleDescription(fragment.getHeaders()); List imports = description.getExternalImports(); for (BundleDescription.ImportPackage packageImport : imports) { String packageName = packageImport.getName(); if (discoveryFilter.packageDiscoveryRequired(packageName)) { ExportedPackage[] exports = packageAdmin.getExportedPackages(packageName); Bundle wiredBundle = isWired(host, exports); if (wiredBundle != null) { Set allClasses = findAllClasses(wiredBundle, packageName); classes.addAll(allClasses); } } } } private void scanRequireBundles(Collection classes, Bundle bundle) { BundleDescription description = new BundleDescription(bundle.getHeaders()); List requiredBundleList = description.getRequireBundle(); for (RequireBundle requiredBundle : requiredBundleList) { RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(requiredBundle.getName()); Bundle wiredBundle = isWired(bundle, requiredBundles); if (wiredBundle != null) { BundleDescription wiredBundleDescription = new BundleDescription(wiredBundle.getHeaders()); List exportPackages = wiredBundleDescription.getExportPackage(); Set exportedPackageNames = new HashSet(); for (ExportPackage exportPackage : exportPackages) { exportedPackageNames.add(exportPackage.getName()); } Set allClasses = findAllClasses(wiredBundle, discoveryFilter, exportedPackageNames); classes.addAll(allClasses); } } } private void scanBundleClassPath(Collection resources, Bundle bundle) { BundleDescription description = new BundleDescription(bundle.getHeaders()); List paths = description.getBundleClassPath(); if (paths.isEmpty()) { scanDirectory(resources, bundle, "/"); } else { for (HeaderEntry path : paths) { String name = path.getName(); if (name.equals(".") || name.equals("/")) { // scan root scanDirectory(resources, bundle, "/"); } else if (name.endsWith(".jar") || name.endsWith(".zip")) { // scan embedded jar/zip scanZip(resources, bundle, name); } else { // assume it's a directory scanDirectory(resources, bundle, "/" + name); } } } } private void scanDirectory(Collection classes, Bundle bundle, String basePath) { basePath = addSlash(basePath); if (!discoveryFilter.directoryDiscoveryRequired(basePath)) { return; } Enumeration e = bundle.findEntries(basePath, PATTERN, true); if (e != null) { while (e.hasMoreElements()) { URL u = e.nextElement(); String entryName = u.getPath().substring(basePath.length()); if (discoveryFilter.packageDiscoveryRequired(toJavaStylePackageName(entryName))) { if (isClassAcceptable(u)) { classes.add(toJavaStyleClassName(entryName)); } } } } } private void scanZip(Collection classes, Bundle bundle, String zipName) { if (!discoveryFilter.jarFileDiscoveryRequired(zipName)) { return; } URL zipEntry = bundle.getEntry(zipName); if (zipEntry == null) { return; } ZipInputStream in = null; try { in = new ZipInputStream(zipEntry.openStream()); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String name = entry.getName(); if (name.endsWith(EXT) && discoveryFilter.packageDiscoveryRequired(toJavaStylePackageName(name))) { if (isClassAcceptable(name, in)) { classes.add(toJavaStyleClassName(name)); } } } } catch (IOException ignore) { logger.warn("Fail to check zip file " + zipName, ignore); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } protected String addSlash(String name) { if (!name.endsWith("/")) { name = name + "/"; } return name; } protected Bundle isWired(Bundle bundle, ExportedPackage[] exports) { if (exports != null) { for (ExportedPackage exportedPackage : exports) { Bundle[] importingBundles = exportedPackage.getImportingBundles(); if (importingBundles != null) { for (Bundle importingBundle : importingBundles) { if (importingBundle == bundle) { return exportedPackage.getExportingBundle(); } } } } } return null; } protected Bundle isWired(Bundle bundle, RequiredBundle[] requiredBundles) { if (requiredBundles != null) { for (RequiredBundle requiredBundle : requiredBundles) { Bundle[] requiringBundles = requiredBundle.getRequiringBundles(); if (requiringBundles != null) { for (Bundle requiringBundle : requiringBundles) { if (requiringBundle == bundle) { return requiredBundle.getBundle(); } } } } } return null; } public static class DummyDiscoveryFilter implements ClassDiscoveryFilter { public boolean directoryDiscoveryRequired(String url) { return true; } public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange) { return true; } public boolean jarFileDiscoveryRequired(String url) { return true; } public boolean packageDiscoveryRequired(String packageName) { return true; } } public static class NonImportedPackageDiscoveryFilter implements ClassDiscoveryFilter { public boolean directoryDiscoveryRequired(String url) { return true; } public boolean jarFileDiscoveryRequired(String url) { return true; } public boolean packageDiscoveryRequired(String packageName) { return true; } public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange) { return !discoveryRange.equals(DiscoveryRange.IMPORT_PACKAGES); } } private static class ImportExclusivePackageDiscoveryFilter implements ClassDiscoveryFilter { private String expectedPckageName; public ImportExclusivePackageDiscoveryFilter(String expectedPckageName) { this.expectedPckageName = expectedPckageName; } public boolean directoryDiscoveryRequired(String url) { return true; } public boolean jarFileDiscoveryRequired(String url) { return true; } public boolean packageDiscoveryRequired(String packageName) { return expectedPckageName.equals(packageName); } public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange) { return !discoveryRange.equals(DiscoveryRange.IMPORT_PACKAGES); } } private static class ImportExclusivePackageDiscoveryFilterAdapter implements ClassDiscoveryFilter { private Set acceptedPackageNames; private ClassDiscoveryFilter classDiscoveryFilter; public ImportExclusivePackageDiscoveryFilterAdapter(ClassDiscoveryFilter classDiscoveryFilter, Set acceptedPackageNames) { this.classDiscoveryFilter = classDiscoveryFilter; this.acceptedPackageNames = acceptedPackageNames; } public boolean directoryDiscoveryRequired(String url) { return true; } public boolean jarFileDiscoveryRequired(String url) { return true; } public boolean packageDiscoveryRequired(String packageName) { return acceptedPackageNames.contains(packageName) && classDiscoveryFilter.packageDiscoveryRequired(packageName); } public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange) { return !discoveryRange.equals(DiscoveryRange.IMPORT_PACKAGES); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/ClassDiscoveryFilter.javaxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/ClassDiscoveryFilter.jav0000644000175000017500000000234111367010247033537 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.osgi.bundle.util; /** * @version $Rev: 939977 $ $Date: 2010-05-01 13:29:43 +0200 (sam. 01 mai 2010) $ */ public interface ClassDiscoveryFilter { public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange); public boolean jarFileDiscoveryRequired(String url); public boolean directoryDiscoveryRequired(String url); public boolean packageDiscoveryRequired(String packageName); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleResourceFinder.javaxbean-3.7/xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleResourceFinder.jav0000644000175000017500000001762311371713340033515 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.xbean.osgi.bundle.util.BundleDescription.HeaderEntry; import org.osgi.framework.Bundle; import org.osgi.service.packageadmin.PackageAdmin; /** * Finds all available resources to a bundle by scanning Bundle-ClassPath header * of the given bundle and its fragments. * DynamicImport-Package header is not considered during scanning. * * @version $Rev: 942661 $ $Date: 2010-05-10 07:17:20 +0200 (lun. 10 mai 2010) $ */ public class BundleResourceFinder { public static final ResourceDiscoveryFilter FULL_DISCOVERY_FILTER = new DummyDiscoveryFilter(); private final Bundle bundle; private final PackageAdmin packageAdmin; private final String prefix; private final String suffix; private ResourceDiscoveryFilter discoveryFilter; public BundleResourceFinder(PackageAdmin packageAdmin, Bundle bundle, String prefix, String suffix) { this(packageAdmin, bundle, prefix, suffix, FULL_DISCOVERY_FILTER); } public BundleResourceFinder(PackageAdmin packageAdmin, Bundle bundle, String prefix, String suffix, ResourceDiscoveryFilter discoveryFilter) { this.packageAdmin = packageAdmin; this.bundle = bundle; this.prefix = prefix.trim(); this.suffix = suffix.trim(); this.discoveryFilter = discoveryFilter; } public void find(ResourceFinderCallback callback) throws Exception { if (discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.BUNDLE_CLASSPATH)) { scanBundleClassPath(callback, bundle); } if (packageAdmin != null && discoveryFilter.rangeDiscoveryRequired(DiscoveryRange.FRAGMENT_BUNDLES)) { Bundle[] fragments = packageAdmin.getFragments(bundle); if (fragments != null) { for (Bundle fragment : fragments) { scanBundleClassPath(callback, fragment); } } } } public Set find() { Set resources = new LinkedHashSet(); try { find(new DefaultResourceFinderCallback(resources)); } catch (Exception e) { // this should not happen throw new RuntimeException("Resource discovery failed", e); } return resources; } private void scanBundleClassPath(ResourceFinderCallback callback, Bundle bundle) throws Exception { BundleDescription desc = new BundleDescription(bundle.getHeaders()); List paths = desc.getBundleClassPath(); if (paths.isEmpty()) { scanDirectory(callback, bundle, prefix); } else { for (HeaderEntry path : paths) { String name = path.getName(); if (name.equals(".") || name.equals("/")) { // scan root scanDirectory(callback, bundle, prefix); } else if (name.endsWith(".jar") || name.endsWith(".zip")) { // scan embedded jar/zip scanZip(callback, bundle, name); } else { // assume it's a directory scanDirectory(callback, bundle, addSlash(prefix) + name); } } } } private void scanDirectory(ResourceFinderCallback callback, Bundle bundle, String basePath) throws Exception { if (!discoveryFilter.directoryDiscoveryRequired(basePath)) { return; } Enumeration e = bundle.findEntries(basePath, "*" + suffix, true); if (e != null) { while (e.hasMoreElements()) { callback.foundInDirectory(bundle, basePath, (URL) e.nextElement()); } } } private void scanZip(ResourceFinderCallback callback, Bundle bundle, String zipName) throws Exception { if (!discoveryFilter.zipFileDiscoveryRequired(zipName)) { return; } URL zipEntry = bundle.getEntry(zipName); if (zipEntry == null) { return; } try { ZipInputStream in = new ZipInputStream(zipEntry.openStream()); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String name = entry.getName(); if (prefixMatches(name) && suffixMatches(name)) { callback.foundInJar(bundle, zipName, entry, new ZipEntryInputStream(in)); } } } catch (IOException e) { e.printStackTrace(); } } private static class ZipEntryInputStream extends FilterInputStream { public ZipEntryInputStream(ZipInputStream in) { super(in); } public void close() throws IOException { // not really necessary // ((ZipInputStream) in).closeEntry(); } } private boolean prefixMatches(String name) { if (prefix.length() == 0 || prefix.equals(".") || prefix.equals("/")) { return true; } else if (prefix.startsWith("/")) { return name.startsWith(prefix, 1); } else { return name.startsWith(prefix); } } private boolean suffixMatches(String name) { return (suffix.length() == 0) ? true : name.endsWith(suffix); } private static String addSlash(String name) { if (!name.endsWith("/")) { name = name + "/"; } return name; } public interface ResourceFinderCallback { void foundInDirectory(Bundle bundle, String baseDir, URL url) throws Exception; void foundInJar(Bundle bundle, String jarName, ZipEntry entry, InputStream in) throws Exception; } public static class DefaultResourceFinderCallback implements ResourceFinderCallback { private Set resources; public DefaultResourceFinderCallback() { this(new LinkedHashSet()); } public DefaultResourceFinderCallback(Set resources) { this.resources = resources; } public Set getResources() { return resources; } public void foundInDirectory(Bundle bundle, String baseDir, URL url) throws Exception { resources.add(url); } public void foundInJar(Bundle bundle, String jarName, ZipEntry entry, InputStream in) throws Exception { URL jarURL = bundle.getEntry(jarName); URL url = new URL("jar:" + jarURL.toString() + "!/" + entry.getName()); resources.add(url); } } public static class DummyDiscoveryFilter implements ResourceDiscoveryFilter { public boolean directoryDiscoveryRequired(String url) { return true; } public boolean rangeDiscoveryRequired(DiscoveryRange discoveryRange) { return true; } public boolean zipFileDiscoveryRequired(String url) { return true; } } } xbean-3.7/xbean-bundleutils/src/test/0000755000175000017500000000000011610661033017544 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/0000755000175000017500000000000011610661033020465 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/0000755000175000017500000000000011610661033021254 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/0000755000175000017500000000000011610661033022475 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661033023572 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/0000755000175000017500000000000011610661033024533 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/bundle/0000755000175000017500000000000011610661033026004 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/bundle/util/0000755000175000017500000000000011610661033026761 5ustar drazzibdrazzibxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/bundle/util/HeaderParserTest.java0000644000175000017500000001220311365244010033026 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.util.List; import org.apache.xbean.osgi.bundle.util.HeaderParser; import org.apache.xbean.osgi.bundle.util.HeaderParser.HeaderElement; import junit.framework.TestCase; public class HeaderParserTest extends TestCase { public void testSimple() throws Exception { List paths = HeaderParser.parseHeader("/foo.xml, /foo/bar.xml"); assertEquals(2, paths.size()); assertEquals("/foo.xml", paths.get(0).getName()); assertEquals(0, paths.get(0).getAttributes().size()); assertEquals(0, paths.get(0).getDirectives().size()); assertEquals("/foo/bar.xml", paths.get(1).getName()); assertEquals(0, paths.get(1).getAttributes().size()); assertEquals(0, paths.get(1).getDirectives().size()); } public void testComplex() throws Exception { List paths = HeaderParser.parseHeader("OSGI-INF/blueprint/comp1_named.xml;ignored-directive:=true,OSGI-INF/blueprint/comp2_named.xml;some-other-attribute=1"); assertEquals(2, paths.size()); assertEquals("OSGI-INF/blueprint/comp1_named.xml", paths.get(0).getName()); assertEquals(0, paths.get(0).getAttributes().size()); assertEquals(1, paths.get(0).getDirectives().size()); assertEquals("true", paths.get(0).getDirective("ignored-directive")); assertEquals("OSGI-INF/blueprint/comp2_named.xml", paths.get(1).getName()); assertEquals(1, paths.get(1).getAttributes().size()); assertEquals("1", paths.get(1).getAttribute("some-other-attribute")); assertEquals(0, paths.get(1).getDirectives().size()); } public void testPaths() throws Exception { List paths = HeaderParser.parseHeader("OSGI-INF/blueprint/comp1_named.xml;ignored-directive:=true,OSGI-INF/blueprint/comp2_named.xml;foo.xml;a=b;1:=2;c:=d;4=5"); assertEquals(3, paths.size()); assertEquals("OSGI-INF/blueprint/comp1_named.xml", paths.get(0).getName()); assertEquals(0, paths.get(0).getAttributes().size()); assertEquals(1, paths.get(0).getDirectives().size()); assertEquals("true", paths.get(0).getDirective("ignored-directive")); assertEquals("OSGI-INF/blueprint/comp2_named.xml", paths.get(1).getName()); assertEquals(0, paths.get(1).getAttributes().size()); assertEquals(0, paths.get(1).getDirectives().size()); assertEquals("foo.xml", paths.get(2).getName()); assertEquals(2, paths.get(2).getAttributes().size()); assertEquals("b", paths.get(2).getAttribute("a")); assertEquals("5", paths.get(2).getAttribute("4")); assertEquals(2, paths.get(2).getDirectives().size()); assertEquals("d", paths.get(2).getDirective("c")); assertEquals("2", paths.get(2).getDirective("1")); } public void testExportPackages() throws Exception { List paths = HeaderParser.parseHeader("org.apache.geronimo.kernel.rmi;uses:=\"javax.rmi.ssl,org.apache.geronimo.gbean,org.slf4j\",org.apache.geronimo.kernel.proxy"); assertEquals(2, paths.size()); assertEquals("org.apache.geronimo.kernel.rmi", paths.get(0).getName()); assertEquals(0, paths.get(0).getAttributes().size()); assertEquals(1, paths.get(0).getDirectives().size()); assertEquals("javax.rmi.ssl,org.apache.geronimo.gbean,org.slf4j", paths.get(0).getDirective("uses")); assertEquals("org.apache.geronimo.kernel.proxy", paths.get(1).getName()); assertEquals(0, paths.get(1).getAttributes().size()); assertEquals(0, paths.get(1).getDirectives().size()); } public void testImportPackages() throws Exception { List paths = HeaderParser.parseHeader("com.thoughtworks.xstream;version=\"1.3\",com.thoughtworks.xstream.converters"); assertEquals(2, paths.size()); assertEquals("com.thoughtworks.xstream", paths.get(0).getName()); assertEquals(1, paths.get(0).getAttributes().size()); assertEquals("1.3", paths.get(0).getAttribute("version")); assertEquals(0, paths.get(0).getDirectives().size()); assertEquals("com.thoughtworks.xstream.converters", paths.get(1).getName()); assertEquals(0, paths.get(1).getAttributes().size()); assertEquals(0, paths.get(1).getDirectives().size()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/bundle/util/BundleDescriptionTest.javaxbean-3.7/xbean-bundleutils/src/test/java/org/apache/xbean/osgi/bundle/util/BundleDescriptionTest.ja0000644000175000017500000000716411365244010033561 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.osgi.bundle.util; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.framework.Constants; import org.osgi.framework.Version; import junit.framework.TestCase; public class BundleDescriptionTest extends TestCase { public void testSimple() throws Exception { Map headers = new HashMap(); headers.put(Constants.IMPORT_PACKAGE, "com.thoughtworks.xstream;version=\"1.3\",com.thoughtworks.xstream.converters,org.apache.geronimo.kernel.proxy"); headers.put(Constants.EXPORT_PACKAGE, "org.apache.geronimo.kernel.rmi;uses:=\"javax.rmi.ssl,org.apache.geronimo.gbean,org.slf4j\",org.apache.geronimo.kernel.proxy"); BundleDescription desc = new BundleDescription(headers); List imports = desc.getImportPackage(); assertEquals(3, imports.size()); assertEquals("com.thoughtworks.xstream", imports.get(0).getName()); assertEquals("1.3", imports.get(0).getAttributes().get("version")); assertEquals(Version.parseVersion("1.3"), imports.get(0).getVersionRange().getLow()); assertEquals("com.thoughtworks.xstream.converters", imports.get(1).getName()); assertEquals("org.apache.geronimo.kernel.proxy", imports.get(2).getName()); List exports = desc.getExportPackage(); assertEquals(2, exports.size()); assertEquals("org.apache.geronimo.kernel.rmi", exports.get(0).getName()); assertEquals("javax.rmi.ssl,org.apache.geronimo.gbean,org.slf4j", exports.get(0).getDirectives().get("uses")); assertEquals("org.apache.geronimo.kernel.proxy", exports.get(1).getName()); List externalImports = desc.getExternalImports(); assertEquals(2, externalImports.size()); assertEquals("com.thoughtworks.xstream", externalImports.get(0).getName()); assertEquals("1.3", externalImports.get(0).getAttributes().get("version")); assertEquals("com.thoughtworks.xstream.converters", externalImports.get(1).getName()); } public void testSymbolicName() throws Exception { Map headers = new HashMap(); BundleDescription desc = new BundleDescription(headers); // test simple headers.put(Constants.BUNDLE_SYMBOLICNAME, "foo1"); assertEquals("foo1", desc.getSymbolicName().getName()); // test with a directive headers.put(Constants.BUNDLE_SYMBOLICNAME, "foo2; singleton:=true"); assertEquals("foo2", desc.getSymbolicName().getName()); assertEquals("true", desc.getSymbolicName().getDirectives().get("singleton")); } } xbean-3.7/src/0000755000175000017500000000000011610661034013141 5ustar drazzibdrazzibxbean-3.7/src/site/0000755000175000017500000000000011610661034014105 5ustar drazzibdrazzibxbean-3.7/src/site/apt/0000755000175000017500000000000011610661034014671 5ustar drazzibdrazzibxbean-3.7/src/site/site.xml0000644000175000017500000000245010521607760015602 0ustar drazzibdrazzib ${modules} ${reports} xbean-3.7/xbean-classloader/0000755000175000017500000000000011610661034015741 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/pom.xml0000644000175000017500000000470111373256143017267 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-classloader bundle Apache XBean :: Classloader xbean-classloader includes a flexibie multi-parent classloader org.apache.xbean maven-xbean-plugin mapping http://xbean.apache.org/schemas/classloader cglib cglib-nodep test org.springframework spring-beans provided xbean-3.7/xbean-classloader/src/0000755000175000017500000000000011610661034016530 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/0000755000175000017500000000000011610661034017454 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/resources/0000755000175000017500000000000011610661034021466 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/resources/META-INF/0000755000175000017500000000000011610661034022626 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/0000755000175000017500000000000011610661034020375 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/org/0000755000175000017500000000000011610661034021164 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/org/apache/0000755000175000017500000000000011610661034022405 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661034023502 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/0000755000175000017500000000000011610661034025776 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarFileUrlStreamHandler.java0000644000175000017500000001053411205007453033314 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.File; import java.io.IOException; import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @version $Rev: 776705 $ $Date: 2009-05-20 16:09:47 +0200 (mer. 20 mai 2009) $ */ public class JarFileUrlStreamHandler extends URLStreamHandler { public static URL createUrl(JarFile jarFile, JarEntry jarEntry) throws MalformedURLException { return createUrl(jarFile, jarEntry, new File(jarFile.getName()).toURI().toURL()); } public static URL createUrl(JarFile jarFile, JarEntry jarEntry, URL codeSource) throws MalformedURLException { JarFileUrlStreamHandler handler = new JarFileUrlStreamHandler(jarFile, jarEntry); URL url = new URL("jar", "", -1, codeSource + "!/" + jarEntry.getName(), handler); handler.setExpectedUrl(url); return url; } private URL expectedUrl; private final JarFile jarFile; private final JarEntry jarEntry; public JarFileUrlStreamHandler(JarFile jarFile, JarEntry jarEntry) { if (jarFile == null) throw new NullPointerException("jarFile is null"); if (jarEntry == null) throw new NullPointerException("jarEntry is null"); this.jarFile = jarFile; this.jarEntry = jarEntry; } public void setExpectedUrl(URL expectedUrl) { if (expectedUrl == null) throw new NullPointerException("expectedUrl is null"); this.expectedUrl = expectedUrl; } public URLConnection openConnection(URL url) throws IOException { if (expectedUrl == null) throw new IllegalStateException("expectedUrl was not set"); // the caller copied the URL reusing a stream handler from a previous call if (!expectedUrl.equals(url)) { // the new url is supposed to be within our context, so it must have a jar protocol if (!url.getProtocol().equals("jar")) { throw new IllegalArgumentException("Unsupported protocol " + url.getProtocol()); } // split the path at "!/" into the file part and entry part String path = url.getPath(); String[] chunks = path.split("!/", 2); // if we only got only one chunk, it didn't contain the required "!/" delimiter if (chunks.length == 1) { throw new MalformedURLException("Url does not contain a '!' character: " + url); } String file = chunks[0]; String entryPath = chunks[1]; // this handler only supports jars on the local file system if (!file.startsWith("file:")) { // let the system handler deal with this return new URL(url.toExternalForm()).openConnection(); } file = file.substring("file:".length()); // again the new url is supposed to be within our context so it must reference the same jar file if (!jarFile.getName().equals(file)) { // let the system handler deal with this return new URL(url.toExternalForm()).openConnection(); } // get the entry JarEntry newEntry = jarFile.getJarEntry(entryPath); if (newEntry == null) { throw new FileNotFoundException("Entry not found: " + url); } return new JarFileUrlConnection(url, jarFile, newEntry); } return new JarFileUrlConnection(url, jarFile, jarEntry); } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarFileClassLoader.java0000644000175000017500000003270110474504727032311 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.IOException; import java.io.File; import java.net.URL; import java.net.URI; import java.security.AccessControlContext; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import java.security.cert.Certificate; import java.util.Collection; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * The JarFileClassLoader that loads classes and resources from a list of JarFiles. This method is simmilar to URLClassLoader * except it properly closes JarFiles when the classloader is destroyed so that the file read lock will be released, and * the jar file can be modified and deleted. *

* Note: This implementation currently does not work reliably on windows, since the jar URL handler included with the Sun JavaVM * holds a read lock on the JarFile, and this lock is not released when the jar url is dereferenced. To fix this a * replacement for the jar url handler must be written. * * @author Dain Sundstrom * @version $Id: JarFileClassLoader.java 437551 2006-08-28 06:14:47Z adc $ * @since 2.0 */ public class JarFileClassLoader extends MultiParentClassLoader { private static final URL[] EMPTY_URLS = new URL[0]; private final UrlResourceFinder resourceFinder = new UrlResourceFinder(); private final AccessControlContext acc; /** * Creates a JarFileClassLoader that is a child of the system class loader. * @param name the name of this class loader * @param urls a list of URLs from which classes and resources should be loaded */ public JarFileClassLoader(String name, URL[] urls) { super(name, EMPTY_URLS); this.acc = AccessController.getContext(); addURLs(urls); } /** * Creates a JarFileClassLoader that is a child of the specified class loader. * @param name the name of this class loader * @param urls a list of URLs from which classes and resources should be loaded * @param parent the parent of this class loader */ public JarFileClassLoader(String name, URL[] urls, ClassLoader parent) { super(name, EMPTY_URLS, parent); this.acc = AccessController.getContext(); addURLs(urls); } public JarFileClassLoader(String name, URL[] urls, ClassLoader parent, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { super(name, EMPTY_URLS, parent, inverseClassLoading, hiddenClasses, nonOverridableClasses); this.acc = AccessController.getContext(); addURLs(urls); } /** * Creates a named class loader as a child of the specified parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parents the parents of this class loader */ public JarFileClassLoader(String name, URL[] urls, ClassLoader[] parents) { super(name, EMPTY_URLS, parents); this.acc = AccessController.getContext(); addURLs(urls); } public JarFileClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, Collection hiddenClasses, Collection nonOverridableClasses) { super(name, EMPTY_URLS, parents, inverseClassLoading, hiddenClasses, nonOverridableClasses); this.acc = AccessController.getContext(); addURLs(urls); } public JarFileClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { super(name, EMPTY_URLS, parents, inverseClassLoading, hiddenClasses, nonOverridableClasses); this.acc = AccessController.getContext(); addURLs(urls); } /** * {@inheritDoc} */ public URL[] getURLs() { return resourceFinder.getUrls(); } /** * {@inheritDoc} */ public void addURL(final URL url) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { resourceFinder.addUrl(url); return null; } }, acc); } /** * Adds an array of urls to the end of this class loader. * @param urls the URLs to add */ protected void addURLs(final URL[] urls) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { resourceFinder.addUrls(urls); return null; } }, acc); } /** * {@inheritDoc} */ public void destroy() { resourceFinder.destroy(); super.destroy(); } /** * {@inheritDoc} */ public URL findResource(final String resourceName) { return (URL) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return resourceFinder.findResource(resourceName); } }, acc); } /** * {@inheritDoc} */ public Enumeration findResources(final String resourceName) throws IOException { // todo this is not right // first get the resources from the parent classloaders Enumeration parentResources = super.findResources(resourceName); // get the classes from my urls Enumeration myResources = (Enumeration) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return resourceFinder.findResources(resourceName); } }, acc); // join the two together Enumeration resources = new UnionEnumeration(parentResources, myResources); return resources; } /** * {@inheritDoc} */ protected String findLibrary(String libraryName) { // if the libraryName is actually a directory it is invalid int pathEnd = libraryName.lastIndexOf('/'); if (pathEnd == libraryName.length() - 1) { throw new IllegalArgumentException("libraryName ends with a '/' character: " + libraryName); } // get the name if the library file final String resourceName; if (pathEnd < 0) { resourceName = System.mapLibraryName(libraryName); } else { String path = libraryName.substring(0, pathEnd + 1); String file = libraryName.substring(pathEnd + 1); resourceName = path + System.mapLibraryName(file); } // get a resource handle to the library ResourceHandle resourceHandle = (ResourceHandle) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return resourceFinder.getResource(resourceName); } }, acc); if (resourceHandle == null) { return null; } // the library must be accessable on the file system URL url = resourceHandle.getUrl(); if (!"file".equals(url.getProtocol())) { return null; } String path = new File(URI.create(url.toString())).getPath(); return path; } /** * {@inheritDoc} */ protected Class findClass(final String className) throws ClassNotFoundException { try { return (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws ClassNotFoundException { // first think check if we are allowed to define the package SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { String packageName; int packageEnd = className.lastIndexOf('.'); if (packageEnd >= 0) { packageName = className.substring(0, packageEnd); securityManager.checkPackageDefinition(packageName); } } // convert the class name to a file name String resourceName = className.replace('.', '/') + ".class"; // find the class file resource ResourceHandle resourceHandle = resourceFinder.getResource(resourceName); if (resourceHandle == null) { throw new ClassNotFoundException(className); } byte[] bytes; Manifest manifest; try { // get the bytes from the class file bytes = resourceHandle.getBytes(); // get the manifest for defining the packages manifest = resourceHandle.getManifest(); } catch (IOException e) { throw new ClassNotFoundException(className, e); } // get the certificates for the code source Certificate[] certificates = resourceHandle.getCertificates(); // the code source url is used to define the package and as the security context for the class URL codeSourceUrl = resourceHandle.getCodeSourceUrl(); // define the package (required for security) definePackage(className, codeSourceUrl, manifest); // this is the security context of the class CodeSource codeSource = new CodeSource(codeSourceUrl, certificates); // load the class into the vm Class clazz = defineClass(className, bytes, 0, bytes.length, codeSource); return clazz; } }, acc); } catch (PrivilegedActionException e) { throw (ClassNotFoundException) e.getException(); } } private void definePackage(String className, URL jarUrl, Manifest manifest) { int packageEnd = className.lastIndexOf('.'); if (packageEnd < 0) { return; } String packageName = className.substring(0, packageEnd); String packagePath = packageName.replace('.', '/') + "/"; Attributes packageAttributes = null; Attributes mainAttributes = null; if (manifest != null) { packageAttributes = manifest.getAttributes(packagePath); mainAttributes = manifest.getMainAttributes(); } Package pkg = getPackage(packageName); if (pkg != null) { if (pkg.isSealed()) { if (!pkg.isSealed(jarUrl)) { throw new SecurityException("Package was already sealed with another URL: package=" + packageName + ", url=" + jarUrl); } } else { if (isSealed(packageAttributes, mainAttributes)) { throw new SecurityException("Package was already been loaded and not sealed: package=" + packageName + ", url=" + jarUrl); } } } else { String specTitle = getAttribute(Attributes.Name.SPECIFICATION_TITLE, packageAttributes, mainAttributes); String specVendor = getAttribute(Attributes.Name.SPECIFICATION_VENDOR, packageAttributes, mainAttributes); String specVersion = getAttribute(Attributes.Name.SPECIFICATION_VERSION, packageAttributes, mainAttributes); String implTitle = getAttribute(Attributes.Name.IMPLEMENTATION_TITLE, packageAttributes, mainAttributes); String implVendor = getAttribute(Attributes.Name.IMPLEMENTATION_VENDOR, packageAttributes, mainAttributes); String implVersion = getAttribute(Attributes.Name.IMPLEMENTATION_VERSION, packageAttributes, mainAttributes); URL sealBase = null; if (isSealed(packageAttributes, mainAttributes)) { sealBase = jarUrl; } definePackage(packageName, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); } } private String getAttribute(Attributes.Name name, Attributes packageAttributes, Attributes mainAttributes) { if (packageAttributes != null) { String value = packageAttributes.getValue(name); if (value != null) { return value; } } if (mainAttributes != null) { return mainAttributes.getValue(name); } return null; } private boolean isSealed(Attributes packageAttributes, Attributes mainAttributes) { String sealed = getAttribute(Attributes.Name.SEALED, packageAttributes, mainAttributes); if (sealed == null) { return false; } return "true".equalsIgnoreCase(sealed); } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/UrlResourceFinder.java0000644000175000017500000002616211205007453032251 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * @version $Rev: 776705 $ $Date: 2009-05-20 16:09:47 +0200 (mer. 20 mai 2009) $ */ public class UrlResourceFinder implements ResourceFinder { private final Object lock = new Object(); private final LinkedHashSet urls = new LinkedHashSet(); private final LinkedHashMap classPath = new LinkedHashMap(); private final LinkedHashSet watchedFiles = new LinkedHashSet(); private boolean destroyed = false; public UrlResourceFinder() { } public UrlResourceFinder(URL[] urls) { addUrls(urls); } public void destroy() { synchronized (lock) { if (destroyed) { return; } destroyed = true; urls.clear(); for (Iterator iterator = classPath.values().iterator(); iterator.hasNext();) { ResourceLocation resourceLocation = (ResourceLocation) iterator.next(); resourceLocation.close(); } classPath.clear(); } } public ResourceHandle getResource(String resourceName) { synchronized (lock) { if (destroyed) { return null; } for (Iterator iterator = getClassPath().entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); ResourceLocation resourceLocation = (ResourceLocation) entry.getValue(); ResourceHandle resourceHandle = resourceLocation.getResourceHandle(resourceName); if (resourceHandle != null && !resourceHandle.isDirectory()) { return resourceHandle; } } } return null; } public URL findResource(String resourceName) { synchronized (lock) { if (destroyed) { return null; } for (Iterator iterator = getClassPath().entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); ResourceLocation resourceLocation = (ResourceLocation) entry.getValue(); ResourceHandle resourceHandle = resourceLocation.getResourceHandle(resourceName); if (resourceHandle != null) { return resourceHandle.getUrl(); } } } return null; } public Enumeration findResources(String resourceName) { synchronized (lock) { return new ResourceEnumeration(new ArrayList(getClassPath().values()), resourceName); } } public void addUrl(URL url) { addUrls(Collections.singletonList(url)); } public URL[] getUrls() { synchronized (lock) { return (URL[]) urls.toArray(new URL[urls.size()]); } } /** * Adds an array of urls to the end of this class loader. * @param urls the URLs to add */ protected void addUrls(URL[] urls) { addUrls(Arrays.asList(urls)); } /** * Adds a list of urls to the end of this class loader. * @param urls the URLs to add */ protected void addUrls(List urls) { synchronized (lock) { if (destroyed) { throw new IllegalStateException("UrlResourceFinder has been destroyed"); } boolean shouldRebuild = this.urls.addAll(urls); if (shouldRebuild) { rebuildClassPath(); } } } private LinkedHashMap getClassPath() { assert Thread.holdsLock(lock): "This method can only be called while holding the lock"; for (Iterator iterator = watchedFiles.iterator(); iterator.hasNext();) { File file = (File) iterator.next(); if (file.canRead()) { rebuildClassPath(); break; } } return classPath; } /** * Rebuilds the entire class path. This class is called when new URLs are added or one of the watched files * becomes readable. This method will not open jar files again, but will add any new entries not alredy open * to the class path. If any file based url is does not exist, we will watch for that file to appear. */ private void rebuildClassPath() { assert Thread.holdsLock(lock): "This method can only be called while holding the lock"; // copy all of the existing locations into a temp map and clear the class path Map existingJarFiles = new LinkedHashMap(classPath); classPath.clear(); LinkedList locationStack = new LinkedList(urls); try { while (!locationStack.isEmpty()) { URL url = (URL) locationStack.removeFirst(); // Skip any duplicate urls in the claspath if (classPath.containsKey(url)) { continue; } // Check is this URL has already been opened ResourceLocation resourceLocation = (ResourceLocation) existingJarFiles.remove(url); // If not opened, cache the url and wrap it with a resource location if (resourceLocation == null) { try { File file = cacheUrl(url); resourceLocation = createResourceLocation(url, file); } catch (FileNotFoundException e) { // if this is a file URL, the file doesn't exist yet... watch to see if it appears later if ("file".equals(url.getProtocol())) { File file = new File(url.getPath()); watchedFiles.add(file); continue; } } catch (IOException ignored) { // can't seem to open the file... this is most likely a bad jar file // so don't keep a watch out for it because that would require lots of checking // Dain: We may want to review this decision later continue; } } // add the jar to our class path classPath.put(resourceLocation.getCodeSource(), resourceLocation); // push the manifest classpath on the stack (make sure to maintain the order) List manifestClassPath = getManifestClassPath(resourceLocation); locationStack.addAll(0, manifestClassPath); } } catch (Error e) { destroy(); throw e; } for (Iterator iterator = existingJarFiles.values().iterator(); iterator.hasNext();) { ResourceLocation resourceLocation = (ResourceLocation) iterator.next(); resourceLocation.close(); } } protected File cacheUrl(URL url) throws IOException { if (!"file".equals(url.getProtocol())) { // download the jar throw new Error("Only local file jars are supported " + url); } File file; try { file = new File(url.toURI()); } catch (URISyntaxException e) { file = new File(url.getPath()); } if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } if (!file.canRead()) { throw new IOException("File is not readable: " + file.getAbsolutePath()); } return file; } protected ResourceLocation createResourceLocation(URL codeSource, File cacheFile) throws IOException { if (!cacheFile.exists()) { throw new FileNotFoundException(cacheFile.getAbsolutePath()); } if (!cacheFile.canRead()) { throw new IOException("File is not readable: " + cacheFile.getAbsolutePath()); } ResourceLocation resourceLocation = null; if (cacheFile.isDirectory()) { // DirectoryResourceLocation will only return "file" URLs within this directory // do not user the DirectoryResourceLocation for non file based urls resourceLocation = new DirectoryResourceLocation(cacheFile); } else { resourceLocation = new JarResourceLocation(codeSource, new JarFile(cacheFile)); } return resourceLocation; } private List getManifestClassPath(ResourceLocation resourceLocation) { try { // get the manifest, if possible Manifest manifest = resourceLocation.getManifest(); if (manifest == null) { // some locations don't have a manifest return Collections.EMPTY_LIST; } // get the class-path attribute, if possible String manifestClassPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (manifestClassPath == null) { return Collections.EMPTY_LIST; } // build the urls... // the class-path attribute is space delimited URL codeSource = resourceLocation.getCodeSource(); LinkedList classPathUrls = new LinkedList(); for (StringTokenizer tokenizer = new StringTokenizer(manifestClassPath, " "); tokenizer.hasMoreTokens();) { String entry = tokenizer.nextToken(); try { // the class path entry is relative to the resource location code source URL entryUrl = new URL(codeSource, entry); classPathUrls.addLast(entryUrl); } catch (MalformedURLException ignored) { // most likely a poorly named entry } } return classPathUrls; } catch (IOException ignored) { // error opening the manifest return Collections.EMPTY_LIST; } } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/MultiParentClassLoader.java0000644000175000017500000003067311120225203033221 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.IOException; import java.net.URL; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; /** * A MultiParentClassLoader is a simple extension of the URLClassLoader that simply changes the single parent class * loader model to support a list of parent class loaders. Each operation that accesses a parent, has been replaced * with a operation that checks each parent in order. This getParent method of this class will always return null, * which may be interperated by the calling code to mean that this class loader is a direct child of the system class * loader. * * @author Dain Sundstrom * @version $Id: MultiParentClassLoader.java 725706 2008-12-11 14:58:11Z gnodet $ * @since 2.0 */ public class MultiParentClassLoader extends NamedClassLoader { private final ClassLoader[] parents; private final boolean inverseClassLoading; private final String[] hiddenClasses; private final String[] nonOverridableClasses; private final String[] hiddenResources; private final String[] nonOverridableResources; /** * Creates a named class loader with no parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources */ public MultiParentClassLoader(String name, URL[] urls) { this(name, urls, ClassLoader.getSystemClassLoader()); } /** * Creates a named class loader as a child of the specified parent. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent) { this(name, urls, new ClassLoader[] {parent}); } /** * Creates a named class loader as a child of the specified parent and using the specified URLStreamHandlerFactory * for accessing the urls.. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader * @param factory the URLStreamHandlerFactory used to access the urls */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { this(name, urls, new ClassLoader[] {parent}, factory); } /** * Creates a named class loader as a child of the specified parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parents the parents of this class loader */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents) { this(name, urls, parents, false, new String[0], new String[0]); } public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { this(name, urls, new ClassLoader[]{parent}, inverseClassLoading, hiddenClasses, nonOverridableClasses); } /** * Creates a named class loader as a child of the specified parents and using the specified URLStreamHandlerFactory * for accessing the urls.. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parents the parents of this class loader * @param factory the URLStreamHandlerFactory used to access the urls */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, URLStreamHandlerFactory factory) { super(name, urls, null, factory); this.parents = copyParents(parents); this.inverseClassLoading = false; this.hiddenClasses = new String[0]; this.nonOverridableClasses = new String[0]; this.hiddenResources = new String[0]; this.nonOverridableResources = new String[0]; } public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, Collection hiddenClasses, Collection nonOverridableClasses) { this(name, urls, parents, inverseClassLoading, (String[]) hiddenClasses.toArray(new String[hiddenClasses.size()]), (String[]) nonOverridableClasses.toArray(new String[nonOverridableClasses.size()])); } public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { super(name, urls); this.parents = copyParents(parents); this.inverseClassLoading = inverseClassLoading; this.hiddenClasses = hiddenClasses; this.nonOverridableClasses = nonOverridableClasses; hiddenResources = toResources(hiddenClasses); nonOverridableResources = toResources(nonOverridableClasses); } private static String[] toResources(String[] classes) { String[] resources = new String[classes.length]; for (int i = 0; i < classes.length; i++) { String className = classes[i]; resources[i] = className.replace('.', '/'); } return resources; } private static ClassLoader[] copyParents(ClassLoader[] parents) { ClassLoader[] newParentsArray = new ClassLoader[parents.length]; for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; if (parent == null) { throw new NullPointerException("parent[" + i + "] is null"); } newParentsArray[i] = parent; } return newParentsArray; } /** * Gets the parents of this class loader. * @return the parents of this class loader */ public ClassLoader[] getParents() { return parents; } /** * {@inheritDoc} */ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // // Check if class is in the loaded classes cache // Class cachedClass = findLoadedClass(name); if (cachedClass != null) { return resolveClass(cachedClass, resolve); } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableClass(name)) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } // // Check parent class loaders // if (!isHiddenClass(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; try { Class clazz = parent.loadClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { // this parent didn't have the class; try the next one } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable classes here... we // have alredy checked he parent and the parent didn't have the // class, so we can override now if (!isDestroyed()) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } throw new ClassNotFoundException(name + " in classloader " + getName()); } private boolean isNonOverridableClass(String name) { for (int i = 0; i < nonOverridableClasses.length; i++) { if (name.startsWith(nonOverridableClasses[i])) { return true; } } return false; } private boolean isHiddenClass(String name) { for (int i = 0; i < hiddenClasses.length; i++) { if (name.startsWith(hiddenClasses[i])) { return true; } } return false; } private Class resolveClass(Class clazz, boolean resolve) { if (resolve) { resolveClass(clazz); } return clazz; } /** * {@inheritDoc} */ public URL getResource(String name) { if (isDestroyed()) { return null; } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableResource(name)) { URL url = findResource(name); if (url != null) { return url; } } // // Check parent class loaders // if (!isHiddenResource(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; URL url = parent.getResource(name); if (url != null) { return url; } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable resources here... we // have alredy checked he parent and the parent didn't have the // resource, so we can override now if (!isDestroyed()) { // parents didn't have the resource; attempt to load it from my urls return findResource(name); } return null; } /** * {@inheritDoc} */ public Enumeration findResources(String name) throws IOException { if (isDestroyed()) { return Collections.enumeration(Collections.EMPTY_SET); } List resources = new ArrayList(); // // if we are using inverse class loading, add the resources from local urls first // if (inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } // // Add parent resources // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; List parentResources = Collections.list(parent.getResources(name)); resources.addAll(parentResources); } // // if we are not using inverse class loading, add the resources from local urls now // if (!inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } return Collections.enumeration(resources); } private boolean isNonOverridableResource(String name) { for (int i = 0; i < nonOverridableResources.length; i++) { if (name.startsWith(nonOverridableResources[i])) { return true; } } return false; } private boolean isHiddenResource(String name) { for (int i = 0; i < hiddenResources.length; i++) { if (name.startsWith(hiddenResources[i])) { return true; } } return false; } /** * {@inheritDoc} */ public String toString() { return "[" + getClass().getName() + ":" + " name=" + getName() + " urls=" + Arrays.asList(getURLs()) + " parents=" + Arrays.asList(parents) + "]"; } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/DirectoryResourceHandle.java0000644000175000017500000000561411205007453033436 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.net.MalformedURLException; import java.security.cert.Certificate; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * @version $Rev: 776705 $ $Date: 2009-05-20 16:09:47 +0200 (mer. 20 mai 2009) $ */ public class DirectoryResourceHandle extends AbstractResourceHandle { private final String name; private final File file; private final Manifest manifest; private final URL url; private final URL codeSource; public DirectoryResourceHandle(String name, File file, File codeSource, Manifest manifest) throws MalformedURLException { this.name = name; this.file = file; this.codeSource = codeSource.toURI().toURL(); this.manifest = manifest; url = file.toURI().toURL(); } public String getName() { return name; } public URL getUrl() { return url; } public URL getCodeSourceUrl() { return codeSource; } public boolean isDirectory() { return file.isDirectory(); } public InputStream getInputStream() throws IOException { if (file.isDirectory()) { return new IoUtil.EmptyInputStream(); } return new FileInputStream(file); } public int getContentLength() { if (file.isDirectory() || file.length() > Integer.MAX_VALUE) { return -1; } else { return (int) file.length(); } } public Manifest getManifest() throws IOException { return manifest; } public Attributes getAttributes() throws IOException { if (manifest == null) { return null; } return manifest.getAttributes(getName()); } /** * Always return null. This could be implementd by verifing the signatures * in the manifest file against the actual file, but we don't need this right now. * @return null */ public Certificate[] getCertificates() { return null; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ThreadContextClassLoaderFactoryBean.javaxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ThreadContextClassLoaderFacto0000644000175000017500000000303310474504727033602 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import org.springframework.beans.factory.FactoryBean; /** * A factory bean to expose the current thread context class loader. * * * @org.apache.xbean.XBean namespace="http://xbean.apache.org/schemas/classloader" * element="threadContextClassLoader" description="References the ClassLoader of the current thread context" * @version $Revision: 437551 $ */ public class ThreadContextClassLoaderFactoryBean implements FactoryBean { public Object getObject() throws Exception { return Thread.currentThread().getContextClassLoader(); } public Class getObjectType() { return ClassLoader.class; } public boolean isSingleton() { return true; } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarResourceHandle.java0000644000175000017500000000470510474504727032223 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.util.jar.Manifest; import java.util.jar.Attributes; import java.net.URL; import java.net.MalformedURLException; import java.io.InputStream; import java.io.IOException; import java.security.cert.Certificate; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public class JarResourceHandle extends AbstractResourceHandle { private final JarFile jarFile; private final JarEntry jarEntry; private final URL url; private final URL codeSource; public JarResourceHandle(JarFile jarFile, JarEntry jarEntry, URL codeSource) throws MalformedURLException { this.jarFile = jarFile; this.jarEntry = jarEntry; this.url = JarFileUrlStreamHandler.createUrl(jarFile, jarEntry, codeSource); this.codeSource = codeSource; } public String getName() { return jarEntry.getName(); } public URL getUrl() { return url; } public URL getCodeSourceUrl() { return codeSource; } public boolean isDirectory() { return jarEntry.isDirectory(); } public InputStream getInputStream() throws IOException { return jarFile.getInputStream(jarEntry); } public int getContentLength() { return (int) jarEntry.getSize(); } public Manifest getManifest() throws IOException { return jarFile.getManifest(); } public Attributes getAttributes() throws IOException { return jarEntry.getAttributes(); } public Certificate[] getCertificates() { return jarEntry.getCertificates(); } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/DestroyableClassLoader.java0000644000175000017500000000253310474504727033252 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; /** * DestroyableClassLoader is a mixin interface for a ClassLoader that add a destroy method to propertly cleanup a * classloader then dereferenced by the server. * * @author Dain Sundstrom * @version $Id: DestroyableClassLoader.java 437551 2006-08-28 06:14:47Z adc $ * @since 2.0 */ public interface DestroyableClassLoader { /** * Destroys the clasloader releasing all resources. After this mehtod is called, the class loader will no longer * load any classes or resources. */ void destroy(); } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/AbstractResourceHandle.java0000644000175000017500000000370110474504727033245 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public abstract class AbstractResourceHandle implements ResourceHandle { public byte[] getBytes() throws IOException { InputStream in = getInputStream(); try { byte[] bytes = IoUtil.getBytes(in); return bytes; } finally { IoUtil.close(in); } } public Manifest getManifest() throws IOException { return null; } public Certificate[] getCertificates() { return null; } public Attributes getAttributes() throws IOException { Manifest m = getManifest(); if (m == null) { return null; } String entry = getUrl().getFile(); return m.getAttributes(entry); } public void close() { } public String toString() { return "[" + getName() + ": " + getUrl() + "; code source: " + getCodeSourceUrl() + "]"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/AbstractUrlResourceLocation.javaxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/AbstractUrlResourceLocation.j0000644000175000017500000000333210474504727033615 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public abstract class AbstractUrlResourceLocation implements ResourceLocation { private final URL codeSource; public AbstractUrlResourceLocation(URL codeSource) { this.codeSource = codeSource; } public final URL getCodeSource() { return codeSource; } public void close() { } public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractUrlResourceLocation that = (AbstractUrlResourceLocation) o; return codeSource.equals(that.codeSource); } public final int hashCode() { return codeSource.hashCode(); } public final String toString() { return "[" + getClass().getName() + ": " + codeSource + "]"; } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ResourceHandle.java0000644000175000017500000000612310474504727031562 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; import java.io.InputStream; import java.io.IOException; import java.util.jar.Manifest; import java.util.jar.Attributes; import java.security.cert.Certificate; /** * This is a handle (a connection) to some resource, which may * be a class, native library, text file, image, etc. Handles are returned * by a ResourceFinder. A resource handle allows easy access to the resource data * (using methods {@link #getInputStream} or {@link #getBytes}) as well as * access resource metadata, such as attributes, certificates, etc. *

* As soon as the handle is no longer in use, it should be explicitly * {@link #close}d, similarly to I/O streams. * * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public interface ResourceHandle { /** * Return the name of the resource. The name is a "/"-separated path * name that identifies the resource. */ String getName(); /** * Returns the URL of the resource. */ URL getUrl(); /** * Does this resource refer to a directory. Directory resources are commly used * as the basis for a URL in client application. A directory resource has 0 bytes for it's content. */ boolean isDirectory(); /** * Returns the CodeSource URL for the class or resource. */ URL getCodeSourceUrl(); /** * Returns and InputStream for reading this resource data. */ InputStream getInputStream() throws IOException; /** * Returns the length of this resource data, or -1 if unknown. */ int getContentLength(); /** * Returns this resource data as an array of bytes. */ byte[] getBytes() throws IOException; /** * Returns the Manifest of the JAR file from which this resource * was loaded, or null if none. */ Manifest getManifest() throws IOException; /** * Return the Certificates of the resource, or null if none. */ Certificate[] getCertificates(); /** * Return the Attributes of the resource, or null if none. */ Attributes getAttributes() throws IOException; /** * Closes a connection to the resource indentified by this handle. Releases * any I/O objects associated with the handle. */ void close(); } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ResourceLocation.java0000644000175000017500000000234110474504727032135 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.jar.Manifest; import java.io.IOException; import java.net.URL; /** * This is a location which is searched by * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public interface ResourceLocation { URL getCodeSource(); ResourceHandle getResourceHandle(String resourceName); Manifest getManifest() throws IOException; void close(); } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ResourceFinder.java0000644000175000017500000000402410474504727031574 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; import java.util.Enumeration; /** * Abstraction of resource searching policy. Given resource name, the resource * finder performs implementation-specific lookup, and, if it is able to locate * the resource, returns the {@link AbstractResourceHandle handle(s)} or URL(s) of it. * * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public interface ResourceFinder { /** * Find the resource by name and return URL of it if found. * * @param name the resource name * @return resource URL or null if resource was not found */ public URL findResource(String name); /** * Find all resources with given name and return enumeration of their URLs. * * @param name the resource name * @return enumeration of resource URLs (possibly empty). */ public Enumeration findResources(String name); /** * Get the resource by name and, if found, open connection to it and return * the {@link AbstractResourceHandle handle} of it. * * @param name the resource name * @return resource handle or null if resource was not found */ public ResourceHandle getResource(String name); } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ClassLoaderUtil.java0000644000175000017500000000732711252032104031674 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.Map; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.beans.Introspector; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; /** * Utility methods for class loader manipulation in a server environment. * * @author Dain Sundstrom * @version $Id: ClassLoaderUtil.java 813161 2009-09-09 23:03:32Z djencks $ * @since 2.0 */ public final class ClassLoaderUtil { private ClassLoaderUtil() { } /** * Cleans well known class loader leaks in VMs and libraries. There is a lot of bad code out there and this method * will clear up the known problems. This method should only be called when the class loader will no longer be used. * It this method is called two often it can have a serious impact on preformance. * @param classLoader the class loader to destroy */ public static void destroy(ClassLoader classLoader) { releaseCommonsLoggingCache(classLoader); clearSunSoftCache(ObjectInputStream.class, "subclassAudits"); clearSunSoftCache(ObjectOutputStream.class, "subclassAudits"); clearSunSoftCache(ObjectStreamClass.class, "localDescs"); clearSunSoftCache(ObjectStreamClass.class, "reflectors"); Introspector.flushCaches(); } /** * Clears the caches maintained by the SunVM object stream implementation. This method uses reflection and * setAccessable to obtain access to the Sun cache. The cache is locked with a synchronize monitor and cleared. * This method completely clears the class loader cache which will impact performance of object serialization. * @param clazz the name of the class containing the cache field * @param fieldName the name of the cache field */ public static void clearSunSoftCache(Class clazz, String fieldName) { Map cache = null; try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); cache = (Map) field.get(null); } catch (Throwable ignored) { // there is nothing a user could do about this anyway } if (cache != null) { synchronized (cache) { cache.clear(); } } } /** * Releases the specified classloader from the Apache Jakarta Commons Logging class loader cache using reflection. * @param classLoader the class loader to release */ public static void releaseCommonsLoggingCache(ClassLoader classLoader) { try { Class logFactory = classLoader.loadClass("org.apache.commons.logging.LogFactory"); Method release = logFactory.getMethod("release", new Class[] {ClassLoader.class}); release.invoke(null, new Object[] {classLoader}); } catch (Throwable ignored) { // there is nothing a user could do about this anyway } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/DirectoryResourceLocation.javaxbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/DirectoryResourceLocation.jav0000644000175000017500000000516411205007453033652 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.Manifest; /** * @version $Rev: 776705 $ $Date: 2009-05-20 16:09:47 +0200 (mer. 20 mai 2009) $ */ public class DirectoryResourceLocation extends AbstractUrlResourceLocation { private final File baseDir; private boolean manifestLoaded = false; private Manifest manifest; public DirectoryResourceLocation(File baseDir) throws MalformedURLException { super(baseDir.toURI().toURL()); this.baseDir = baseDir; } public ResourceHandle getResourceHandle(String resourceName) { File file = new File(baseDir, resourceName); if (!file.exists()) { return null; } try { ResourceHandle resourceHandle = new DirectoryResourceHandle(resourceName, file, baseDir, getManifestSafe()); return resourceHandle; } catch (MalformedURLException e) { return null; } } public Manifest getManifest() throws IOException { if (!manifestLoaded) { File manifestFile = new File(baseDir, "META-INF/MANIFEST.MF"); if (manifestFile.isFile() && manifestFile.canRead()) { FileInputStream in = null; try { in = new FileInputStream(manifestFile); manifest = new Manifest(in); } finally { IoUtil.close(in); } } manifestLoaded = true; } return manifest; } private Manifest getManifestSafe() { Manifest manifest = null; try { manifest = getManifest(); } catch (IOException e) { // ignore } return manifest; } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/IoUtil.java0000644000175000017500000000725310474504727030071 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.jar.JarFile; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public final class IoUtil { private IoUtil() { } public static byte[] getBytes(InputStream inputStream) throws IOException { try { byte[] buffer = new byte[4096]; ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int count = inputStream.read(buffer); count >= 0; count = inputStream.read(buffer)) { out.write(buffer, 0, count); } byte[] bytes = out.toByteArray(); return bytes; } finally { close(inputStream); } } public static void flush(OutputStream thing) { if (thing != null) { try { thing.flush(); } catch(Exception ignored) { } } } public static void flush(Writer thing) { if (thing != null) { try { thing.flush(); } catch(Exception ignored) { } } } public static void close(JarFile thing) { if (thing != null) { try { thing.close(); } catch(Exception ignored) { } } } public static void close(InputStream thing) { if (thing != null) { try { thing.close(); } catch(Exception ignored) { } } } public static void close(OutputStream thing) { if (thing != null) { try { thing.close(); } catch(Exception ignored) { } } } public static void close(Reader thing) { if (thing != null) { try { thing.close(); } catch(Exception ignored) { } } } public static void close(Writer thing) { if (thing != null) { try { thing.close(); } catch(Exception ignored) { } } } public static final class EmptyInputStream extends InputStream { public int read() { return -1; } public int read(byte b[]) { return -1; } public int read(byte b[], int off, int len) { return -1; } public long skip(long n) { return 0; } public int available() { return 0; } public void close() { } public synchronized void mark(int readlimit) { } public synchronized void reset() { } public boolean markSupported() { return false; } } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/UnionEnumeration.java0000644000175000017500000000435110474504727032157 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public final class UnionEnumeration implements Enumeration { private final LinkedList enumerations = new LinkedList(); public UnionEnumeration(List enumerations) { this.enumerations.addAll(enumerations); } public UnionEnumeration(Enumeration first, Enumeration second) { if (first == null) throw new NullPointerException("first is null"); if (second == null) throw new NullPointerException("second is null"); enumerations.add(first); enumerations.add(second); } public boolean hasMoreElements() { while (!enumerations.isEmpty()) { Enumeration enumeration = (Enumeration) enumerations.getFirst(); if (enumeration.hasMoreElements()) { return true; } enumerations.removeFirst(); } return false; } public Object nextElement() { while (!enumerations.isEmpty()) { Enumeration enumeration = (Enumeration) enumerations.getFirst(); if (enumeration.hasMoreElements()) { return enumeration.nextElement(); } enumerations.removeFirst(); } throw new NoSuchElementException(); } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarResourceLocation.java0000644000175000017500000000363410474504727032600 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.jar.Manifest; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.net.URL; import java.net.MalformedURLException; import java.io.IOException; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public class JarResourceLocation extends AbstractUrlResourceLocation { private final JarFile jarFile; public JarResourceLocation(URL codeSource, JarFile jarFile) { super(codeSource); this.jarFile = jarFile; } public ResourceHandle getResourceHandle(String resourceName) { JarEntry jarEntry = jarFile.getJarEntry(resourceName); if (jarEntry != null) { try { URL url = new URL(getCodeSource(), resourceName); return new JarResourceHandle(jarFile, jarEntry, getCodeSource()); } catch (MalformedURLException e) { } } return null; } public Manifest getManifest() throws IOException { return jarFile.getManifest(); } public void close() { IoUtil.close(jarFile); } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarFileUrlConnection.java0000644000175000017500000000775611205007453032676 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.security.Permission; import java.security.cert.Certificate; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * @version $Rev: 776705 $ $Date: 2009-05-20 16:09:47 +0200 (mer. 20 mai 2009) $ */ public class JarFileUrlConnection extends JarURLConnection { public static final URL DUMMY_JAR_URL; static { try { DUMMY_JAR_URL = new URL("jar", "", -1, "file:dummy!/", new URLStreamHandler() { protected URLConnection openConnection(URL u) { throw new UnsupportedOperationException(); } }); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } private final URL url; private final JarFile jarFile; private final JarEntry jarEntry; private final URL jarFileUrl; public JarFileUrlConnection(URL url, JarFile jarFile, JarEntry jarEntry) throws MalformedURLException { super(DUMMY_JAR_URL); if (url == null) throw new NullPointerException("url is null"); if (jarFile == null) throw new NullPointerException("jarFile is null"); if (jarEntry == null) throw new NullPointerException("jarEntry is null"); this.url = url; this.jarFile = jarFile; this.jarEntry = jarEntry; jarFileUrl = new File(jarFile.getName()).toURI().toURL(); } public JarFile getJarFile() throws IOException { return jarFile; } public synchronized void connect() { } public URL getJarFileURL() { return jarFileUrl; } public String getEntryName() { return getJarEntry().getName(); } public Manifest getManifest() throws IOException { return jarFile.getManifest(); } public JarEntry getJarEntry() { return jarEntry; } public Attributes getAttributes() throws IOException { return getJarEntry().getAttributes(); } public Attributes getMainAttributes() throws IOException { return getManifest().getMainAttributes(); } public Certificate[] getCertificates() throws IOException { return getJarEntry().getCertificates(); } public URL getURL() { return url; } public int getContentLength() { long size = getJarEntry().getSize(); if (size > Integer.MAX_VALUE) { return -1; } return (int) size; } public long getLastModified() { return getJarEntry().getTime(); } public synchronized InputStream getInputStream() throws IOException { return jarFile.getInputStream(jarEntry); } public Permission getPermission() throws IOException { URL jarFileUrl = new File(jarFile.getName()).toURI().toURL(); return jarFileUrl.openConnection().getPermission(); } public String toString() { return JarFileUrlConnection.class.getName() + ":" + url; } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/ResourceEnumeration.java0000644000175000017500000000531510474504727032657 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.util.Enumeration; import java.util.Iterator; import java.util.Collection; import java.util.NoSuchElementException; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public class ResourceEnumeration implements Enumeration { private Iterator iterator; private final String resourceName; private Object next; public ResourceEnumeration(Collection resourceLocations, String resourceName) { this.iterator = resourceLocations.iterator(); this.resourceName = resourceName; } public boolean hasMoreElements() { fetchNext(); return (next != null); } public Object nextElement() { fetchNext(); // save next into a local variable and clear the next field Object next = this.next; this.next = null; // if we didn't have a next throw an exception if (next == null) { throw new NoSuchElementException(); } return next; } private void fetchNext() { if (iterator == null) { return; } if (next != null) { return; } try { while (iterator.hasNext()) { ResourceLocation resourceLocation = (ResourceLocation) iterator.next(); ResourceHandle resourceHandle = resourceLocation.getResourceHandle(resourceName); if (resourceHandle != null) { next = resourceHandle.getUrl(); return; } } // no more elements // clear the iterator so it can be GCed iterator = null; } catch (IllegalStateException e) { // Jar file was closed... this means the resource finder was destroyed // clear the iterator so it can be GCed iterator = null; throw e; } } } xbean-3.7/xbean-classloader/src/main/java/org/apache/xbean/classloader/NamedClassLoader.java0000644000175000017500000000671710575256556032037 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandlerFactory; import java.util.Arrays; /** * The NamedClassLoader is a simple extension to URLClassLoader that adds a name and a destroy method that cleans up * the commons logging and JavaVM caches of the classloader. * * @author Dain Sundstrom * @version $Id: NamedClassLoader.java 517223 2007-03-12 14:02:22Z gnodet $ * @since 2.0 */ public class NamedClassLoader extends URLClassLoader implements DestroyableClassLoader { private final String name; private volatile boolean destroyed = false; /** * Creates a named class loader with no parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources */ public NamedClassLoader(String name, URL[] urls) { super(urls); this.name = name; } /** * Creates a named class loader as a child of the specified parent. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader */ public NamedClassLoader(String name, URL[] urls, ClassLoader parent) { super(urls, parent); this.name = name; } /** * Creates a named class loader as a child of the specified parent and using the specified URLStreamHandlerFactory * for accessing the urls.. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader * @param factory the URLStreamHandlerFactory used to access the urls */ public NamedClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { super(urls, parent, factory); this.name = name; } /** * Check if this classloader has been destroyed * @return */ public boolean isDestroyed() { return destroyed; } /** * {@inheritDoc} */ public void destroy() { synchronized(this) { if (destroyed) return; destroyed = true; } ClassLoaderUtil.destroy(this); } /** * Gets the name of this class loader. * @return the name of this class loader */ public String getName() { return name; } /** * {@inheritDoc} */ public String toString() { return "[" + getClass().getName() + ":" + " name=" + getName() + " urls=" + Arrays.asList(getURLs()) + "]"; } } xbean-3.7/xbean-classloader/src/test-data/0000755000175000017500000000000011610661034020416 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test-data/resourceFinderTest/0000755000175000017500000000000011610661034024235 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test-data/resourceFinderTest/jar1/0000755000175000017500000000000011610661034025072 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test-data/resourceFinderTest/jar1/resource0000644000175000017500000000001110467423550026644 0ustar drazzibdrazzibresource1xbean-3.7/xbean-classloader/src/test-data/resourceFinderTest/jar2/0000755000175000017500000000000011610661034025073 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test-data/resourceFinderTest/jar2/resource0000644000175000017500000000001110467423550026645 0ustar drazzibdrazzibresource2xbean-3.7/xbean-classloader/src/test/0000755000175000017500000000000011610661034017507 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test/java/0000755000175000017500000000000011610661034020430 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test/java/org/0000755000175000017500000000000011610661034021217 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test/java/org/apache/0000755000175000017500000000000011610661034022440 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661034023535 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/classloader/0000755000175000017500000000000011610661034026031 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/classloader/MultiParentClassLoaderTest.javaxbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/classloader/MultiParentClassLoaderTest.ja0000644000175000017500000003307210474504727033607 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.SortedSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import junit.framework.TestCase; import net.sf.cglib.core.DefaultGeneratorStrategy; import net.sf.cglib.core.NamingPolicy; import net.sf.cglib.core.Predicate; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.NoOp; /** * Tests the MultiParentClassLoader including classloading and resource loading. * @author Dain Sundstrom * @version $Id: MultiParentClassLoaderTest.java 437551 2006-08-28 06:14:47Z adc $ * @since 2.0 */ public class MultiParentClassLoaderTest extends TestCase { private static final String CLASS_NAME = "TestClass"; private static final String ENTRY_NAME = "foo"; private static final String ENTRY_VALUE = "bar"; private File[] files; private static final String NON_EXISTANT_RESOURCE = "non-existant-resource"; private static final String NON_EXISTANT_CLASS = "NonExistant.class"; private URLClassLoader[] parents; private File myFile; private MultiParentClassLoader classLoader; private static final String NAME = "my test class loader"; /** * Verify that the test jars are valid. * @throws Exception if a problem occurs */ public void testTestJars() throws Exception { for (int i = 0; i < files.length; i++) { File file = files[i]; JarFile jarFile = new JarFile(files[i]); String urlString = "jar:" + file.toURL() + "!/" + ENTRY_NAME; URL url = new URL(files[i].toURL(), urlString); assertStreamContains(ENTRY_VALUE + i, url.openStream()); jarFile.close(); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { file.toURL() } ); // clazz shared by all Class clazz = urlClassLoader.loadClass(CLASS_NAME); assertNotNull(clazz); assertTrue(SortedSet.class.isAssignableFrom(clazz)); // clazz specific to this jar clazz = urlClassLoader.loadClass(CLASS_NAME + i); assertNotNull(clazz); assertTrue(SortedSet.class.isAssignableFrom(clazz)); // resource shared by all jars InputStream in = urlClassLoader.getResourceAsStream(ENTRY_NAME ); assertStreamContains("Should have found value from parent " + i, ENTRY_VALUE + i, in); // resource specific to this jar in = urlClassLoader.getResourceAsStream(ENTRY_NAME + i); assertStreamContains("Should have found value from parent " + i, ENTRY_VALUE + i + ENTRY_VALUE, in); } } /** * Verify the get name method returns the name provided to the constructor. */ public void testGetName() { assertEquals(NAME, classLoader.getName()); } /** * Verufy that the getParents method returns a different array from the one passed to the constructor and that the * parents are in the same order. */ public void testGetParents() { ClassLoader[] actualParents = classLoader.getParents(); assertNotSame(parents, actualParents); assertEquals(parents.length, actualParents.length); for (int i = 0; i < actualParents.length; i++) { assertEquals(parents[i], actualParents[i]); } } /** * Test loadClass loads in preference of the parents, in order, and then the local urls. * @throws Exception if a problem occurs */ public void testLoadClass() throws Exception { // load class specific to my class loader Class clazz = classLoader.loadClass(CLASS_NAME + 33); assertNotNull(clazz); assertTrue(SortedSet.class.isAssignableFrom(clazz)); assertEquals(classLoader, clazz.getClassLoader()); // load class specific to each parent class loader for (int i = 0; i < parents.length; i++) { URLClassLoader parent = parents[i]; clazz = classLoader.loadClass(CLASS_NAME + i); assertNotNull(clazz); assertTrue(SortedSet.class.isAssignableFrom(clazz)); assertEquals(parent, clazz.getClassLoader()); } // class shared by all class loaders clazz = classLoader.loadClass(CLASS_NAME); assertNotNull(clazz); assertTrue(SortedSet.class.isAssignableFrom(clazz)); assertEquals(parents[0], clazz.getClassLoader()); } /** * Test that an attempt to load a non-existant class causes a ClassNotFoundException. */ public void testLoadNonExistantClass() { try { classLoader.loadClass(NON_EXISTANT_CLASS); fail("loadClass should have thrown a ClassNotFoundException"); } catch (ClassNotFoundException e) { // expected } } /** * Test getResourceAsStream loads in preference of the parents, in order, and then the local urls. * @throws Exception if a problem occurs */ public void testGetResourceAsStream() throws Exception { InputStream in = classLoader.getResourceAsStream(ENTRY_NAME + 33); assertStreamContains("Should have found value from my file", ENTRY_VALUE + 33 + ENTRY_VALUE, in); for (int i = 0; i < parents.length; i++) { in = classLoader.getResourceAsStream(ENTRY_NAME + i); assertStreamContains("Should have found value from parent " + i, ENTRY_VALUE + i + ENTRY_VALUE, in); } in = classLoader.getResourceAsStream(ENTRY_NAME); assertStreamContains("Should have found value from first parent", ENTRY_VALUE + 0, in); } /** * Test getResourceAsStream returns null when attempt is made to loade a non-existant resource. * @throws Exception if a problem occurs */ public void testGetNonExistantResourceAsStream() throws Exception { InputStream in = classLoader.getResourceAsStream(NON_EXISTANT_RESOURCE); assertNull(in); } /** * Test getResource loads in preference of the parents, in order, and then the local urls. * @throws Exception if a problem occurs */ public void testGetResource() throws Exception { URL resource = classLoader.getResource(ENTRY_NAME + 33); assertURLContains("Should have found value from my file", ENTRY_VALUE + 33 + ENTRY_VALUE, resource); for (int i = 0; i < parents.length; i++) { resource = classLoader.getResource(ENTRY_NAME + i); assertURLContains("Should have found value from parent " + i, ENTRY_VALUE + i + ENTRY_VALUE, resource); } resource = classLoader.getResource(ENTRY_NAME); assertURLContains("Should have found value from first parent", ENTRY_VALUE + 0, resource); } /** * Test getResource returns null when attempt is made to loade a non-existant resource. * @throws Exception if a problem occurs */ public void testGetNonExistantResource() throws Exception { URL resource = classLoader.getResource(NON_EXISTANT_RESOURCE); assertNull(resource); } /** * Test getResource returns an enumeration in preference of the parents, in order, and then the local urls. * @throws Exception if a problem occurs */ public void testGetResources() throws Exception { Enumeration resources = classLoader.getResources(ENTRY_NAME); assertNotNull(resources); assertTrue(resources.hasMoreElements()); // there should be one entry for each parent for (int i = 0; i < parents.length; i++) { URL resource = (URL) resources.nextElement(); assertURLContains("Should have found value from parent " + i, ENTRY_VALUE + i, resource); } // and one entry from my url assertTrue(resources.hasMoreElements()); URL resource = (URL) resources.nextElement(); assertURLContains("Should have found value from my file", ENTRY_VALUE + 33, resource); } /** * Test getResources returns an empty enumeration when attempt is made to loade a non-existant resource. * @throws Exception if a problem occurs */ public void testGetNonExistantResources() throws Exception { Enumeration resources = classLoader.getResources(NON_EXISTANT_RESOURCE); assertNotNull(resources); assertFalse(resources.hasMoreElements()); } private void assertStreamContains(String expectedValue, InputStream in) throws IOException { assertStreamContains(null, expectedValue, in); } private void assertStreamContains(String message, String expectedValue, InputStream in) throws IOException { String entryValue; try { StringBuffer stringBuffer = new StringBuffer(); byte[] bytes = new byte[4000]; for (int count = in.read(bytes); count != -1; count = in.read(bytes)) { stringBuffer.append(new String(bytes, 0, count)); } entryValue = stringBuffer.toString(); } finally { in.close(); } assertEquals(message, expectedValue, entryValue); } private void assertURLContains(String message, String expectedValue, URL resource) throws IOException { InputStream in; assertNotNull(resource); in = resource.openStream(); assertStreamContains(message, expectedValue, in); } private static void assertFileExists(File file) { assertTrue("File should exist: " + file, file.canRead()); } private static void assertFileNotExists(File file) { assertTrue("File should not exist: " + file, !file.canRead()); } protected void setUp() throws Exception { super.setUp(); files = new File[3]; for (int i = 0; i < files.length; i++) { files[i] = createJarFile(i); } parents = new URLClassLoader[3]; for (int i = 0; i < parents.length; i++) { parents[i] = new URLClassLoader(new URL[]{files[i].toURL()}); } myFile = createJarFile(33); classLoader = createClassLoader(NAME, new URL[]{myFile.toURL()}, parents); } /** * Creates the class loader to test. * @param name the name of the classloader * @param urls the urls to load classes and resources from * @param parents the parents of the class loader * @return the class loader to test */ protected MultiParentClassLoader createClassLoader(String name, URL[] urls, ClassLoader[] parents) { return new MultiParentClassLoader(name, urls, parents); } private static File createJarFile(int i) throws IOException { File file = File.createTempFile("test-" + i + "-", ".jar"); FileOutputStream out = new FileOutputStream(file); JarOutputStream jarOut = new JarOutputStream(out); // common class shared by everyone jarOut.putNextEntry(new JarEntry(CLASS_NAME + ".class")); jarOut.write(createClass(CLASS_NAME)); // class only available in this jar jarOut.putNextEntry(new JarEntry(CLASS_NAME + i + ".class")); jarOut.write(createClass(CLASS_NAME + i)); // common resource shared by everyone jarOut.putNextEntry(new JarEntry(ENTRY_NAME)); jarOut.write((ENTRY_VALUE + i).getBytes()); // resource only available in this jar jarOut.putNextEntry(new JarEntry(ENTRY_NAME + i)); jarOut.write((ENTRY_VALUE + i + ENTRY_VALUE).getBytes()); jarOut.close(); out.close(); assertFileExists(file); return file; } private static byte[] createClass(final String name) { Enhancer enhancer = new Enhancer(); enhancer.setNamingPolicy(new NamingPolicy() { public String getClassName(String prefix, String source, Object key, Predicate names) { return name; } }); enhancer.setClassLoader(new URLClassLoader(new URL[0])); enhancer.setSuperclass(Object.class); enhancer.setInterfaces(new Class[]{SortedSet.class}); enhancer.setCallbackTypes(new Class[]{NoOp.class}); enhancer.setUseFactory(false); ByteCode byteCode = new ByteCode(); enhancer.setStrategy(byteCode); enhancer.createClass(); return byteCode.getByteCode(); } protected void tearDown() throws Exception { super.tearDown(); for (int i = 0; i < files.length; i++) { files[i].delete(); } } private static class ByteCode extends DefaultGeneratorStrategy { private byte[] byteCode; public byte[] transform(byte[] byteCode) { this.byteCode = byteCode; return byteCode; } public byte[] getByteCode() { return byteCode; } } } xbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/classloader/UrlResourceFinderTest.java0000644000175000017500000004717010474504727033163 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.jar.Attributes; import java.io.InputStream; import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.io.FileNotFoundException; import junit.framework.TestCase; /** * @version $Rev: 437551 $ $Date: 2006-08-28 08:14:47 +0200 (lun. 28 août 2006) $ */ public class UrlResourceFinderTest extends TestCase { private File basedir = new File(System.getProperty("basedir")); private File jarFile; private Manifest manifest; private Attributes resourceAttributes; private File alternateJarFile; private File testResource; /** * There are 2 "jars" with a "resource" inside. Make sure the enumeration has exactly 2 elements and * that hasMoreElements() doesn't advance the iterator. * * @throws Exception */ public void testResourceEnumeration() throws Exception { URL jar1 = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL(); URL jar2 = new File(basedir, "src/test-data/resourceFinderTest/jar2/").toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar1, jar2}); Enumeration enumeration = resourceFinder.findResources("resource"); // resource1 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource1 = (URL) enumeration.nextElement(); assertNotNull(resource1); assertEquals("resource1", toString(resource1.openStream())); // resource2 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource2 = (URL) enumeration.nextElement(); assertNotNull(resource2); assertEquals("resource2", toString(resource2.openStream())); assertFalse(enumeration.hasMoreElements()); } public void testDirectoryResource() throws Exception { URL jar = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); ResourceHandle resource = resourceFinder.getResource("resource"); assertNotNull(resource); // handle.getBytes() assertEquals("resource1", new String(resource.getBytes())); // handle.getInputStream() assertEquals("resource1", toString(resource.getInputStream())); // handle.getUrl() URL url = resource.getUrl(); assertEquals("resource1", toString(url.openStream())); // copy the url and verify we can still get the data URL copyUrl = new URL(url.toExternalForm()); assertEquals("resource1", toString(copyUrl.openStream())); // resourceFinder.findResource URL directUrl = resourceFinder.findResource("resource"); assertEquals("resource1", toString(directUrl.openStream())); assertEquals("resource1", toString(new URL(directUrl.toExternalForm()).openStream())); // handle.getContentLength() assertEquals("resource1".length(), resource.getContentLength()); // handle.getName() assertEquals("resource", resource.getName()); // handle.getAttributes() assertNull(resource.getAttributes()); // handle.getManifest() assertNull(resource.getManifest()); } public void testJarResource() throws Exception { URL jar = jarFile.toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); ResourceHandle resource = resourceFinder.getResource("resource"); assertNotNull(resource); // handle.getBytes() assertEquals("resource3", new String(resource.getBytes())); // handle.getInputStream() assertEquals("resource3", toString(resource.getInputStream())); // handle.getUrl() URL url = resource.getUrl(); assertEquals("resource3", toString(url.openStream())); // copy the url and verify we can still get the data URL copyUrl = new URL(url.toExternalForm()); assertEquals("resource3", toString(copyUrl.openStream())); // resourceFinder.findResource URL directUrl = resourceFinder.findResource("resource"); assertEquals("resource3", toString(directUrl.openStream())); assertEquals("resource3", toString(new URL(directUrl.toExternalForm()).openStream())); // handle.getContentLength() assertEquals("resource3".length(), resource.getContentLength()); // handle.getName() assertEquals("resource", resource.getName()); // handle.getAttributes() assertEquals(resourceAttributes, resource.getAttributes()); // handle.getManifest() assertEquals(manifest, resource.getManifest()); } public void testAddURL() throws Exception { URL jar1 = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar1}); Enumeration enumeration = resourceFinder.findResources("resource"); // resource1 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource1 = (URL) enumeration.nextElement(); assertNotNull(resource1); assertEquals("resource1", toString(resource1.openStream())); assertFalse(enumeration.hasMoreElements()); // addUrl URL jar2 = new File(basedir, "src/test-data/resourceFinderTest/jar2/").toURL(); resourceFinder.addUrl(jar2); // getResource should find the first jar only ResourceHandle resource = resourceFinder.getResource("resource"); assertNotNull(resource); assertEquals("resource1", new String(resource.getBytes())); // findResource should find the first jar only resource1 = resourceFinder.findResource("resource"); assertEquals("resource1", toString(resource1.openStream())); // findResouces should see both jars enumeration = resourceFinder.findResources("resource"); // resource1 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); resource1 = (URL) enumeration.nextElement(); assertNotNull(resource1); assertEquals("resource1", toString(resource1.openStream())); assertTrue(enumeration.hasMoreElements()); // resource2 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource2 = (URL) enumeration.nextElement(); assertNotNull(resource2); assertEquals("resource2", toString(resource2.openStream())); assertFalse(enumeration.hasMoreElements()); } public void testConcurrentAddURL() throws Exception { URL jar1 = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL(); URL jar2 = new File(basedir, "src/test-data/resourceFinderTest/jar2/").toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar1, jar2}); Enumeration enumeration = resourceFinder.findResources("resource"); // resource1 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource1 = (URL) enumeration.nextElement(); assertNotNull(resource1); assertEquals("resource1", toString(resource1.openStream())); assertTrue(enumeration.hasMoreElements()); // // addURL // URL newJar = jarFile.toURL(); resourceFinder.addUrl(newJar); // new resources should be available // getResource should find the first jar only ResourceHandle jar3Resouce = resourceFinder.getResource("jar3"); assertNotNull(jar3Resouce); assertEquals("jar3", new String(jar3Resouce.getBytes())); // findResource should find the first jar only URL jar3Url = resourceFinder.findResource("jar3"); assertEquals("jar3", toString(jar3Url.openStream())); // // enumeration from above should still be valid, but only see the resources available at the time it was created // // resource2 assertTrue(enumeration.hasMoreElements()); assertTrue(enumeration.hasMoreElements()); URL resource2 = (URL) enumeration.nextElement(); assertNotNull(resource2); assertEquals("resource2", toString(resource2.openStream())); assertFalse(enumeration.hasMoreElements()); } public void testDirectoryDestroy() throws Exception { URL jar = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); assertDestroyed(resourceFinder, "resource1", null); } public void testJarDestroy() throws Exception { URL jar = jarFile.toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); assertDestroyed(resourceFinder, "resource3", manifest); } public void testUrlCopy() throws Exception { URL jar = jarFile.toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); // get the resource URL resource = resourceFinder.findResource("resource"); assertNotNull(resource); assertEquals("resource3", toString(resource.openStream())); // copy resource with string URL stringCopy = new URL(resource.toExternalForm()); assertEquals("resource3", toString(stringCopy.openStream())); // copy resource perserving the url handler URL handlerCopy = new URL(resource, resource.toExternalForm()); assertEquals("resource3", toString(handlerCopy.openStream())); // access the other resource using the original url as a starting point URL other = new URL(resource, "jar3"); assertEquals("jar3", toString(other.openStream())); } public void testUrlAccess() throws Exception { URL jar = jarFile.toURL(); UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[]{jar}); // get geronimo url from the resource finder URL geronimoUrl = resourceFinder.findResource("resource"); assertNotNull(geronimoUrl); assertEquals("resource3", toString(geronimoUrl.openStream())); // get a system url by copying the url by string URL systemUrl = new URL(geronimoUrl.toExternalForm()); assertEquals("resource3", toString(systemUrl.openStream())); // verify both can see the jar3 file withing the jar file assertEquals("jar3", toString(new URL(systemUrl, "jar3").openStream())); assertEquals("jar3", toString(new URL(geronimoUrl, "jar3").openStream())); // verify both can see the jar3 file withing the jar file using a full url spec String mainEntry = "jar:" + jarFile.toURL().toExternalForm() + "!/jar3"; assertEquals("jar3", toString(new URL(systemUrl, mainEntry).openStream())); assertEquals("jar3", toString(new URL(geronimoUrl, mainEntry).openStream())); // verify both throw a FileNotFoundExcetion for an unknown file try { new URL(systemUrl, "unknown").openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } try { new URL(geronimoUrl, "unknown").openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } // verify both can see the alternate jar String alternateEntry = "jar:" + alternateJarFile.toURL().toExternalForm() + "!/jar4"; assertEquals("jar4", toString(new URL(systemUrl, alternateEntry).openStream())); assertEquals("jar4", toString(new URL(geronimoUrl, alternateEntry).openStream())); // verify both throw a FileNotFoundExcetion for an unknown entry in the alternate file String alternateUnknownEntry = "jar:" + alternateJarFile.toURL().toExternalForm() + "!/unknown"; try { new URL(systemUrl, alternateUnknownEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } try { new URL(geronimoUrl, alternateUnknownEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } // verify both work an excepton for a non-jar entry assertEquals("testResource", toString(new URL(systemUrl, testResource.toURL().toExternalForm()).openStream())); assertEquals("testResource", toString(new URL(geronimoUrl, testResource.toURL().toExternalForm()).openStream())); // verify both fail for a spec without a !/ String badEntry = "jar:" + alternateJarFile.toURL().toExternalForm(); try { new URL(systemUrl, badEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (MalformedURLException expected) { } try { new URL(geronimoUrl, badEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (MalformedURLException expected) { } // verify both throw FileNotFoundException for a nested jar file badEntry = "jar:" + alternateJarFile.toURL().toExternalForm() + "!/foo.jar!/bar"; try { new URL(systemUrl, badEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } try { new URL(geronimoUrl, badEntry).openStream(); fail("Expected a FileNotFoundException"); } catch (FileNotFoundException expected) { } } public void assertDestroyed(UrlResourceFinder resourceFinder, String resourceValue, Manifest expectedManifest) throws Exception { ResourceHandle resource = resourceFinder.getResource("resource"); assertNotNull(resource); assertEquals(resourceValue, new String(resource.getBytes())); // handle.getUrl() URL url = resource.getUrl(); assertEquals(resourceValue, toString(url.openStream())); // copy the url and verify we can still get the data URL copyUrl = new URL(url.toExternalForm()); assertEquals(resourceValue, toString(copyUrl.openStream())); // resourceFinder.findResource URL directUrl = resourceFinder.findResource("resource"); assertEquals(resourceValue, toString(directUrl.openStream())); URL directUrlCopy = new URL(directUrl.toExternalForm()); assertEquals(resourceValue, toString(directUrlCopy.openStream())); // destroy resourceFinder.destroy(); // getResource always returns null assertNull(resourceFinder.getResource("resource")); // findResource always returns null assertNull(resourceFinder.findResource("resource")); // findResources always returns an empty enumeration assertFalse(resourceFinder.findResources("resource").hasMoreElements()); // existing url may not work try { assertEquals(resourceValue, toString(url.openStream())); } catch (IllegalStateException expected) { } catch (IOException expected) { } try { assertEquals(resourceValue, toString(directUrl.openStream())); } catch (IllegalStateException expected) { } catch (IOException expected) { } // the copied urls will work since they are proviced by the vm assertEquals(resourceValue, toString(copyUrl.openStream())); assertEquals(resourceValue, toString(directUrlCopy.openStream())); // existing resource handle may not work since the location was closed assertEquals("resource", resource.getName()); try { if (expectedManifest != null) { assertEquals(expectedManifest.getAttributes("resource"), resource.getAttributes()); } } catch (IllegalStateException expected) { } try { assertEquals(expectedManifest, resource.getManifest()); } catch (IllegalStateException expected) { } try { assertEquals(resourceValue, toString(resource.getUrl().openStream())); } catch (IllegalStateException expected) { } try { assertEquals(resourceValue, toString(resource.getInputStream())); } catch (IllegalStateException expected) { } catch (IOException expected) { } try { assertEquals(resourceValue, new String(resource.getBytes())); } catch (IllegalStateException expected) { } catch (IOException expected) { } } protected void setUp() throws Exception { super.setUp(); // // Build a simple Jar file to test with // manifest = new Manifest(); Attributes mainAttributes = manifest.getMainAttributes(); mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttributes.putValue("food", "nacho"); resourceAttributes = new Attributes(); resourceAttributes.putValue("drink", "margarita"); manifest.getEntries().put("resource", resourceAttributes); File targetDir = new File(basedir, "target"); jarFile = new File(targetDir, "resourceFinderTest.jar"); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile), manifest); jarOutputStream.putNextEntry(new ZipEntry("resource")); jarOutputStream.write("resource3".getBytes()); jarOutputStream.putNextEntry(new ZipEntry("jar3")); jarOutputStream.write("jar3".getBytes()); IoUtil.close(jarOutputStream); alternateJarFile = new File(targetDir, "alternate.jar"); System.out.println(alternateJarFile.getAbsolutePath()); jarOutputStream = new JarOutputStream(new FileOutputStream(alternateJarFile), manifest); jarOutputStream.putNextEntry(new ZipEntry("resource")); jarOutputStream.write("resource4".getBytes()); jarOutputStream.putNextEntry(new ZipEntry("jar4")); jarOutputStream.write("jar4".getBytes()); IoUtil.close(jarOutputStream); testResource = new File(targetDir, "testResource"); FileOutputStream fileOutputStream = new FileOutputStream(testResource); fileOutputStream.write("testResource".getBytes()); IoUtil.close(fileOutputStream); } protected void tearDown() throws Exception { jarFile.delete(); super.tearDown(); } private static String toString(InputStream in) throws IOException { try { byte[] bytes = IoUtil.getBytes(in); String string = new String(bytes); return string; } finally { IoUtil.close(in); } } } xbean-3.7/xbean-classloader/src/test/java/org/apache/xbean/classloader/JarFileClassLoaderTest.java0000644000175000017500000000237110474504727033204 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.classloader; import java.net.URL; /** * Test the JarFileClassLoader. * * @author Dain Sundstrom * @version $Id: JarFileClassLoaderTest.java 437551 2006-08-28 06:14:47Z adc $ * @since 2.0 */ public class JarFileClassLoaderTest extends MultiParentClassLoaderTest { protected MultiParentClassLoader createClassLoader(String name, URL[] urls, ClassLoader[] parents) { return new JarFileClassLoader(name, urls, parents); } } xbean-3.7/xbean-classloader/src/site/0000755000175000017500000000000011610661034017474 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/site/apt/0000755000175000017500000000000011610661034020260 5ustar drazzibdrazzibxbean-3.7/xbean-classloader/src/site/site.xml0000644000175000017500000000210010473277125021165 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/xbean-blueprint/0000755000175000017500000000000011610661037015454 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/pom.xml0000644000175000017500000001517511373256143017006 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-blueprint bundle Apache XBean :: OSGI Blueprint Namespace Handler xbean-blueprint provides a schema-driven namespace handler for Apache Aries Blueprint 1.5.0 org.apache.aries.blueprint org.apache.aries.blueprint 0.1-incubating provided org.apache.commons commons-jexl 2.0 commons-logging commons-logging org.ops4j.pax.logging pax-logging-api ${pax.logging.version} org.osgi org.osgi.core 4.2.0 provided org.osgi org.osgi.compendium 4.2.0 provided org.ops4j.pax.logging pax-logging-service ${pax.logging.version} log4j log4j provided com.thoughtworks.qdox qdox true ant ant true src/test/resources target/test-generated org.apache.maven.plugins maven-surefire-plugin **/BeerUsingXBeanNSTest.java maven-antrun-plugin process-classes run org.apache.felix maven-bundle-plugin true com.thoughtworks.qdox*;resolution:=optional, org.apache.tools.ant*;resolution:=optional, * xbean-3.7/xbean-blueprint/src/0000755000175000017500000000000011610661037016243 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/0000755000175000017500000000000011610661037017167 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/0000755000175000017500000000000011610661037021201 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/0000755000175000017500000000000011610661037021770 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/apache/0000755000175000017500000000000011610661037023211 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/apache/xbean/0000755000175000017500000000000011610661037024306 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/apache/xbean/blueprint/0000755000175000017500000000000011610661037026312 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/apache/xbean/blueprint/cm/0000755000175000017500000000000011610661037026711 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/org/apache/xbean/blueprint/cm/xbean-cm.xsd0000644000175000017500000001412111333220747031123 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/main/resources/OSGI-INF/0000755000175000017500000000000011610661037022354 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/OSGI-INF/blueprint/0000755000175000017500000000000011610661037024360 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/resources/OSGI-INF/blueprint/xbean-cm.xml0000644000175000017500000000245311333220747026601 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/main/java/0000755000175000017500000000000011610661037020110 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/0000755000175000017500000000000011610661037020677 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/0000755000175000017500000000000011610661037022120 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661037023215 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/0000755000175000017500000000000011610661037025221 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/0000755000175000017500000000000011610661037027207 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/XsdGenerator.java0000644000175000017500000002333711320711571032464 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XsdGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public XsdGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { // TODO can only handle 1 schema document so far... File file = destFile; log.log("Generating XSD file: " + file + " for namespace: " + namespaceMapping.getNamespace()); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateSchema(out, namespaceMapping); } finally { out.close(); } } public void generateSchema(PrintWriter out, NamespaceMapping namespaceMapping) { out.println(""); out.println(""); out.println(); out.println(""); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementMapping(out, namespaceMapping, element); } out.println(); out.println(""); } private void generateElementMapping(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { out.println(); out.println(" "); String localName = element.getElementName(); out.println(" "); if (!isEmptyString(element.getDescription())) { out.println(" "); out.println(" "); out.println(" "); } out.println(" "); int complexCount = 0; for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (!namespaceMapping.isSimpleType(attributeMapping.getType())) { complexCount++; } } if (complexCount > 0) { out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (!namespaceMapping.isSimpleType(attributeMapping.getType())) { generateElementMappingComplexProperty(out, namespaceMapping, attributeMapping); } } out.println(" "); out.println(" "); } for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if (namespaceMapping.isSimpleType(attributeMapping.getType())) { generateElementMappingSimpleProperty(out, attributeMapping); } else if (!attributeMapping.getType().isCollection()) { generateElementMappingComplexPropertyAsRef(out, attributeMapping); } } generateIDAttributeMapping(out, namespaceMapping, element); out.println(" "); out.println(" "); out.println(" "); out.println(); } private boolean isEmptyString(String str) { if (str == null) { return true; } for (int i = 0; i < str.length(); i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } private void generateIDAttributeMapping(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); if ("id".equals(attributeMapping.getAttributeName())) { return; } } out.println(" "); } private void generateElementMappingSimpleProperty(PrintWriter out, AttributeMapping attributeMapping) { // types with property editors need to be xs:string in the schema to validate String type = attributeMapping.getPropertyEditor() != null ? Utils.getXsdType(Type.newSimpleType(String.class.getName())) : Utils.getXsdType(attributeMapping.getType()); if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); } else { out.println(" "); } } private void generateElementMappingComplexPropertyAsRef(PrintWriter out, AttributeMapping attributeMapping) { if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); out.println(" "); out.println(" "); } else { out.println(" "); } } private void generateElementMappingComplexProperty(PrintWriter out, NamespaceMapping namespaceMapping, AttributeMapping attributeMapping) { Type type = attributeMapping.getType(); List types; if (type.isCollection()) { types = Utils.findImplementationsOf(namespaceMapping, type.getNestedType()); } else { types = Utils.findImplementationsOf(namespaceMapping, type); } String maxOccurs = type.isCollection() || "java.util.Map".equals(type.getName()) ? "unbounded" : "1"; out.println(" "); if (!isEmptyString(attributeMapping.getDescription())) { out.println(" "); out.println(" "); out.println(" "); } out.println(" "); if (types.isEmpty()) { // We don't know the type because it's generic collection. Allow folks to insert objets from any namespace out.println(" "); } else { out.println(" "); for (Iterator iterator = types.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.println(" "); } out.println(" "); out.println(" "); } out.println(" "); out.println(" "); } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/XmlWriter.java0000644000175000017500000001117111320711571032005 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.PrintWriter; import java.io.Writer; import java.util.LinkedList; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XmlWriter { private PrintWriter writer; private LinkedList elementStack = new LinkedList(); private boolean tagInProgress; private int depth; private String lineIndenter; private String encoding; private String docType; private boolean readyForNewLine; private boolean tagIsEmpty; public XmlWriter(PrintWriter writer, String lineIndenter) { this(writer, lineIndenter, null, null); } public XmlWriter(Writer writer, String lineIndenter) { this(new PrintWriter(writer), lineIndenter); } public XmlWriter(PrintWriter writer) { this(writer, null, null); } public XmlWriter(Writer writer) { this(new PrintWriter(writer)); } public XmlWriter(PrintWriter writer, String lineIndenter, String encoding, String doctype) { this.writer = writer; this.lineIndenter = lineIndenter; this.encoding = encoding; this.docType = doctype; if (docType != null || encoding != null) { writeDocumentHeaders(); } } public XmlWriter(Writer writer, String lineIndenter, String encoding, String doctype) { this(new PrintWriter(writer), lineIndenter, encoding, doctype); } public XmlWriter(PrintWriter writer, String encoding, String doctype) { this(writer, " ", encoding, doctype); } public XmlWriter(Writer writer, String encoding, String doctype) { this(new PrintWriter(writer), encoding, doctype); } public void startElement(String name) { tagIsEmpty = false; finishTag(); write("<"); write(name); elementStack.addLast(name); tagInProgress = true; depth++; readyForNewLine = true; tagIsEmpty = true; } public void writeText(String text) { writeText(text, true); } public void writeMarkup(String text) { writeText(text, false); } private void writeText(String text, boolean escapeHtml) { readyForNewLine = false; tagIsEmpty = false; finishTag(); if (escapeHtml) { text = text.replaceAll("&", "&"); text = text.replaceAll("<", "<"); text = text.replaceAll(">", ">"); } write(text); } public void addAttribute(String key, String value) { write(" "); write(key); write("=\""); write(value); write("\""); } public void endElement() { depth--; if (tagIsEmpty) { write("/"); readyForNewLine = false; finishTag(); elementStack.removeLast(); } else { finishTag(); write(""); } readyForNewLine = true; } private void write(String str) { writer.write(str); } private void finishTag() { if (tagInProgress) { write(">"); } tagInProgress = false; if (readyForNewLine) { endOfLine(); } readyForNewLine = false; tagIsEmpty = false; } protected void endOfLine() { write("\n"); for (int i = 0; i < depth; i++) { write(lineIndenter); } } private void writeDocumentHeaders() { write(""); endOfLine(); if (docType != null) { write(""); endOfLine(); } } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/SchemaGenerator.java0000644000175000017500000000354511320711571033125 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.IOException; import java.util.Iterator; import java.util.Set; /** * @version $Revision: 896187 $ */ public class SchemaGenerator { private final MappingLoader mappingLoader; private final GeneratorPlugin[] plugins; private final LogFacade log; public SchemaGenerator(LogFacade log, MappingLoader mappingLoader, GeneratorPlugin[] plugins) { this.log = log; this.mappingLoader = mappingLoader; this.plugins = plugins; } public void generate() throws IOException { Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { log.log("Warning: no namespaces found!"); } for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.generate(namespaceMapping); } } } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/ParameterMapping.java0000644000175000017500000000235711320711571033312 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; /** * @version $Rev: 896187 $ $Date: 2010-01-05 20:31:05 +0100 (mar. 05 janv. 2010) $ */ public class ParameterMapping { private final String name; private final Type type; public ParameterMapping(String name, Type type) { this.name = name; this.type = type; } public String getName() { return name; } public Type getType() { return type; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/Utils.java0000644000175000017500000001177711320711571031164 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public final class Utils { public static final String XBEAN_ANNOTATION = "org.apache.xbean.XBean"; public static final String PROPERTY_ANNOTATION = "org.apache.xbean.Property"; private Utils() { } public static String decapitalise(String value) { if (value == null || value.length() == 0) { return value; } return value.substring(0, 1).toLowerCase() + value.substring(1); } public static boolean isSimpleType(Type type) { if (type.isPrimitive()) { return true; } if (type.isCollection()) { return false; } String name = type.getName(); if (name.equals("java.lang.Class") || name.equals("javax.xml.namespace.QName")) { return true; } return hasPropertyEditor(name); } private static boolean hasPropertyEditor(String type) { Class theClass; try { theClass = loadClass(type); // lets see if we can find a property editor for this type PropertyEditor editor = PropertyEditorManager.findEditor(theClass); return editor != null; } catch (Throwable e) { System.out.println("Warning, could not load class: " + type + ": " + e); return false; } } /** * Attempts to load the class on the current thread context class loader or * the class loader which loaded us */ private static Class loadClass(String name) throws ClassNotFoundException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { return contextClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } } return Utils.class.getClassLoader().loadClass(name); } public static String getXsdType(Type type) { String name = type.getName(); String xsdType = (String) XSD_TYPES.get(name); if (xsdType == null) { xsdType = "xs:string"; } return xsdType; } public static final Map XSD_TYPES; static { // TODO check these XSD types are right... Map map = new HashMap(); map.put(String.class.getName(), "xs:string"); map.put(Boolean.class.getName(), "xs:boolean"); map.put(boolean.class.getName(), "xs:boolean"); map.put(Byte.class.getName(), "xs:byte"); map.put(byte.class.getName(), "xs:byte"); map.put(Short.class.getName(), "xs:short"); map.put(short.class.getName(), "xs:short"); map.put(Integer.class.getName(), "xs:integer"); map.put(int.class.getName(), "xs:integer"); map.put(Long.class.getName(), "xs:long"); map.put(long.class.getName(), "xs:long"); map.put(Float.class.getName(), "xs:float"); map.put(float.class.getName(), "xs:float"); map.put(Double.class.getName(), "xs:double"); map.put(double.class.getName(), "xs:double"); map.put(java.util.Date.class.getName(), "xs:date"); map.put(java.sql.Date.class.getName(), "xs:date"); map.put("javax.xml.namespace.QName", "xs:QName"); XSD_TYPES = Collections.unmodifiableMap(map); } public static List findImplementationsOf(NamespaceMapping namespaceMapping, Type type) { List elements = new ArrayList(); String nestedTypeName = type.getName(); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); if (element.getClassName().equals(nestedTypeName) || element.getInterfaces().contains(nestedTypeName) || element.getSuperClasses().contains(nestedTypeName)) { elements.add(element); } } return elements; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/LogFacade.java0000644000175000017500000000167711320711571031667 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; public interface LogFacade { void log(String message); void log(String message, int level); } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/AttributeMapping.java0000644000175000017500000000557611320711571033343 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class AttributeMapping implements Comparable { private final String attributeName; private final String propertyName; private final String description; private final Type type; private final String value; private final boolean fixed; private final boolean required; private final String propertyEditor; public AttributeMapping(String attributeName, String propertyName, String description, Type type, String value, boolean fixed, boolean required, String propertyEditor) { this.propertyEditor = propertyEditor; if (attributeName == null) throw new NullPointerException("attributeName"); if (propertyName == null) throw new NullPointerException("propertyName"); if (type == null) throw new NullPointerException("type"); this.attributeName = attributeName; this.propertyName = propertyName; if (description == null) description = ""; this.description = description; this.type = type; this.value = value; this.fixed = fixed; this.required = required; } public String getAttributeName() { return attributeName; } public String getPropertyName() { return propertyName; } public String getDescription() { return description; } public Type getType() { return type; } public String getValue() { return value; } public boolean isFixed() { return fixed; } public boolean isRequired() { return required; } public int hashCode() { return attributeName.hashCode(); } public boolean equals(Object obj) { if (obj instanceof AttributeMapping) { return attributeName.equals(((AttributeMapping) obj).attributeName); } return false; } public int compareTo(Object obj) { return attributeName.compareTo(((AttributeMapping) obj).attributeName); } public String getPropertyEditor() { return propertyEditor; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/MapMapping.java0000644000175000017500000000327211320711571032104 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; public class MapMapping { private String entryName; private String keyName; private boolean flat; private String dupsMode; private String defaultKey; public MapMapping(String entryName, String keyName, boolean flat, String dupsMode, String defaultKey) { this.entryName = entryName; this.keyName = keyName; this.flat = flat; this.dupsMode = dupsMode; this.defaultKey = defaultKey; } public String getEntryName() { return entryName; } public String getKeyName() { return keyName; } public boolean isFlat() { return flat; } public String getDupsMode() { return dupsMode; } public String getDefaultKey() { return defaultKey; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/WikiDocumentationGenerator.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/WikiDocumentationGenera0000644000175000017500000002134611320711571033714 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * @author Hiram Chirino * @version $Id$ * @since 1.0 */ public class WikiDocumentationGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public WikiDocumentationGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); File file = new File(destFile.getParentFile(), destFile.getName() + ".wiki"); log.log("Generating WIKI documentation file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateDocumentation(out, namespaceMapping); } finally { out.close(); } } private void generateDocumentation(PrintWriter out, NamespaceMapping namespaceMapping) { HashMap refercencedTypes = new HashMap(); // Build of map of types that are referenced by element types. for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attribute = (AttributeMapping) iterator.next(); Type type = getNestedType( attribute.getType() ); if( namespaceMapping.isSimpleType( type) ) continue; if( !refercencedTypes.containsKey(type.getName()) ) refercencedTypes.put(type.getName(), new ArrayList()); } } // Add all the elements that implement those types. for (Iterator iter = refercencedTypes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String type = (String) entry.getKey(); ArrayList implementations = (ArrayList) entry.getValue(); for (Iterator iterator = namespaceMapping.getElements().iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); // Check to see if the class is matches boolean matched=false; if (type.equals(element.getClassName())) { implementations.add(element); matched=true; } // Perhaps a super class matches. if(!matched) { for (Iterator j = element.getSuperClasses().iterator(); j.hasNext();) { String t = (String) j.next(); if( type.equals(t) ) { implementations.add(element); matched=true; break; } } } // Or it might be an interface. if(!matched) { for (Iterator j = element.getInterfaces().iterator(); j.hasNext();) { String t = (String) j.next(); if( type.equals(t) ) { implementations.add(element); matched=true; break; } } } } } // Remove any entries that did not have associated elements for (Iterator iter = refercencedTypes.values().iterator(); iter.hasNext();) { ArrayList implementations = (ArrayList) iter.next(); if( implementations.isEmpty() ) iter.remove(); } generateElementsByType(out, namespaceMapping, refercencedTypes); generateElementsDetail(out, namespaceMapping, refercencedTypes); generateElementsIndex(out, namespaceMapping, refercencedTypes); } private Type getNestedType(Type type) { if( type.isCollection() ) { return getNestedType(type.getNestedType()); } else { return type; } } private void generateElementsByType(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { out.println("h3. Elements By Type"); for (Iterator iter = refercencedTypes.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry) iter.next(); String className = (String) entry.getKey(); Collection elements = (Collection) entry.getValue(); out.println("{anchor:"+className+"-types}"); out.println("h4. The _["+className+"|#"+className+"-types]_ Type Implementations"); for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.println(" | _[<"+element.getElementName() +">|#"+element.getElementName() +"-element]_ | {html}"+element.getDescription()+"{html} |"); } out.println(); } out.println(); } private void generateElementsIndex(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { out.println("h3. Element Index"); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); out.println(" | _[<"+element.getElementName() +">|#"+element.getElementName() +"-element]_ | {html}"+element.getDescription()+"{html} |"); } out.println(); } private void generateElementsDetail(PrintWriter out, NamespaceMapping namespaceMapping, HashMap refercencedTypes) { for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementDetail(out, namespaceMapping, element, refercencedTypes); } } private void generateElementDetail(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element, HashMap refercencedTypes) { out.println("{anchor:" + element.getElementName() + "-element}"); out.println("h3. The _[<" + element.getElementName() + ">|#" + element.getElementName() + "-element]_ Element"); out.println(" {html}"+element.getDescription()+"{html}"); if( element.getAttributes().size() > 0 ) { out.println("h4. Properties"); out.println(" || Property Name || Type || Description ||"); for ( Iterator iterator = element.getAttributes().iterator(); iterator.hasNext(); ) { AttributeMapping attribute = (AttributeMapping) iterator.next(); Type type = attribute.getPropertyEditor() != null ? Type.newSimpleType(String.class.getName()): attribute.getType(); out.println(" | " + attribute.getAttributeName() + " | "+getTypeLink(type, refercencedTypes)+" | {html}"+attribute.getDescription()+"{html} |"); } } out.println(); } private String getTypeLink(Type type, HashMap refercencedTypes) { if (type.isCollection()) { return "(" + getTypeLink(type.getNestedType(), refercencedTypes) + ")\\*"; } else { if( refercencedTypes.containsKey(type.getName()) ) { return "_["+type.getName()+"|#"+type.getName()+"-types]_"; } else { return "_"+type.getName()+"_"; } } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/ElementMapping.java0000644000175000017500000001256611320711571032766 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class ElementMapping implements Comparable { private final String namespace; private final String elementName; private final String className; private final String description; private final boolean rootElement; private final String initMethod; private final String destroyMethod; private final String factoryMethod; private final String contentProperty; private final Set attributes; private final Map attributesByName; private final List constructors; private final List flatProperties; private final Map maps; private final Map flatCollections; private final List superClasses; private final HashSet interfaces; public ElementMapping(String namespace, String elementName, String className, String description, boolean rootElement, String initMethod, String destroyMethod, String factoryMethod, String contentProperty, Set attributes, List constructors, List flatProperties, Map maps, Map flatCollections, List superClasses, HashSet interfaces) { this.superClasses = superClasses; this.interfaces = interfaces; if (namespace == null) throw new NullPointerException("namespace"); if (elementName == null) throw new NullPointerException("elementName"); if (className == null) throw new NullPointerException("className"); if (attributes == null) throw new NullPointerException("attributes"); if (constructors == null) throw new NullPointerException("constructors"); this.namespace = namespace; this.elementName = elementName; this.className = className; this.description = description; this.rootElement = rootElement; this.initMethod = initMethod; this.destroyMethod = destroyMethod; this.factoryMethod = factoryMethod; this.contentProperty = contentProperty; this.constructors = constructors; this.attributes = Collections.unmodifiableSet(new TreeSet(attributes)); this.maps = Collections.unmodifiableMap(maps); this.flatProperties = Collections.unmodifiableList(flatProperties); this.flatCollections = Collections.unmodifiableMap(flatCollections); Map attributesByName = new HashMap(); for (Iterator iterator = attributes.iterator(); iterator.hasNext();) { AttributeMapping attribute = (AttributeMapping) iterator.next(); attributesByName.put(attribute.getAttributeName(), attribute); } this.attributesByName = Collections.unmodifiableMap(attributesByName); } public String getNamespace() { return namespace; } public String getElementName() { return elementName; } public String getClassName() { return className; } public String getDescription() { return description; } public boolean isRootElement() { return rootElement; } public String getInitMethod() { return initMethod; } public String getDestroyMethod() { return destroyMethod; } public String getFactoryMethod() { return factoryMethod; } public String getContentProperty() { return contentProperty; } public Set getAttributes() { return attributes; } public AttributeMapping getAttribute(String attributeName) { return (AttributeMapping) attributesByName.get(attributeName); } public Map getMapMappings() { return maps; } public MapMapping getMapMapping(String name) { return (MapMapping) maps.get(name); } public Map getFlatCollections() { return flatCollections; } public List getFlatProperties() { return flatProperties; } public List getConstructors() { return constructors; } public int hashCode() { return elementName.hashCode(); } public boolean equals(Object obj) { if (obj instanceof ElementMapping) { return elementName.equals(((ElementMapping) obj).elementName); } return false; } public int compareTo(Object obj) { return elementName.compareTo(((ElementMapping) obj).elementName); } public HashSet getInterfaces() { return interfaces; } public List getSuperClasses() { return superClasses; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/Type.java0000644000175000017500000000625411333220747031003 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.util.Set; import java.util.HashSet; import java.util.Collections; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class Type { private final String name; private final Type nestedType; private final boolean primitive; public static Type newSimpleType(String name) { if (name == null) throw new NullPointerException("type"); if (name.indexOf("[") >= 0 || name.indexOf("]") >= 0) { throw new IllegalArgumentException("Name can not contain '[' or ']' " + name); } return new Type(name, null); } public static Type newArrayType(String type, int dimensions) { if (type == null) throw new NullPointerException("type"); if (dimensions < 1) throw new IllegalArgumentException("dimensions must be at least one"); StringBuffer buf = new StringBuffer(type.length() + (dimensions * 2)); buf.append(type); for (int i = 0; i < dimensions; i ++) { buf.append("[]"); } return new Type(buf.toString(), newSimpleType(type)); } public static Type newCollectionType(String collectionType, Type elementType) { if (collectionType == null) throw new NullPointerException("collectionType"); if (elementType == null) throw new NullPointerException("elementType"); return new Type(collectionType, elementType); } private Type(String name, Type nestedType) { this.name = name; this.nestedType = nestedType; primitive = (nestedType == null) && primitives.contains(name); } public String getName() { return name; } public Type getNestedType() { return nestedType; } public boolean isCollection() { return nestedType != null; } public boolean isPrimitive() { return primitive; } public int hashCode() { return super.hashCode(); } public boolean equals(Object obj) { return super.equals(obj); } private static final Set primitives; static { Set set = new HashSet(); set.add("boolean"); set.add("byte"); set.add("char"); set.add("short"); set.add("int"); set.add("long"); set.add("float"); set.add("double"); primitives = Collections.unmodifiableSet(set); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/MappingLoader.java0000644000175000017500000000205111320711571032567 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.IOException; import java.util.Set; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public interface MappingLoader { Set loadNamespaces() throws IOException; } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/XmlMetadataGenerator.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/XmlMetadataGenerator.ja0000644000175000017500000002550011320711571033572 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Properties; import org.apache.xbean.blueprint.context.impl.NamespaceHelper; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class XmlMetadataGenerator implements GeneratorPlugin { private final String metaInfDir; private LogFacade log; private final File schema; public static final String NAMESPACE_HANDLER = "org.apache.xbean.blueprint.context.v2.XBeanNamespaceHandler"; private final boolean generateSpringSchemasFile; private final boolean generateSpringHandlersFile; public XmlMetadataGenerator(String metaInfDir, File schema) { this(metaInfDir, schema, true, true); } public XmlMetadataGenerator(String metaInfDir, File schema, boolean generateSpringSchemasFile, boolean generateSpringHandlersFile) { this.metaInfDir = metaInfDir; this.schema = schema; this.generateSpringSchemasFile = generateSpringSchemasFile; this.generateSpringHandlersFile = generateSpringHandlersFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); if (namespace == null) { return; } File file = new File(metaInfDir, NamespaceHelper.createDiscoveryPathName(namespace)); file.getParentFile().mkdirs(); log.log("Generating META-INF properties file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generatePropertiesFile(out, namespaceMapping.getElements()); } finally { out.close(); } if( generateSpringHandlersFile ) { // Generate spring 2.0 mapping file = new File(metaInfDir, "META-INF/spring.handlers"); Properties properties = new Properties(); if (!file.exists()) { log.log("Generating Spring 2.0 handler mapping: " + file + " for namespace: " + namespace); } else { log.log("Updating Spring 2.0 handler mapping: " + file + " for namespace: " + namespace); // read in current file InputStream in = new FileInputStream(file); try { properties.load(in); } catch (IOException e) { in.close(); } } // add property properties.put(namespace, NAMESPACE_HANDLER); // write properties OutputStream fout = new FileOutputStream(file); try { properties.store(fout, "Generated by xbean-spring"); } finally { fout.close(); } } if (schema != null && generateSpringSchemasFile ) { String cp = new File(metaInfDir).toURI().relativize(schema.toURI()).toString(); file = new File(metaInfDir, "META-INF/spring.schemas"); Properties properties = new Properties(); if (!file.exists()) { log.log("Generating Spring 2.0 schema mapping: " + file + " for namespace: " + namespace); } else { log.log("Updating Spring 2.0 schema mapping: " + file + " for namespace: " + namespace); // read in current file InputStream in = new FileInputStream(file); try { properties.load(in); } catch (IOException e) { in.close(); } } // add property String uri = namespace; if (!uri.endsWith("/")) { uri += "/"; } properties.put(uri + cp, cp); // write properties OutputStream fout = new FileOutputStream(file); try { properties.store(fout, "Generated by xbean-spring"); } finally { fout.close(); } } } private void generatePropertiesFile(PrintWriter out, Set elements) { out.println("# NOTE: this file is autogenerated by Apache XBean"); out.println(); out.println("# beans"); for (Iterator iter = elements.iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); out.println(element.getElementName() + " = " + element.getClassName()); generatePropertiesFileContent(out, element); generatePropertiesFilePropertyAliases(out, element); generatePropertiesFileConstructors(out, element); out.println(); } } private void generatePropertiesFileContent(PrintWriter out, ElementMapping element) { String contentProperty = element.getContentProperty(); if (contentProperty != null) { out.println(element.getElementName() + ".contentProperty = " + contentProperty); } String initMethod = element.getInitMethod(); if (initMethod != null) { out.println(element.getElementName() + ".initMethod = " + initMethod); } String destroyMethod = element.getDestroyMethod(); if (destroyMethod != null) { out.println(element.getElementName() + ".destroyMethod = " + destroyMethod); } String factoryMethod = element.getFactoryMethod(); if (factoryMethod != null) { out.println(element.getElementName() + ".factoryMethod = " + factoryMethod); } for (Iterator iter = element.getAttributes().iterator(); iter.hasNext();) { AttributeMapping attribute = (AttributeMapping) iter.next(); if( attribute.getPropertyEditor() !=null ) { out.println(element.getElementName() + "."+attribute.getPropertyName()+ ".propertyEditor = " + attribute.getPropertyEditor()); } } List flatProperties = element.getFlatProperties(); for (Iterator itr = flatProperties.iterator(); itr.hasNext();) { out.println(element.getElementName() + "." + itr.next() + ".flat"); } Map maps = element.getMapMappings(); for (Iterator itr = maps.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); MapMapping mm = (MapMapping) entry.getValue(); if (mm.getEntryName() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.entryName = " + mm.getEntryName()); } if (mm.getKeyName() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.keyName = " + mm.getKeyName()); } if (mm.isFlat()) { out.println(element.getElementName() + "." + entry.getKey() + ".map.flat = " + Boolean.toString(mm.isFlat())); } if (mm.getDupsMode() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.dups = " + mm.getDupsMode()); } if (mm.getDefaultKey() != null) { out.println(element.getElementName() + "." + entry.getKey() + ".map.defaultKey = " + mm.getDefaultKey()); } } Map flatCollections = element.getFlatCollections(); for (Iterator itr = flatCollections.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String child = (String) entry.getValue(); out.println(element.getElementName() + "." + child + ".flatCollection = " + entry.getKey()); } } private void generatePropertiesFileConstructors(PrintWriter out, ElementMapping element) { List constructors = element.getConstructors(); for (Iterator iterator = constructors.iterator(); iterator.hasNext();) { List args = (List) iterator.next(); generatePropertiesFileConstructor(out, element, args); } } private void generatePropertiesFileConstructor(PrintWriter out, ElementMapping element, List args) { out.print(element.getClassName()); if (element.getFactoryMethod() != null) { out.print("." + element.getFactoryMethod()); } out.print("("); for (Iterator iterator = args.iterator(); iterator.hasNext();) { ParameterMapping parameterMapping = (ParameterMapping) iterator.next(); out.print(parameterMapping.getType().getName()); if (iterator.hasNext()) { out.print(","); } } out.print(").parameterNames ="); for (Iterator iterator = args.iterator(); iterator.hasNext();) { ParameterMapping parameterMapping = (ParameterMapping) iterator.next(); out.print(" "); out.print(parameterMapping.getName()); } out.println(); } private void generatePropertiesFilePropertyAliases(PrintWriter out, ElementMapping element) { for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); String propertyName = attributeMapping.getPropertyName(); String attributeName = attributeMapping.getAttributeName(); if (!propertyName.equals(attributeName)) { if (List.class.getName().equals(attributeMapping.getType().getName())) { out.println(element.getElementName() + ".list." + attributeName + " = " + propertyName); } else { out.println(element.getElementName() + ".alias." + attributeName + " = " + propertyName); } } } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/InvalidModelException.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/InvalidModelException.j0000644000175000017500000000204511320711571033606 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class InvalidModelException extends RuntimeException { public InvalidModelException(String message) { super(message); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/NamespaceMapping.java0000644000175000017500000000562411320711571033266 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class NamespaceMapping implements Comparable { private final String namespace; private final Set elements; private final Map elementsByName; private final ElementMapping rootElement; public NamespaceMapping(String namespace, Set elements, ElementMapping rootElement) { this.namespace = namespace; this.elements = Collections.unmodifiableSet(new TreeSet(elements)); this.rootElement = rootElement; Map elementsByName = new HashMap(); for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ElementMapping elementMapping = (ElementMapping) iterator.next(); elementsByName.put(elementMapping.getElementName(), elementMapping); } this.elementsByName = Collections.unmodifiableMap(elementsByName); } public String getNamespace() { return namespace; } public Set getElements() { return elements; } public ElementMapping getElement(String elementName) { return (ElementMapping) elementsByName.get(elementName); } public ElementMapping getRootElement() { return rootElement; } public int hashCode() { return namespace.hashCode(); } public boolean equals(Object obj) { if (obj instanceof NamespaceMapping) { return namespace.equals(((NamespaceMapping) obj).namespace); } return false; } public int compareTo(Object obj) { return namespace.compareTo(((NamespaceMapping) obj).namespace); } private final HashMap checkedTypes = new HashMap(); public boolean isSimpleType(Type type) { Boolean b = (Boolean) checkedTypes.get(type); if (b == null){ b = Utils.isSimpleType(type)? Boolean.TRUE: Boolean.FALSE; checkedTypes.put(type, b); } return b.booleanValue(); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/QdoxMappingLoader.java0000644000175000017500000006012411320711571033430 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.BeanProperty; import com.thoughtworks.qdox.model.DocletTag; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.Type; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class QdoxMappingLoader implements MappingLoader { public static final String XBEAN_ANNOTATION = "org.apache.xbean.XBean"; public static final String PROPERTY_ANNOTATION = "org.apache.xbean.Property"; public static final String INIT_METHOD_ANNOTATION = "org.apache.xbean.InitMethod"; public static final String DESTROY_METHOD_ANNOTATION = "org.apache.xbean.DestroyMethod"; public static final String FACTORY_METHOD_ANNOTATION = "org.apache.xbean.FactoryMethod"; public static final String MAP_ANNOTATION = "org.apache.xbean.Map"; public static final String FLAT_PROPERTY_ANNOTATION = "org.apache.xbean.Flat"; public static final String FLAT_COLLECTION_ANNOTATION = "org.apache.xbean.FlatCollection"; public static final String ELEMENT_ANNOTATION = "org.apache.xbean.Element"; private static final Log log = LogFactory.getLog(QdoxMappingLoader.class); private final String defaultNamespace; private final File[] srcDirs; private final String[] excludedClasses; private Type collectionType; public QdoxMappingLoader(String defaultNamespace, File[] srcDirs, String[] excludedClasses) { this.defaultNamespace = defaultNamespace; this.srcDirs = srcDirs; this.excludedClasses = excludedClasses; } public String getDefaultNamespace() { return defaultNamespace; } public File[] getSrcDirs() { return srcDirs; } public Set loadNamespaces() throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); log.debug("Source directories: "); for (File sourceDirectory : srcDirs) { if (!sourceDirectory.isDirectory() && !sourceDirectory.toString().endsWith(".jar")) { log.warn("Specified source directory isn't a directory or a jar file: '" + sourceDirectory.getAbsolutePath() + "'."); } log.debug(" - " + sourceDirectory.getAbsolutePath()); getSourceFiles(sourceDirectory, excludedClasses, builder); } collectionType = builder.getClassByName("java.util.Collection").asType(); return loadNamespaces(builder); } private Set loadNamespaces(JavaDocBuilder builder) { // load all of the elements List elements = loadElements(builder); // index the elements by namespace and find the root element of each namespace Map> elementsByNamespace = new HashMap>(); Map namespaceRoots = new HashMap(); for (ElementMapping element : elements) { String namespace = element.getNamespace(); Set namespaceElements = elementsByNamespace.get(namespace); if (namespaceElements == null) { namespaceElements = new HashSet(); elementsByNamespace.put(namespace, namespaceElements); } namespaceElements.add(element); if (element.isRootElement()) { if (namespaceRoots.containsKey(namespace)) { log.info("Multiple root elements found for namespace " + namespace); } namespaceRoots.put(namespace, element); } } // build the NamespaceMapping objects Set namespaces = new TreeSet(); for (Map.Entry> entry : elementsByNamespace.entrySet()) { String namespace = entry.getKey(); Set namespaceElements = entry.getValue(); ElementMapping rootElement = namespaceRoots.get(namespace); NamespaceMapping namespaceMapping = new NamespaceMapping(namespace, namespaceElements, rootElement); namespaces.add(namespaceMapping); } return Collections.unmodifiableSet(namespaces); } private List loadElements(JavaDocBuilder builder) { JavaSource[] javaSources = builder.getSources(); List elements = new ArrayList(); for (JavaSource javaSource : javaSources) { if (javaSource.getClasses().length == 0) { log.info("No Java Classes defined in: " + javaSource.getURL()); } else { JavaClass[] classes = javaSource.getClasses(); for (JavaClass javaClass : classes) { ElementMapping element = loadElement(builder, javaClass); if (element != null && !javaClass.isAbstract()) { elements.add(element); } else { log.debug("No XML annotation found for type: " + javaClass.getFullyQualifiedName()); } } } } return elements; } private ElementMapping loadElement(JavaDocBuilder builder, JavaClass javaClass) { DocletTag xbeanTag = javaClass.getTagByName(XBEAN_ANNOTATION); if (xbeanTag == null) { return null; } String element = getElementName(javaClass, xbeanTag); String description = getProperty(xbeanTag, "description"); if (description == null) { description = javaClass.getComment(); } String namespace = getProperty(xbeanTag, "namespace", defaultNamespace); boolean root = getBooleanProperty(xbeanTag, "rootElement"); String contentProperty = getProperty(xbeanTag, "contentProperty"); String factoryClass = getProperty(xbeanTag, "factoryClass"); Map mapsByPropertyName = new HashMap(); List flatProperties = new ArrayList(); Map flatCollections = new HashMap(); Set attributes = new HashSet(); Map attributesByPropertyName = new HashMap(); for (JavaClass jClass = javaClass; jClass != null; jClass = jClass.getSuperJavaClass()) { BeanProperty[] beanProperties = jClass.getBeanProperties(); for (BeanProperty beanProperty : beanProperties) { // we only care about properties with a setter if (beanProperty.getMutator() != null) { AttributeMapping attributeMapping = loadAttribute(beanProperty, ""); if (attributeMapping != null) { attributes.add(attributeMapping); attributesByPropertyName.put(attributeMapping.getPropertyName(), attributeMapping); } JavaMethod acc = beanProperty.getAccessor(); if (acc != null) { DocletTag mapTag = acc.getTagByName(MAP_ANNOTATION); if (mapTag != null) { MapMapping mm = new MapMapping( mapTag.getNamedParameter("entryName"), mapTag.getNamedParameter("keyName"), Boolean.valueOf(mapTag.getNamedParameter("flat")), mapTag.getNamedParameter("dups"), mapTag.getNamedParameter("defaultKey")); mapsByPropertyName.put(beanProperty.getName(), mm); } DocletTag flatColTag = acc.getTagByName(FLAT_COLLECTION_ANNOTATION); if (flatColTag != null) { String childName = flatColTag.getNamedParameter("childElement"); if (childName == null) throw new InvalidModelException("Flat collections must specify the childElement attribute."); flatCollections.put(beanProperty.getName(), childName); } DocletTag flatPropTag = acc.getTagByName(FLAT_PROPERTY_ANNOTATION); if (flatPropTag != null) { flatProperties.add(beanProperty.getName()); } } } } } String initMethod = null; String destroyMethod = null; String factoryMethod = null; for (JavaClass jClass = javaClass; jClass != null; jClass = jClass.getSuperJavaClass()) { JavaMethod[] methods = javaClass.getMethods(); for (JavaMethod method : methods) { if (method.isPublic() && !method.isConstructor()) { if (initMethod == null && method.getTagByName(INIT_METHOD_ANNOTATION) != null) { initMethod = method.getName(); } if (destroyMethod == null && method.getTagByName(DESTROY_METHOD_ANNOTATION) != null) { destroyMethod = method.getName(); } if (factoryMethod == null && method.getTagByName(FACTORY_METHOD_ANNOTATION) != null) { factoryMethod = method.getName(); } } } } List> constructorArgs = new ArrayList>(); JavaMethod[] methods = javaClass.getMethods(); for (JavaMethod method : methods) { JavaParameter[] parameters = method.getParameters(); if (isValidConstructor(factoryMethod, method, parameters)) { List args = new ArrayList(parameters.length); for (JavaParameter parameter : parameters) { AttributeMapping attributeMapping = attributesByPropertyName.get(parameter.getName()); if (attributeMapping == null) { attributeMapping = loadParameter(parameter); attributes.add(attributeMapping); attributesByPropertyName.put(attributeMapping.getPropertyName(), attributeMapping); } args.add(new ParameterMapping(attributeMapping.getPropertyName(), toMappingType(parameter.getType(), null))); } constructorArgs.add(Collections.unmodifiableList(args)); } } HashSet interfaces = new HashSet(); interfaces.addAll(getFullyQualifiedNames(javaClass.getImplementedInterfaces())); JavaClass actualClass = javaClass; if (factoryClass != null) { JavaClass clazz = builder.getClassByName(factoryClass); if (clazz != null) { log.info("Detected factory: using " + factoryClass + " instead of " + javaClass.getFullyQualifiedName()); actualClass = clazz; } else { log.info("Could not load class built by factory: " + factoryClass); } } ArrayList superClasses = new ArrayList(); JavaClass p = actualClass; if (actualClass != javaClass) { superClasses.add(actualClass.getFullyQualifiedName()); } while (true) { JavaClass s = p.getSuperJavaClass(); if (s == null || s.equals(p) || "java.lang.Object".equals(s.getFullyQualifiedName())) { break; } p = s; superClasses.add(p.getFullyQualifiedName()); interfaces.addAll(getFullyQualifiedNames(p.getImplementedInterfaces())); } return new ElementMapping(namespace, element, javaClass.getFullyQualifiedName(), description, root, initMethod, destroyMethod, factoryMethod, contentProperty, attributes, constructorArgs, flatProperties, mapsByPropertyName, flatCollections, superClasses, interfaces); } private List getFullyQualifiedNames(JavaClass[] implementedInterfaces) { ArrayList l = new ArrayList(); for (JavaClass implementedInterface : implementedInterfaces) { l.add(implementedInterface.getFullyQualifiedName()); } return l; } private String getElementName(JavaClass javaClass, DocletTag tag) { String elementName = getProperty(tag, "element"); if (elementName == null) { String className = javaClass.getFullyQualifiedName(); int index = className.lastIndexOf("."); if (index > 0) { className = className.substring(index + 1); } // strip off "Bean" from a spring factory bean if (className.endsWith("FactoryBean")) { className = className.substring(0, className.length() - 4); } elementName = Utils.decapitalise(className); } return elementName; } private AttributeMapping loadAttribute(BeanProperty beanProperty, String defaultDescription) { DocletTag propertyTag = getPropertyTag(beanProperty); if (getBooleanProperty(propertyTag, "hidden")) { return null; } String attribute = getProperty(propertyTag, "alias", beanProperty.getName()); String attributeDescription = getAttributeDescription(beanProperty, propertyTag, defaultDescription); String defaultValue = getProperty(propertyTag, "default"); boolean fixed = getBooleanProperty(propertyTag, "fixed"); boolean required = getBooleanProperty(propertyTag, "required"); String nestedType = getProperty(propertyTag, "nestedType"); String propertyEditor = getProperty(propertyTag, "propertyEditor"); return new AttributeMapping(attribute, beanProperty.getName(), attributeDescription, toMappingType(beanProperty.getType(), nestedType), defaultValue, fixed, required, propertyEditor); } private static DocletTag getPropertyTag(BeanProperty beanProperty) { JavaMethod accessor = beanProperty.getAccessor(); if (accessor != null) { DocletTag propertyTag = accessor.getTagByName(PROPERTY_ANNOTATION); if (propertyTag != null) { return propertyTag; } } JavaMethod mutator = beanProperty.getMutator(); if (mutator != null) { DocletTag propertyTag = mutator.getTagByName(PROPERTY_ANNOTATION); if (propertyTag != null) { return propertyTag; } } return null; } private String getAttributeDescription(BeanProperty beanProperty, DocletTag propertyTag, String defaultDescription) { String description = getProperty(propertyTag, "description"); if (description != null && description.trim().length() > 0) { return description.trim(); } JavaMethod accessor = beanProperty.getAccessor(); if (accessor != null) { description = accessor.getComment(); if (description != null && description.trim().length() > 0) { return description.trim(); } } JavaMethod mutator = beanProperty.getMutator(); if (mutator != null) { description = mutator.getComment(); if (description != null && description.trim().length() > 0) { return description.trim(); } } return defaultDescription; } private AttributeMapping loadParameter(JavaParameter parameter) { String parameterName = parameter.getName(); String parameterDescription = getParameterDescription(parameter); // first attempt to load the attribute from the java beans accessor methods JavaClass javaClass = parameter.getParentMethod().getParentClass(); BeanProperty beanProperty = javaClass.getBeanProperty(parameterName); if (beanProperty != null) { AttributeMapping attributeMapping = loadAttribute(beanProperty, parameterDescription); // if the attribute mapping is null, the property was tagged as hidden and this is an error if (attributeMapping == null) { throw new InvalidModelException("Hidden property usage: " + "The construction method " + toMethodLocator(parameter.getParentMethod()) + " can not use a hidded property " + parameterName); } return attributeMapping; } // create an attribute solely based on the parameter information return new AttributeMapping(parameterName, parameterName, parameterDescription, toMappingType(parameter.getType(), null), null, false, false, null); } private String getParameterDescription(JavaParameter parameter) { String parameterName = parameter.getName(); DocletTag[] tags = parameter.getParentMethod().getTagsByName("param"); for (DocletTag tag : tags) { if (tag.getParameters()[0].equals(parameterName)) { String parameterDescription = tag.getValue().trim(); if (parameterDescription.startsWith(parameterName)) { parameterDescription = parameterDescription.substring(parameterName.length()).trim(); } return parameterDescription; } } return null; } private boolean isValidConstructor(String factoryMethod, JavaMethod method, JavaParameter[] parameters) { if (!method.isPublic() || parameters.length == 0) { return false; } if (factoryMethod == null) { return method.isConstructor(); } else { return method.getName().equals(factoryMethod); } } private static String getProperty(DocletTag propertyTag, String propertyName) { return getProperty(propertyTag, propertyName, null); } private static String getProperty(DocletTag propertyTag, String propertyName, String defaultValue) { String value = null; if (propertyTag != null) { value = propertyTag.getNamedParameter(propertyName); } if (value == null) { return defaultValue; } return value; } private boolean getBooleanProperty(DocletTag propertyTag, String propertyName) { return toBoolean(getProperty(propertyTag, propertyName)); } private static boolean toBoolean(String value) { if (value != null) { return Boolean.valueOf(value); } return false; } private org.apache.xbean.blueprint.generator.Type toMappingType(Type type, String nestedType) { try { if (type.isArray()) { return org.apache.xbean.blueprint.generator.Type.newArrayType(type.getValue(), type.getDimensions()); } else if (type.isA(collectionType)) { if (nestedType == null) nestedType = "java.lang.Object"; return org.apache.xbean.blueprint.generator.Type.newCollectionType(type.getValue(), org.apache.xbean.blueprint.generator.Type.newSimpleType(nestedType)); } } catch (Throwable t) { log.debug("Could not load type mapping", t); } return org.apache.xbean.blueprint.generator.Type.newSimpleType(type.getValue()); } private static String toMethodLocator(JavaMethod method) { StringBuffer buf = new StringBuffer(); buf.append(method.getParentClass().getFullyQualifiedName()); if (!method.isConstructor()) { buf.append(".").append(method.getName()); } buf.append("("); JavaParameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { JavaParameter parameter = parameters[i]; if (i > 0) { buf.append(", "); } buf.append(parameter.getName()); } buf.append(") : ").append(method.getLineNumber()); return buf.toString(); } private static void getSourceFiles(File base, String[] excludedClasses, JavaDocBuilder builder) throws IOException { if (base.isDirectory()) { listAllFileNames(base, "", excludedClasses, builder); } else { listAllJarEntries(base, excludedClasses, builder); } } private static void listAllFileNames(File base, String prefix, String[] excludedClasses, JavaDocBuilder builder) throws IOException { if (!base.canRead() || !base.isDirectory()) { throw new IllegalArgumentException(base.getAbsolutePath()); } File[] hits = base.listFiles(); for (File hit : hits) { String name = prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName(); if (hit.canRead() && !isExcluded(name, excludedClasses)) { if (hit.isDirectory()) { listAllFileNames(hit, name, excludedClasses, builder); } else if (name.endsWith(".java")) { builder.addSource(hit); } } } } private static void listAllJarEntries(File base, String[] excludedClasses, JavaDocBuilder builder) throws IOException { JarFile jarFile = new JarFile(base); for (Enumeration entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (name.endsWith(".java") && !isExcluded(name, excludedClasses) && !name.endsWith("/package-info.java")) { builder.addSource(new URL("jar:" + base.toURL().toString() + "!/" + name)); } } } private static boolean isExcluded(String sourceName, String[] excludedClasses) { if (excludedClasses == null) { return false; } String className = sourceName; if (sourceName.endsWith(".java")) { className = className.substring(0, className.length() - ".java".length()); } className = className.replace('/', '.'); for (String excludedClass : excludedClasses) { if (className.equals(excludedClass)) { return true; } } return false; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/MappingGeneratorTask.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/MappingGeneratorTask.ja0000644000175000017500000001225611320711571033613 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import java.io.File; import java.util.Iterator; import java.util.Set; import java.util.List; import java.util.LinkedList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.beans.PropertyEditorManager; /** * An Ant task for executing generating mapping metadata. * * @version $Revision: 896187 $ */ public class MappingGeneratorTask extends MatchingTask implements LogFacade { private String namespace; private Path srcDir; private String excludedClasses = null; private File destFile = new File("target/classes/schema.xsd"); private String metaInfDir = "target/classes/"; private String propertyEditorPaths = "org.apache.xbean.blueprint.context.impl"; public File getDestFile() { return destFile; } public void setDestFile(File destFile) { this.destFile = destFile; } public String getMetaInfDir() { return metaInfDir; } public void setMetaInfDir(String metaInfDir) { this.metaInfDir = metaInfDir; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Path getSrcDir() { return srcDir; } public void setSrcDir(Path srcDir) { this.srcDir = srcDir; } public String getPropertyEditorPaths() { return propertyEditorPaths; } public void setPropertyEditorPaths(String propertyEditorPaths) { this.propertyEditorPaths = propertyEditorPaths; } public void execute() throws BuildException { if (namespace == null) { throw new BuildException("'namespace' must be specified"); } if (srcDir == null) { throw new BuildException("'srcDir' must be specified"); } if (destFile == null) { throw new BuildException("'destFile' must be specified"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); editorSearchPath.addAll(Collections.list(paths)); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } MappingLoader mappingLoader = new QdoxMappingLoader(namespace, getFiles(srcDir), excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(metaInfDir, destFile), new DocumentationGenerator(destFile), new XsdGenerator(destFile) }; // load the mappings Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.setLog(this); plugin.generate(namespaceMapping); } } log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } private File[] getFiles(Path path) { if (path == null) { return null; } String[] paths = path.list(); File[] files = new File[paths.length]; for (int i = 0; i < files.length; i++) { files[i] = new File(paths[i]).getAbsoluteFile(); } return files; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/DocumentationGenerator.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/DocumentationGenerator.0000644000175000017500000002003611320711571033666 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class DocumentationGenerator implements GeneratorPlugin { private final File destFile; private LogFacade log; public DocumentationGenerator(File destFile) { this.destFile = destFile; } public void generate(NamespaceMapping namespaceMapping) throws IOException { String namespace = namespaceMapping.getNamespace(); // TODO can only handle 1 schema document so far... File file = new File(destFile.getParentFile(), destFile.getName() + ".html"); log.log("Generating HTML documentation file: " + file + " for namespace: " + namespace); PrintWriter out = new PrintWriter(new FileWriter(file)); try { generateDocumentation(out, namespaceMapping); } finally { out.close(); } } private void generateDocumentation(PrintWriter out, NamespaceMapping namespaceMapping) { String namespace = namespaceMapping.getNamespace(); out.println(""); out.println(""); out.println(""); out.println("Schema for namespace: " + namespace + ""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(); out.println(""); out.println(); generateRootElement(out, namespaceMapping); generateElementsSummary(out, namespaceMapping); out.println(); out.println(); generateElementsDetail(out, namespaceMapping); out.println(); out.println(""); out.println(""); } private void generateRootElement(PrintWriter out, NamespaceMapping namespaceMapping) { ElementMapping rootElement = namespaceMapping.getRootElement(); if (rootElement != null) { out.println("

Root Element

"); out.println(""); out.println(" "); generateElementSummary(out, rootElement); out.println("
ElementDescriptionClass
"); out.println(); } } private void generateElementsSummary(PrintWriter out, NamespaceMapping namespaceMapping) { out.println("

Element Summary

"); out.println(""); out.println(" "); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateElementSummary(out, element); } out.println("
ElementDescriptionClass
"); } private void generateElementSummary(PrintWriter out, ElementMapping element) { out.println(" " + "" + element.getElementName() + "" + "" + element.getDescription() + "" + "" + element.getClassName() + ""); } private void generateElementsDetail(PrintWriter out, NamespaceMapping namespaceMapping) { out.println("

Element Detail

"); for (Iterator iter = namespaceMapping.getElements().iterator(); iter.hasNext();) { ElementMapping element = (ElementMapping) iter.next(); generateHtmlElementDetail(out, namespaceMapping, element); } } private void generateHtmlElementDetail(PrintWriter out, NamespaceMapping namespaceMapping, ElementMapping element) { out.println("

Element: " + element.getElementName() + "

"); boolean hasAttributes = false; boolean hasElements = false; for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext() && (!hasAttributes || !hasElements);) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getType(); if (namespaceMapping.isSimpleType(type)) { hasAttributes = true; } else { hasElements = true; } } if (hasAttributes) { out.println(""); out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getPropertyEditor() != null ? Type.newSimpleType(String.class.getName()) : attributeMapping.getType(); if (namespaceMapping.isSimpleType(type)) { out.println(" "); } } out.println("
AttributeTypeDescription
" + attributeMapping.getAttributeName() + "" + Utils.getXsdType(type) + "" + attributeMapping.getDescription() + "
"); } if (hasElements) { out.println(""); out.println(" "); for (Iterator iterator = element.getAttributes().iterator(); iterator.hasNext();) { AttributeMapping attributeMapping = (AttributeMapping) iterator.next(); Type type = attributeMapping.getType(); if (!namespaceMapping.isSimpleType(type)) { out.print(" "); } } out.println("
ElementTypeDescription
" + attributeMapping.getAttributeName() + ""); printComplexPropertyTypeDocumentation(out, namespaceMapping, type); out.println("" + attributeMapping.getDescription() + "
"); } } private void printComplexPropertyTypeDocumentation(PrintWriter out, NamespaceMapping namespaceMapping, Type type) { if (type.isCollection()) { out.print("("); } List types; if (type.isCollection()) { types = Utils.findImplementationsOf(namespaceMapping, type.getNestedType()); } else { types = Utils.findImplementationsOf(namespaceMapping, type); } for (Iterator iterator = types.iterator(); iterator.hasNext();) { ElementMapping element = (ElementMapping) iterator.next(); out.print("" + element.getElementName() + ""); if (iterator.hasNext()) { out.print(" | "); } } if (types.size() == 0) { out.print("<spring:bean/>"); } if (type.isCollection()) { out.print(")*"); } } public LogFacade getLog() { return log; } public void setLog(LogFacade log) { this.log = log; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/GeneratorPlugin.java0000644000175000017500000000212711320711571033156 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import java.io.IOException; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public interface GeneratorPlugin { void generate(NamespaceMapping namespaceMapping) throws IOException; LogFacade getLog(); void setLog(LogFacade log); } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/cm/0000755000175000017500000000000011610661037025620 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/cm/CmNamespaceHandler.java0000644000175000017500000007007111333220747032143 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.cm; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.ext.ExtNamespaceHandler; import org.apache.aries.blueprint.ext.PlaceholdersUtils; import org.apache.aries.blueprint.mutable.MutableBeanMetadata; import org.apache.aries.blueprint.mutable.MutableCollectionMetadata; import org.apache.aries.blueprint.mutable.MutableComponentMetadata; import org.apache.aries.blueprint.mutable.MutableIdRefMetadata; import org.apache.aries.blueprint.mutable.MutableMapMetadata; import org.apache.aries.blueprint.mutable.MutableRefMetadata; import org.apache.aries.blueprint.mutable.MutableReferenceMetadata; import org.apache.aries.blueprint.mutable.MutableValueMetadata; import org.osgi.service.blueprint.container.BlueprintContainer; import org.osgi.service.blueprint.container.ComponentDefinitionException; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.IdRefMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.RefMetadata; import org.osgi.service.blueprint.reflect.ReferenceMetadata; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Modified from aries CmNamespaceHandler * * @version $Rev: 907189 $ $Date: 2010-02-06 09:01:43 +0100 (sam. 06 févr. 2010) $ */ public class CmNamespaceHandler implements NamespaceHandler { public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0"; public static final String XBEAN_CM_NAMESPACE = "http://xbean.apache.org/blueprint/xmlns/xbean-cm/v1.0.0"; public static final String PROPERTY_PLACEHOLDER_ELEMENT = "property-placeholder"; // public static final String MANAGED_PROPERTIES_ELEMENT = "managed-properties"; // public static final String MANAGED_SERVICE_FACTORY_ELEMENT = "managed-service-factory"; public static final String CM_PROPERTIES_ELEMENT = "cm-properties"; public static final String DEFAULT_PROPERTIES_ELEMENT = "default-properties"; public static final String PROPERTY_ELEMENT = "property"; public static final String INTERFACES_ELEMENT = "interfaces"; public static final String VALUE_ELEMENT = "value"; public static final String MANAGED_COMPONENT_ELEMENT = "managed-component"; public static final String ID_ATTRIBUTE = "id"; public static final String PERSISTENT_ID_ATTRIBUTE = "persistent-id"; public static final String PLACEHOLDER_PREFIX_ATTRIBUTE = "placeholder-prefix"; public static final String PLACEHOLDER_SUFFIX_ATTRIBUTE = "placeholder-suffix"; public static final String DEFAULTS_REF_ATTRIBUTE = "defaults-ref"; public static final String UPDATE_STRATEGY_ATTRIBUTE = "update-strategy"; public static final String UPDATE_METHOD_ATTRIBUTE = "update-method"; public static final String FACTORY_PID_ATTRIBUTE = "factory-pid"; public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export"; public static final String RANKING_ATTRIBUTE = "ranking"; public static final String INTERFACE_ATTRIBUTE = "interface"; public static final String UPDATE_ATTRIBUTE = "update"; public static final String AUTO_EXPORT_DISABLED = "disabled"; public static final String AUTO_EXPORT_INTERFACES = "interfaces"; public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy"; public static final String AUTO_EXPORT_ALL = "all-classes"; public static final String AUTO_EXPORT_DEFAULT = AUTO_EXPORT_DISABLED; public static final String RANKING_DEFAULT = "0"; private static final String MANAGED_OBJECT_MANAGER_NAME = "org.apache.aries.managedObjectManager"; private static final Logger LOGGER = LoggerFactory.getLogger(CmNamespaceHandler.class); // private final ConfigurationAdmin configAdmin; private int idCounter; // public CmNamespaceHandler(ConfigurationAdmin configAdmin) { // this.configAdmin = configAdmin; // } public URL getSchemaLocation(String namespace) { return getClass().getResource("xbean-cm.xsd"); } public Set getManagedClasses() { return new HashSet(Arrays.asList( JexlPropertyPlaceholder.class )); } public Metadata parse(Element element, ParserContext context) { LOGGER.debug("Parsing element {{}}{}", element.getNamespaceURI(), element.getLocalName()); ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); // registerManagedObjectManager(context, registry); if (nodeNameEquals(element, PROPERTY_PLACEHOLDER_ELEMENT)) { return parsePropertyPlaceholder(context, element); // } else if (nodeNameEquals(element, MANAGED_SERVICE_FACTORY_ELEMENT)) { // return parseManagedServiceFactory(context, element); } else { throw new ComponentDefinitionException("Unsupported element: " + element.getNodeName()); } } public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) { LOGGER.debug("Decorating node {{}}{}", node.getNamespaceURI(), node.getLocalName()); ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); // registerManagedObjectManager(context, registry); if (node instanceof Element) { // if (nodeNameEquals(node, MANAGED_PROPERTIES_ELEMENT)) { // return decorateManagedProperties(context, (Element) node, component); // } else // if (nodeNameEquals(node, CM_PROPERTIES_ELEMENT)) { // return decorateCmProperties(context, (Element) node, component); // } else { throw new ComponentDefinitionException("Unsupported element: " + node.getNodeName()); // } } else { throw new ComponentDefinitionException("Illegal use of blueprint cm namespace"); } } private ComponentMetadata parsePropertyPlaceholder(ParserContext context, Element element) { MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class); metadata.setProcessor(true); metadata.setId(getId(context, element)); metadata.setScope(BeanMetadata.SCOPE_SINGLETON); metadata.setRuntimeClass(JexlPropertyPlaceholder.class); metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); // metadata.addProperty("configAdmin", createConfigAdminProxy(context)); metadata.addProperty("configAdmin", createReference(context, ConfigurationAdmin.class.getName())); metadata.addProperty("persistentId", createValue(context, element.getAttribute(PERSISTENT_ID_ATTRIBUTE))); // metadata.addArgument(createRef(context, "blueprintContainer"), BlueprintContainer.class.getName(), 0); // metadata.addArgument(createReference(context, ConfigurationAdmin.class.getName()), ConfigurationAdmin.class.getName(), 1); // metadata.addArgument(createValue(context, element.getAttribute(PERSISTENT_ID_ATTRIBUTE)), String.class.getName(), 2); String prefix = element.hasAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE) ? element.getAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE) : "${"; metadata.addProperty("placeholderPrefix", createValue(context, prefix)); String suffix = element.hasAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE) ? element.getAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE) : "}"; metadata.addProperty("placeholderSuffix", createValue(context, suffix)); String defaultsRef = element.hasAttribute(DEFAULTS_REF_ATTRIBUTE) ? element.getAttribute(DEFAULTS_REF_ATTRIBUTE) : null; if (defaultsRef != null) { metadata.addProperty("defaultProperties", createRef(context, defaultsRef)); } String ignoreMissingLocations = element.hasAttributeNS(ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE, ExtNamespaceHandler.IGNORE_MISSING_LOCATIONS_ATTRIBUTE) ? element.getAttributeNS(ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE, ExtNamespaceHandler.IGNORE_MISSING_LOCATIONS_ATTRIBUTE) : null; if (ignoreMissingLocations != null) { metadata.addProperty("ignoreMissingLocations", createValue(context, ignoreMissingLocations)); } String systemProperties = element.hasAttributeNS(ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE, ExtNamespaceHandler.SYSTEM_PROPERTIES_ATTRIBUTE) ? element.getAttributeNS(ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE, ExtNamespaceHandler.SYSTEM_PROPERTIES_ATTRIBUTE) : null; if (systemProperties == null) { systemProperties = ExtNamespaceHandler.SYSTEM_PROPERTIES_NEVER; } metadata.addProperty("systemProperties", createValue(context, systemProperties)); // Parse elements List locations = new ArrayList(); NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element e = (Element) node; if (XBEAN_CM_NAMESPACE.equals(e.getNamespaceURI())) { if (nodeNameEquals(e, DEFAULT_PROPERTIES_ELEMENT)) { if (defaultsRef != null) { throw new ComponentDefinitionException("Only one of " + DEFAULTS_REF_ATTRIBUTE + " attribute or " + DEFAULT_PROPERTIES_ELEMENT + " element is allowed"); } Metadata props = parseDefaultProperties(context, metadata, e); metadata.addProperty("defaultProperties", props); } } else if (ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE.equals(e.getNamespaceURI())) { if (nodeNameEquals(e, ExtNamespaceHandler.LOCATION_ELEMENT)) { locations.add(getTextValue(e)); } } } } if (!locations.isEmpty()) { metadata.addProperty("locations", createList(context, locations)); } // PlaceholdersUtils.validatePlaceholder(metadata, context.getComponentDefinitionRegistry()); return metadata; } private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) { MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class); NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element e = (Element) node; if (XBEAN_CM_NAMESPACE.equals(e.getNamespaceURI())) { if (nodeNameEquals(e, PROPERTY_ELEMENT)) { BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e); props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue()); } } } } return props; } // private ComponentMetadata parseManagedServiceFactory(ParserContext context, Element element) { // String id = getId(context, element); // // MutableBeanMetadata factoryMetadata = context.createMetadata(MutableBeanMetadata.class); // generateIdIfNeeded(context, factoryMetadata); // factoryMetadata.addProperty("id", createValue(context, factoryMetadata.getId())); // factoryMetadata.setScope(BeanMetadata.SCOPE_SINGLETON); // factoryMetadata.setRuntimeClass(CmManagedServiceFactory.class); // factoryMetadata.setInitMethod("init"); // factoryMetadata.setDestroyMethod("destroy"); // factoryMetadata.addProperty("configAdmin", createConfigAdminProxy(context)); // factoryMetadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); // factoryMetadata.addProperty("factoryPid", createValue(context, element.getAttribute(FACTORY_PID_ATTRIBUTE))); // String autoExport = element.hasAttribute(AUTO_EXPORT_ATTRIBUTE) ? element.getAttribute(AUTO_EXPORT_ATTRIBUTE) : AUTO_EXPORT_DEFAULT; // if (AUTO_EXPORT_DISABLED.equals(autoExport)) { // autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_DISABLED); // } else if (AUTO_EXPORT_INTERFACES.equals(autoExport)) { // autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_INTERFACES); // } else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExport)) { // autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY); // } else if (AUTO_EXPORT_ALL.equals(autoExport)) { // autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES); // } else { // throw new ComponentDefinitionException("Illegal value (" + autoExport + ") for " + AUTO_EXPORT_ATTRIBUTE + " attribute"); // } // factoryMetadata.addProperty("autoExport", createValue(context, autoExport)); // String ranking = element.hasAttribute(RANKING_ATTRIBUTE) ? element.getAttribute(RANKING_ATTRIBUTE) : RANKING_DEFAULT; // factoryMetadata.addProperty("ranking", createValue(context, ranking)); // // List interfaces = null; // if (element.hasAttribute(INTERFACE_ATTRIBUTE)) { // interfaces = Collections.singletonList(element.getAttribute(INTERFACE_ATTRIBUTE)); // factoryMetadata.addProperty("interfaces", createList(context, interfaces)); // } // // Parser parser = getParser(context); // // // Parse elements // List listeners = new ArrayList(); // NodeList nl = element.getChildNodes(); // for (int i = 0; i < nl.getLength(); i++) { // Node node = nl.item(i); // if (node instanceof Element) { // Element e = (Element) node; // if (isBlueprintNamespace(e.getNamespaceURI())) { // if (nodeNameEquals(e, INTERFACES_ELEMENT)) { // if (interfaces != null) { // throw new ComponentDefinitionException("Only one of " + Parser.INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be used"); // } // interfaces = parseInterfaceNames(e); // factoryMetadata.addProperty("interfaces", createList(context, interfaces)); // } else if (nodeNameEquals(e, Parser.SERVICE_PROPERTIES_ELEMENT)) { // MapMetadata map = parser.parseServiceProperties(e, factoryMetadata); // factoryMetadata.addProperty("serviceProperties", map); // } else if (nodeNameEquals(e, Parser.REGISTRATION_LISTENER_ELEMENT)) { // listeners.add(parser.parseRegistrationListener(e, factoryMetadata)); // } // } else if (XBEAN_CM_NAMESPACE.equals(e.getNamespaceURI())) { // if (nodeNameEquals(e, MANAGED_COMPONENT_ELEMENT)) { // MutableBeanMetadata managedComponent = context.parseElement(MutableBeanMetadata.class, null, e); // generateIdIfNeeded(context, managedComponent); // managedComponent.setScope(BeanMetadata.SCOPE_PROTOTYPE); // // destroy-method on managed-component has different signature than on regular beans // // so we'll handle it differently // String destroyMethod = managedComponent.getDestroyMethod(); // if (destroyMethod != null) { // factoryMetadata.addProperty("componentDestroyMethod", createValue(context, destroyMethod)); // managedComponent.setDestroyMethod(null); // } // context.getComponentDefinitionRegistry().registerComponentDefinition(managedComponent); // factoryMetadata.addProperty("managedComponentName", createIdRef(context, managedComponent.getId())); // } // } // } // } // // MutableCollectionMetadata listenerCollection = context.createMetadata(MutableCollectionMetadata.class); // listenerCollection.setCollectionClass(List.class); // for (RegistrationListener listener : listeners) { // MutableBeanMetadata bean = context.createMetadata(MutableBeanMetadata.class); // bean.setRuntimeClass(ServiceListener.class); // bean.addProperty("listener", listener.getListenerComponent()); // bean.addProperty("registerMethod", createValue(context, listener.getRegistrationMethod())); // bean.addProperty("unregisterMethod", createValue(context, listener.getUnregistrationMethod())); // listenerCollection.addValue(bean); // } // factoryMetadata.addProperty("listeners", listenerCollection); // // context.getComponentDefinitionRegistry().registerComponentDefinition(factoryMetadata); // // MutableBeanMetadata mapMetadata = context.createMetadata(MutableBeanMetadata.class); // mapMetadata.setScope(BeanMetadata.SCOPE_SINGLETON); // mapMetadata.setId(id); // mapMetadata.setFactoryComponent(createRef(context, factoryMetadata.getId())); // mapMetadata.setFactoryMethod("getServiceMap"); // return mapMetadata; // } // private ComponentMetadata decorateCmProperties(ParserContext context, Element element, ComponentMetadata component) { // generateIdIfNeeded(context, ((MutableComponentMetadata) component)); // MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class); // metadata.setProcessor(true); // metadata.setId(getId(context, element)); // metadata.setRuntimeClass(CmProperties.class); // String persistentId = element.getAttribute(PERSISTENT_ID_ATTRIBUTE); // // if persistentId is "" the cm-properties element in nested in managed-service-factory // // and the configuration object will come from the factory. So we only really need to register // // ManagedService if the persistentId is not an empty string. // if (persistentId.length() > 0) { // metadata.setInitMethod("init"); // metadata.setDestroyMethod("destroy"); // } // metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); // metadata.addProperty("configAdmin", createConfigAdminProxy(context)); // metadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME)); // metadata.addProperty("persistentId", createValue(context, persistentId)); // if (element.hasAttribute(UPDATE_ATTRIBUTE)) { // metadata.addProperty("update", createValue(context, element.getAttribute(UPDATE_ATTRIBUTE))); // } // metadata.addProperty("serviceId", createIdRef(context, component.getId())); // context.getComponentDefinitionRegistry().registerComponentDefinition(metadata); // return component; // } // private ComponentMetadata decorateManagedProperties(ParserContext context, Element element, ComponentMetadata component) { // if (!(component instanceof MutableBeanMetadata)) { // throw new ComponentDefinitionException("Element " + MANAGED_PROPERTIES_ELEMENT + " must be used inside a element"); // } // generateIdIfNeeded(context, ((MutableBeanMetadata) component)); // MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class); // metadata.setProcessor(true); // metadata.setId(getId(context, element)); // metadata.setRuntimeClass(CmManagedProperties.class); // String persistentId = element.getAttribute(PERSISTENT_ID_ATTRIBUTE); // // if persistentId is "" the managed properties element in nested in managed-service-factory // // and the configuration object will come from the factory. So we only really need to register // // ManagedService if the persistentId is not an empty string. // if (persistentId.length() > 0) { // metadata.setInitMethod("init"); // metadata.setDestroyMethod("destroy"); // } // metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer")); // metadata.addProperty("configAdmin", createConfigAdminProxy(context)); // metadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME)); // metadata.addProperty("persistentId", createValue(context, persistentId)); // String updateStrategy = element.getAttribute(UPDATE_STRATEGY_ATTRIBUTE); // if (updateStrategy != null) { // metadata.addProperty("updateStrategy", createValue(context, updateStrategy)); // } // if (element.hasAttribute(UPDATE_METHOD_ATTRIBUTE)) { // metadata.addProperty("updateMethod", createValue(context, element.getAttribute(UPDATE_METHOD_ATTRIBUTE))); // } else if ("component-managed".equals(updateStrategy)) { // throw new ComponentDefinitionException(UPDATE_METHOD_ATTRIBUTE + " attribute must be set when " + UPDATE_STRATEGY_ATTRIBUTE + " is set to 'component-managed'"); // } // metadata.addProperty("beanName", createIdRef(context, component.getId())); // context.getComponentDefinitionRegistry().registerComponentDefinition(metadata); // return component; // } /** * Create a reference to the ConfigurationAdmin service if not already done * and add it to the registry. * * @param context the parser context * @return a metadata pointing to the config admin */ private Metadata createConfigAdminProxy(ParserContext context) { MutableBeanMetadata bean = context.createMetadata(MutableBeanMetadata.class); bean.setRuntimeClass(CmNamespaceHandler.class); bean.setFactoryMethod("getConfigAdmin"); bean.setActivation(MutableBeanMetadata.ACTIVATION_LAZY); bean.setScope(MutableBeanMetadata.SCOPE_PROTOTYPE); return bean; } // private void registerManagedObjectManager(ParserContext context, ComponentDefinitionRegistry registry) { // if (registry.getComponentDefinition(MANAGED_OBJECT_MANAGER_NAME) == null) { // MutableBeanMetadata beanMetadata = context.createMetadata(MutableBeanMetadata.class); // beanMetadata.setScope(BeanMetadata.SCOPE_SINGLETON); // beanMetadata.setId(MANAGED_OBJECT_MANAGER_NAME); // beanMetadata.setRuntimeClass(ManagedObjectManager.class); // registry.registerComponentDefinition(beanMetadata); // } // } private static ValueMetadata createValue(ParserContext context, String value) { return createValue(context, value, null); } private static ValueMetadata createValue(ParserContext context, String value, String type) { MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class); m.setStringValue(value); m.setType(type); return m; } private static RefMetadata createRef(ParserContext context, String value) { MutableRefMetadata m = context.createMetadata(MutableRefMetadata.class); m.setComponentId(value); return m; } private static ReferenceMetadata createReference(ParserContext context, String interfaceName) { MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class); m.setInterface(interfaceName); return m; } private static IdRefMetadata createIdRef(ParserContext context, String value) { MutableIdRefMetadata m = context.createMetadata(MutableIdRefMetadata.class); m.setComponentId(value); return m; } private static CollectionMetadata createList(ParserContext context, List list) { MutableCollectionMetadata m = context.createMetadata(MutableCollectionMetadata.class); m.setCollectionClass(List.class); m.setValueType(String.class.getName()); for (String v : list) { m.addValue(createValue(context, v, String.class.getName())); } return m; } private static String getTextValue(Element element) { StringBuffer value = new StringBuffer(); NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) { value.append(item.getNodeValue()); } } return value.toString(); } private static boolean nodeNameEquals(Node node, String name) { return (name.equals(node.getNodeName()) || name.equals(node.getLocalName())); } public static boolean isBlueprintNamespace(String ns) { return BLUEPRINT_NAMESPACE.equals(ns); } public String getId(ParserContext context, Element element) { if (element.hasAttribute(ID_ATTRIBUTE)) { return element.getAttribute(ID_ATTRIBUTE); } else { return generateId(context); } } public void generateIdIfNeeded(ParserContext context, MutableComponentMetadata metadata) { if (metadata.getId() == null) { metadata.setId(generateId(context)); } } private String generateId(ParserContext context) { String id; do { id = ".cm-" + ++idCounter; } while (context.getComponentDefinitionRegistry().containsComponentDefinition(id)); return id; } // private Parser getParser(ParserContext ctx) { // if (ctx instanceof ParserContextImpl) { // return ((ParserContextImpl) ctx).getParser(); // } // throw new RuntimeException("Unable to get parser"); // } public List parseInterfaceNames(Element element) { List interfaceNames = new ArrayList(); NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element e = (Element) node; if (nodeNameEquals(e, VALUE_ELEMENT)) { String v = getTextValue(e).trim(); if (interfaceNames.contains(v)) { throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice"); } interfaceNames.add(getTextValue(e)); } else { throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element"); } } } return interfaceNames; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/cm/JexlPropertyPlaceholder.java0000644000175000017500000000751111333220747033302 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.cm; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.aries.blueprint.compendium.cm.CmPropertyPlaceholder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version $Rev: 907189 $ $Date: 2010-02-06 09:01:43 +0100 (sam. 06 févr. 2010) $ */ public class JexlPropertyPlaceholder extends CmPropertyPlaceholder { private static final Logger LOGGER = LoggerFactory.getLogger(JexlPropertyPlaceholder.class); private transient JexlExpressionParser parser; @Override protected String processString(String str) { LOGGER.debug("Processing {} from configuration with pid {}", str, getPersistentId()); JexlExpressionParser parser = getParser(); try { return parser.evaluate(str).toString(); } catch (Exception e) { LOGGER.info("Could not evaluate expressions {} for {}", str, getPersistentId()); LOGGER.info("Exception:", e); } return str; } protected synchronized JexlExpressionParser getParser() { if (parser == null) { // try { parser = new JexlExpressionParser(toMap()); // } catch (IOException e) { // ignore // } } return parser; } private Map toMap() { return new ConfigMap(); // Map map = new HashMap(); // if (config != null) { // Dictionary properties = config.getProperties(); // for (Enumeration e = properties.keys(); e.hasMoreElements(); ) { // String key = e.nextElement(); // Object value = properties.get(key); // map.put(key, value); // } // } // return map; } private class ConfigMap implements Map { @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean containsKey(Object o) { return getProperty((String) o) != null; } @Override public boolean containsValue(Object o) { return false; } @Override public Object get(Object o) { return getProperty((String) o); } @Override public Object put(String s, Object o) { return null; } @Override public Object remove(Object o) { return null; } @Override public void putAll(Map map) { } @Override public void clear() { } @Override public Set keySet() { return null; } @Override public Collection values() { return null; } @Override public Set> entrySet() { return null; } } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/cm/JexlExpressionParser.java0000644000175000017500000001071111333220747032623 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.cm; import java.util.Map; import org.apache.commons.jexl2.JexlContext; import org.apache.commons.jexl2.JexlEngine; import org.apache.commons.jexl2.MapContext; import org.apache.commons.jexl2.UnifiedJEXL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version $Rev: 907189 $ $Date: 2010-02-06 09:01:43 +0100 (sam. 06 févr. 2010) $ */ public class JexlExpressionParser { private static final Logger log = LoggerFactory.getLogger(JexlExpressionParser.class); private final JexlEngine engine; private final UnifiedJEXL jexl; protected final JexlContext context; public JexlExpressionParser(final Map vars) { if (vars == null) { throw new IllegalArgumentException("vars"); } engine = new JexlEngine(); jexl = new UnifiedJEXL(engine); context = new MapContext(vars); log.trace("Using variables: {}", vars); } // private FlatResolver resolver = new FlatResolver(true); // // protected Expression createExpression(final String expression) throws Exception { // // assert expression != null; // // Expression expr = engine.createExpression(expression); // expr.addPreResolver(resolver); // // return expr; // } public Object evaluate(final String expression) throws Exception { if (expression == null) { throw new IllegalArgumentException("expression"); } log.trace("Evaluating expression: {}", expression); return jexl.parse(expression).evaluate(context); // Expression expr = createExpression(expression); // Object obj = expr.evaluate(context); // log.trace("Result: {}", obj); // // return obj; } // public String parse(final String input) { // if (input == null) { // throw new IllegalArgumentException("input"); // } // // log.trace("Parsing input: {}", input); // // StringBuilder buff = new StringBuilder(); // // int cur = 0; // int prefixLoc; // int suffixLoc; // // while (cur < input.length()) { // prefixLoc = input.indexOf("${", cur); // // if (prefixLoc < 0) { // break; // } // // suffixLoc = findBlockEnd(prefixLoc + 2, input); // if (suffixLoc < 0) { // throw new RuntimeException("Missing '}': " + input); // } // // String expr = input.substring(prefixLoc + 2, suffixLoc); // buff.append(input.substring(cur, prefixLoc)); // // try { // buff.append(evaluate(expr)); // } // catch (Exception e) { // throw new RuntimeException("Failed to evaluate: " + expr, e); // } // // cur = suffixLoc + 1; // } // // buff.append(input.substring(cur)); // // log.trace("Parsed result: {}", buff); // // return buff.toString(); // } // private int findBlockEnd(int pos, String input) { // int nested = 0; // while (pos < input.length()) { // char ch = input.charAt(pos); // if (ch == '{') { // nested++; // } else if (ch == '}') { // if (nested == 0) { // return pos; // } else { // nested--; // } // } // pos++; // } // return -1; // } // public String parse(final String input, final boolean trim) { // String output = parse(input); // if (trim && output != null) { // output = output.trim(); // } // // return output; // } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/0000755000175000017500000000000011610661037026705 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/0000755000175000017500000000000011610661037027646 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/MappingMetaData.java0000644000175000017500000002027711320711571033512 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.util.StringTokenizer; /** * A helper class which understands how to map an XML namespaced element to * Spring bean configurations * * @author James Strachan * @version $Id$ * @since 2.0 */ public class MappingMetaData { private Properties properties; private String packageName; /** * Creates an empty MappingMetaData for the specified Java package. * @param packageName the Java package to map */ public MappingMetaData(String packageName) { this.packageName = packageName; this.properties = new Properties(); } /** * Creates MappingMetaData using the specified properties which contan the package name. * @param properties */ public MappingMetaData(Properties properties) { this.properties = properties; } /** * Returns the Java class name for the given XML element name */ public String getClassName(String localName) { String className = properties.getProperty(localName); if (className == null && packageName != null) { if (packageName.length() > 0) { className = packageName + "." + localName; } else { className = localName; } } return className; } /** * Returns the property name for the given element and attribute name * * @param elementName the XML local name of the element * @param attributeName the XML local name of the attribute * @return the property name to use or null if the attribute is not a valid property */ public String getPropertyName(String elementName, String attributeName) { return properties.getProperty(elementName + ".alias." + attributeName, attributeName); } /** * Returns a valid property name if the childElementName maps to a nested list property * * @param elementName the owner element * @param childElementName is the child element name which maps to the nested list property * @return the property name if available or null if it is not applicable */ public String getNestedListProperty(String elementName, String childElementName) { return properties.getProperty(elementName + ".list." + childElementName); } /** * Returns a valid property name if the childElementName maps to a nested bean property * * @param elementName the owner element * @param childElementName is the child element name which maps to the nested bean property * @return the property name if available or null if it is not applicable */ public String getNestedProperty(String elementName, String childElementName) { return properties.getProperty(elementName + ".alias." + childElementName); } public boolean isDefaultConstructor(Constructor constructor) { String property = properties.getProperty(constructorToPropertyName(constructor) + ".default"); if (property != null) { return Boolean.valueOf(property).booleanValue(); } return false; } public boolean isDefaultFactoryMethod(Class beanClass, Method factoryMethod) { String property = properties.getProperty(methodToPropertyName(beanClass, factoryMethod) + ".default"); if (property != null) { return Boolean.valueOf(property).booleanValue(); } return false; } public String[] getParameterNames(Constructor constructor) { String property = properties.getProperty(constructorToPropertyName(constructor) + ".parameterNames"); if (property != null) { ArrayList names = Collections.list(new StringTokenizer(property, ", ")); return (String[]) names.toArray(new String[0]); } return null; } public String[] getParameterNames(Class beanClass, Method factoryMethod) { String property = properties.getProperty(methodToPropertyName(beanClass, factoryMethod) + ".parameterNames"); if (property != null) { ArrayList names = Collections.list(new StringTokenizer(property, ", ")); return (String[]) names.toArray(new String[0]); } return null; } public static String constructorToPropertyName(Constructor constructor) { StringBuffer buf = new StringBuffer(); buf.append(constructor.getName()).append("("); Class[] parameterTypes = constructor.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Class parameterType = parameterTypes[i]; buf.append(parameterType.getName()); if (i < parameterTypes.length - 1) { buf.append(","); } } buf.append(")"); return buf.toString(); } public static String methodToPropertyName(Class beanClass, Method method) { StringBuffer buf = new StringBuffer(); buf.append(beanClass.getName()).append("."); buf.append(method.getName()).append("("); Class[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Class parameterType = parameterTypes[i]; buf.append(parameterType.getName()); if (i < parameterTypes.length - 1) { buf.append(","); } } buf.append(")"); return buf.toString(); } public String getInitMethodName(String elementName) { return properties.getProperty(elementName + ".initMethod"); } public String getDestroyMethodName(String elementName) { return properties.getProperty(elementName + ".destroyMethod"); } public String getFactoryMethodName(String elementName) { return properties.getProperty(elementName + ".factoryMethod"); } public String getContentProperty(String elementName) { return properties.getProperty(elementName + ".contentProperty"); } public String getMapEntryName(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.entryName"); } public String getMapKeyName(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.keyName"); } public boolean isFlatMap(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.flat") != null; } public String getMapDupsMode(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.dups"); } public String getMapDefaultKey(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".map.defaultKey"); } public String getFlatCollectionProperty(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".flatCollection"); } public boolean isFlatProperty(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".flat") != null; } public String getPropertyEditor(String elementName, String property) { return properties.getProperty(elementName + "." + property + ".propertyEditor"); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/FileEditor.java0000644000175000017500000000237111320711571032537 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.beans.PropertyEditorSupport; import java.io.File; /** * Editor for java.io.File */ public class FileEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { setValue(new File(text)); } public String getAsText() { File value = (File) getValue(); return (value != null ? value.toString() : ""); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/DefaultProperty.java0000644000175000017500000000522711320711571033645 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; /** * DefaultProperty contains the default value assigned to a property with a specific name and type. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class DefaultProperty { private String name; private Class type; private String value; /** * Creates a new empty default property. This instance is unusable until the name, type and values are assigned. */ public DefaultProperty() { } /** * Creates new default property value for a property with the specified name and type. * @param name the name of the property * @param type the type of the property * @param value the default value */ public DefaultProperty(String name, Class type, String value) { this.name = name; this.type = type; this.value = value; } /** * Gets the property name. * @return the property name */ public String getName() { return name; } /** * Sets the property name. * @param name the property name */ public void setName(String name) { this.name = name; } /** * Gets the property type. * @return the property type */ public Class getType() { return type; } /** * Sets the property type. * @param type the property type */ public void setType(Class type) { this.type = type; } /** * Gets the default value. * @return the default value */ public String getValue() { return value; } /** * Sets the default value. * @param value the default value */ public void setValue(String value) { this.value = value; } /** * {@inheritDoc} */ public String toString() { return "[" + name + ", " + type + ", " + value + "]"; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/URIEditor.java0000644000175000017500000000270411320711571032317 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.beans.PropertyEditorSupport; import java.net.URI; import java.net.URISyntaxException; /** * Editor for java.net.URI */ public class URIEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(new URI(text)); } catch (URISyntaxException e) { throw new IllegalArgumentException( "Could not convert URI for " + text + ": " + e.getMessage()); } } public String getAsText() { URI value = (URI) getValue(); return (value != null ? value.toString() : ""); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/NamespaceHelper.java0000644000175000017500000000364711320711571033554 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; /** * A helper class for turning namespaces into META-INF/services URIs * * @version $Revision: 896187 $ */ public class NamespaceHelper { public static final String META_INF_PREFIX = "META-INF/services/org/apache/xbean/blueprint/"; /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri, String localName) { if (isEmpty(uri)) { return localName; } return createDiscoveryPathName(uri) + "/" + localName; } /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri) { // TODO proper encoding required // lets replace any dodgy characters return META_INF_PREFIX + uri.replaceAll("://", "/").replace(':', '/').replace(' ', '_'); } public static boolean isEmpty(String uri) { return uri == null || uri.length() == 0; } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/QNameHelper.java0000644000175000017500000001455211326105761032662 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.beans.PropertyDescriptor; import java.util.List; import javax.xml.namespace.QName; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.mutable.MutableBeanMetadata; import org.apache.aries.blueprint.mutable.MutableCollectionMetadata; import org.apache.aries.blueprint.mutable.MutableValueMetadata; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * * @version $Revision: 1.1 $ */ public class QNameHelper { private static final Log log = LogFactory.getLog(QNameHelper.class); public static Metadata createQNameMetadata(Element element, String qualifiedName, ParserContext parserContext) { MutableBeanMetadata beanMetadata = parserContext.createMetadata(MutableBeanMetadata.class); beanMetadata.setClassName(QName.class.getName()); int index = qualifiedName.indexOf(':'); if (index >= 0) { String prefix = qualifiedName.substring(0, index); String localName = qualifiedName.substring(index + 1); String uri = recursiveGetAttributeValue(element, "xmlns:" + prefix); beanMetadata.addArgument(valueMetadata(uri, parserContext), String.class.getName(), 0); beanMetadata.addArgument(valueMetadata(localName, parserContext), String.class.getName(), 1); beanMetadata.addArgument(valueMetadata(prefix, parserContext), String.class.getName(), 2); } else { String uri = recursiveGetAttributeValue(element, "xmlns"); if (uri != null) { beanMetadata.addArgument(valueMetadata(uri, parserContext), String.class.getName(), 0); beanMetadata.addArgument(valueMetadata(qualifiedName, parserContext), String.class.getName(), 1); } else { beanMetadata.addArgument(valueMetadata(qualifiedName, parserContext), String.class.getName(), 0); } } return beanMetadata; } private static Metadata valueMetadata(String stringValue, ParserContext parserContext) { MutableValueMetadata value = parserContext.createMetadata(MutableValueMetadata.class); value.setStringValue(stringValue); return value; } /** * Recursive method to find a given attribute value in an element or its parents (towards root of dom tree) * @param element element to start searching for attribute in * @param attributeName name of desired attribute * @return value of found attribute */ public static String recursiveGetAttributeValue(Element element, String attributeName) { String answer = null; try { answer = element.getAttribute(attributeName); } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element + ". Cause: " + e, e); } } if (answer == null || answer.length() == 0) { Node parentNode = element.getParentNode(); if (parentNode instanceof Element) { return recursiveGetAttributeValue((Element) parentNode, attributeName); } } return answer; } public static void coerceNamespaceAwarePropertyValues(MutableBeanMetadata bd, Element element, PropertyDescriptor descriptor, ParserContext parserContext) { // When the property is an indexed property, the getPropertyType can return null. if (descriptor.getPropertyType() == null) { return; } if (descriptor.getPropertyType().isAssignableFrom(QName.class)) { String name = descriptor.getName(); BeanProperty propertyValue = XBeanNamespaceHandler.propertyByName(name, bd); if (propertyValue != null) { Metadata value = propertyValue.getValue(); if (value instanceof ValueMetadata) { bd.removeProperty(propertyValue); Metadata valueMetadata = createQNameMetadata(element, ((ValueMetadata)value).getStringValue(), parserContext); bd.addProperty(name, valueMetadata); } //else?? } } else if (descriptor.getPropertyType().isAssignableFrom(QName[].class)) { String name = descriptor.getName(); BeanProperty propertyValue = XBeanNamespaceHandler.propertyByName(name, bd); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof CollectionMetadata) { List values = ((CollectionMetadata) value).getValues(); MutableCollectionMetadata newValue = parserContext.createMetadata(MutableCollectionMetadata.class); for (Metadata v : values) { if (v instanceof ValueMetadata) { newValue.addValue(createQNameMetadata(element, ((ValueMetadata)v).getStringValue(), parserContext)); } else { newValue.addValue(v); } } bd.removeProperty(propertyValue); bd.addProperty(name, newValue); } } } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/XBeanNamespaceHandler.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/XBeanNamespaceHandle0000644000175000017500000011312011347722046033522 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.context.impl; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.mutable.MutableBeanMetadata; import org.apache.aries.blueprint.mutable.MutableCollectionMetadata; import org.apache.aries.blueprint.mutable.MutableMapMetadata; import org.apache.aries.blueprint.mutable.MutableRefMetadata; import org.apache.aries.blueprint.mutable.MutableValueMetadata; import org.osgi.framework.Bundle; import org.osgi.service.blueprint.container.ComponentDefinitionException; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.MapEntry; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.NonNullMetadata; import org.osgi.service.blueprint.reflect.NullMetadata; import org.osgi.service.blueprint.reflect.RefMetadata; import org.osgi.service.blueprint.reflect.ReferenceMetadata; import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; /** * @version $Rev: 923807 $ $Date: 2010-03-16 16:30:46 +0100 (mar. 16 mars 2010) $ */ public class XBeanNamespaceHandler implements NamespaceHandler { private static final Logger LOGGER = LoggerFactory.getLogger(XBeanNamespaceHandler.class); public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0"; private static final String BEAN_REFERENCE_PREFIX = "#"; private static final String NULL_REFERENCE = "#null"; private final String namespace; private final URL schemaLocation; private final Set managedClasses; private final MappingMetaData mappingMetaData; private final Map managedClassesByName; private final Map> propertyEditors; private final NamedConstructorArgs namedConstructorArgs = new NamedConstructorArgs(); public XBeanNamespaceHandler(String namespace, URL schemaLocation, Set managedClasses, Map> propertyEditors, Properties properties) { this.namespace = namespace; this.schemaLocation = schemaLocation; this.managedClasses = managedClasses; managedClassesByName = mapClasses(managedClasses); this.propertyEditors = propertyEditors; this.mappingMetaData = new MappingMetaData(properties); } public XBeanNamespaceHandler(String namespace, String schemaLocation, Bundle bundle, String propertiesLocation) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { URL propertiesUrl = bundle.getResource(propertiesLocation); InputStream in = propertiesUrl.openStream(); Properties properties = new Properties(); try { properties.load(in); } finally { in.close(); } this.namespace = namespace; this.schemaLocation = bundle.getEntry(schemaLocation); this.managedClasses = managedClassesFromProperties(bundle, properties); managedClassesByName = mapClasses(managedClasses); propertyEditors = propertyEditorsFromProperties(bundle, properties); this.mappingMetaData = new MappingMetaData(properties); } public XBeanNamespaceHandler(String namespace, String schemaLocation, String propertiesLocation) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { ClassLoader cl = getClass().getClassLoader(); URL propertiesUrl = cl.getResource(propertiesLocation); if (propertiesUrl == null) { throw new IOException("Could not locate properties at " + propertiesLocation); } InputStream in = propertiesUrl.openStream(); Properties properties = new Properties(); try { properties.load(in); } finally { in.close(); } this.namespace = namespace; this.schemaLocation = cl.getResource(schemaLocation); this.managedClasses = managedClassesFromProperties(cl, properties); managedClassesByName = mapClasses(managedClasses); propertyEditors = propertyEditorsFromProperties(cl, properties); this.mappingMetaData = new MappingMetaData(properties); } private static Set managedClassesFromProperties(ClassLoader cl, Properties properties) { Set managedClasses = new HashSet(); Properties methods = new Properties(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); if (key.indexOf(".") < 0) { String className = (String) entry.getValue(); try { Class beanClass = cl.loadClass(className); managedClasses.add(beanClass); findAnnotations(key, beanClass, methods); } catch (NoClassDefFoundError e) { LOGGER.warn("Could not load class: {} due to {}", className, e.getMessage()); } catch (ClassNotFoundException e) { LOGGER.warn("Could not load class: {}", className); } } } properties.putAll(methods); return managedClasses; } private static Set managedClassesFromProperties(Bundle bundle, Properties properties) { Set managedClasses = new HashSet(); Properties methods = new Properties(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); if (key.indexOf(".") < 0) { String className = (String) entry.getValue(); try { Class beanClass = bundle.loadClass(className); managedClasses.add(beanClass); findAnnotations(key, beanClass, methods); } catch (NoClassDefFoundError e) { LOGGER.warn("Could not load class: {} due to {}", className, e.getMessage()); } catch (ClassNotFoundException e) { LOGGER.warn("Could not load class: {}", className); } } } properties.putAll(methods); return managedClasses; } private static void findAnnotations(String key, Class beanClass, Properties methods) { for (Method m : beanClass.getMethods()) { if (m.isAnnotationPresent(PostConstruct.class)) { methods.put(key + ".initMethod", m.getName()); } if (m.isAnnotationPresent(PreDestroy.class)) { methods.put(key + ".destroyMethod", m.getName()); } } } private Map> propertyEditorsFromProperties(Bundle bundle, Properties properties) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Map> propertyEditors = new HashMap>(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); if (key.endsWith(".propertyEditor")) { String className = (String) entry.getValue(); Class clazz = bundle.loadClass(className).asSubclass(PropertyEditor.class); propertyEditors.put(className, clazz); } } return propertyEditors; } private Map> propertyEditorsFromProperties(ClassLoader classLoader, Properties properties) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Map> propertyEditors = new HashMap>(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); if (key.endsWith(".propertyEditor")) { String className = (String) entry.getValue(); Class clazz = classLoader.loadClass(className).asSubclass(PropertyEditor.class); propertyEditors.put(className, clazz); } } return propertyEditors; } private Map mapClasses(Set managedClasses) { Map map = new HashMap(); for (Class clazz : managedClasses) { map.put(clazz.getName(), clazz); } return map; } public URL getSchemaLocation(String s) { if (namespace.equals(s)) { return schemaLocation; } return null; } public Set getManagedClasses() { return managedClasses; } public Metadata parse(Element element, ParserContext parserContext) { String beanTypeName = element.getLocalName(); String className = mappingMetaData.getClassName(beanTypeName); if (className == null) { throw new ComponentDefinitionException(beanTypeName + " not known to xbean namespace handler for " + namespace); } return parseInternal(element, parserContext, beanTypeName, className); } private Metadata parseInternal(Element element, ParserContext parserContext, String beanTypeName, String className) { MutableBeanMetadata beanMetaData = parserContext.createMetadata(MutableBeanMetadata.class); beanMetaData.setClassName(className); beanMetaData.setScope(BeanMetadata.SCOPE_SINGLETON); beanMetaData.setActivation(BeanMetadata.ACTIVATION_EAGER); beanMetaData.setRuntimeClass(managedClassesByName.get(className)); if (beanMetaData.getRuntimeClass() == null) { throw new ComponentDefinitionException("Unknown bean class: " + className); } if (element.hasAttributeNS(BLUEPRINT_NAMESPACE, "id")) { String id = element.getAttributeNS(BLUEPRINT_NAMESPACE, "id"); beanMetaData.setId(id); } else { beanMetaData.setId(parserContext.generateId()); } lifecycleMethods(beanTypeName, beanMetaData); attributeProperties(element, parserContext, beanTypeName, beanMetaData); contentProperty(beanMetaData, element, parserContext); nestedProperties(beanMetaData, element, beanTypeName, className, parserContext); //QName resolution coerceNamespaceAwarePropertyValues(beanMetaData, element, parserContext); namedConstructorArgs.processParameters(beanMetaData, mappingMetaData, parserContext); return beanMetaData; } private void lifecycleMethods(String beanTypeName, MutableBeanMetadata beanMetaData) { String initMethod = mappingMetaData.getInitMethodName(beanTypeName); if (initMethod != null) { beanMetaData.setInitMethod(initMethod); } String destroyMethod = mappingMetaData.getDestroyMethodName(beanTypeName); if (destroyMethod != null) { beanMetaData.setDestroyMethod(destroyMethod); } String factoryMethod = mappingMetaData.getFactoryMethodName(beanTypeName); if (factoryMethod != null) { beanMetaData.setFactoryMethod(factoryMethod); } } private void attributeProperties(Element element, ParserContext parserContext, String beanTypeName, MutableBeanMetadata beanMetaData) { NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); if (namespace.equals(attr.getNamespaceURI()) || attr.getNamespaceURI() == null) { String attrName = attr.getLocalName(); String value = attr.getValue().trim(); String propertyName = mappingMetaData.getPropertyName(beanTypeName, attrName); String propertyEditor = mappingMetaData.getPropertyEditor(beanTypeName, attrName); addProperty(propertyName, value, propertyEditor, beanMetaData, parserContext); } } } private void contentProperty(MutableBeanMetadata definition, Element element, ParserContext parserContext) { String name = mappingMetaData.getContentProperty(element.getLocalName()); String propertyEditor = mappingMetaData.getPropertyEditor(element.getLocalName(), name); if (name != null) { String value = getElementText(element).trim(); addProperty(name, value, propertyEditor, definition, parserContext); } else { ByteArrayInputStream in = new ByteArrayInputStream(getElementText(element).getBytes()); Properties properties = new Properties(); try { properties.load(in); } catch (IOException e) { return; } for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); addProperty(key, value, propertyEditor, definition, parserContext); } } } private void addProperty(String name, String value, String propertyEditor, MutableBeanMetadata definition, ParserContext parserContext) { Metadata m = getValue(value, propertyEditor, parserContext); definition.addProperty(name, m); } private void nestedProperties(MutableBeanMetadata beanMetadata, Element element, String beanTypeName, String className, ParserContext parserContext) { NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Element) { Element child = (Element) node; String childName = child.getLocalName(); String namespace = child.getNamespaceURI(); if (!this.namespace.equals(namespace)) { BeanProperty prop = parserContext.parseElement(BeanProperty.class, beanMetadata, child); beanMetadata.addProperty(prop); continue; } Metadata childMetadata = null; PropertyDescriptor pd = getPropertyDescriptor(mappingMetaData.getClassName(beanTypeName), childName); Class propertyType = pd == null ? null : pd.getPropertyType(); String propertyName = mappingMetaData.getNestedListProperty(beanTypeName, childName); //explicit list if (propertyName != null || isCollectionType(propertyType)) { propertyName = propertyName == null ? childName : propertyName; childMetadata = parserContext.parseElement(CollectionMetadata.class, beanMetadata, child); } else if ((propertyName = mappingMetaData.getFlatCollectionProperty(beanTypeName, childName)) != null) { //flat collection Metadata elementMetadata = parse(child, parserContext); BeanProperty list = propertyByName(propertyName, beanMetadata); MutableCollectionMetadata listMeta; if (list == null) { listMeta = parserContext.createMetadata(MutableCollectionMetadata.class); childMetadata = listMeta; } else { listMeta = (MutableCollectionMetadata) list.getValue(); } listMeta.addValue(elementMetadata); } else if ((propertyName = mappingMetaData.getNestedProperty(beanTypeName, childName)) != null) { // lets find the first child bean that parses fine childMetadata = parseChildExtensionBean(child, beanMetadata, parserContext); } else if (mappingMetaData.isFlatProperty(beanTypeName, childName)) { propertyName = childName; String flatClassName = getPropertyDescriptor(mappingMetaData.getClassName(beanTypeName), childName).getPropertyType().getName(); childMetadata = parseInternal(child, parserContext, childName, flatClassName); } else { childMetadata = tryParseNestedPropertyViaIntrospection(beanMetadata, className, child, parserContext); propertyName = childName; } if (childMetadata == null) { String text = getElementText(child); if (text != null) { MutableValueMetadata m = parserContext.createMetadata(MutableValueMetadata.class); m.setStringValue(text.trim()); childMetadata = m; } // propertyName = mappingMetaData.getPropertyName(beanTypeName, childName); // NodeList childNodes = child.getChildNodes(); // StringBuilder buf = new StringBuilder(); // for (int j = 0; j < childNodes.getLength(); j++) { // Node childNode = childNodes.item(j); // if (childNode instanceof Element) { // Element childElement = (Element) childNode; // if (namespace.equals(childElement.getNamespaceURI())) { // childMetadata = parse(childElement, parserContext); // } else { // try { // childMetadata = parserContext.parseElement(BeanMetadata.class, beanMetaData, childElement); // } catch (Exception e) { // childMetadata = parserContext.parseElement(ValueMetadata.class, beanMetaData, childElement); // } // } // // break; // } else if (childNode instanceof Text) { // String value = childNode.getNodeValue(); // buf.append(value); // } // } // if (childMetadata == null) { // MutableValueMetadata m = parserContext.createMetadata(MutableValueMetadata.class); // m.setStringValue(buf.toString().trim()); // childMetadata = m; // } } if (childMetadata != null) { beanMetadata.addProperty(propertyName, childMetadata); } } } } private Metadata parseChildExtensionBean(Element child, MutableBeanMetadata beanMetadata, ParserContext parserContext) { NodeList nl = child.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element childElement = (Element) node; String uri = childElement.getNamespaceURI(); String localName = childElement.getLocalName(); Metadata value = parserContext.parseElement(Metadata.class, beanMetadata, childElement); if (value != null) { return value; } //TODO ARIES-111 // if (uri == null || // uri.equals(BLUEPRINT_NAMESPACE)) { // if ("bean".equals(localName)) { // return parserContext.parseElement(BeanMetadata.class, beanMetadata, childElement); // } else { // return parserContext.parseElement(ValueMetadata.class, beanMetadata, childElement); // } // } else { // Metadata value = parse(childElement, parserContext); // if (value != null) { // return value; // } // } } } return null; } private Metadata tryParseNestedPropertyViaIntrospection(MutableBeanMetadata beanMetadata, String className, Element element, ParserContext parserContext) { String localName = element.getLocalName(); PropertyDescriptor descriptor = getPropertyDescriptor(className, localName); if (descriptor != null) { return parseNestedPropertyViaIntrospection(beanMetadata, element, descriptor.getName(), descriptor.getPropertyType(), parserContext); } else { return parseNestedPropertyViaIntrospection(beanMetadata, element, localName, Object.class, parserContext); } } private Metadata parseNestedPropertyViaIntrospection(MutableBeanMetadata beanMetadata, Element element, String propertyName, Class propertyType, ParserContext parserContext) { if (isMap(propertyType)) { return parseCustomMapElement(beanMetadata, element, propertyName, parserContext); } else if (isCollection(propertyType)) { return parserContext.parseElement(CollectionMetadata.class, beanMetadata, element); } else { return parseChildExtensionBean(element, beanMetadata, parserContext); } } private boolean isMap(Class type) { return Map.class.isAssignableFrom(type); } /** * Returns true if the given type is a collection type or an array */ private boolean isCollection(Class type) { return type.isArray() || Collection.class.isAssignableFrom(type); } protected String getLocalName(Element element) { String localName = element.getLocalName(); if (localName == null) { localName = element.getNodeName(); } return localName; } protected Metadata parseCustomMapElement(MutableBeanMetadata beanMetadata, Element element, String name, ParserContext parserContext) { MutableMapMetadata map = parserContext.createMetadata(MutableMapMetadata.class); Element parent = (Element) element.getParentNode(); String entryName = mappingMetaData.getMapEntryName(getLocalName(parent), name); String keyName = mappingMetaData.getMapKeyName(getLocalName(parent), name); String dups = mappingMetaData.getMapDupsMode(getLocalName(parent), name); boolean flat = mappingMetaData.isFlatMap(getLocalName(parent), name); String defaultKey = mappingMetaData.getMapDefaultKey(getLocalName(parent), name); if (entryName == null) entryName = "property"; if (keyName == null) keyName = "key"; if (dups == null) dups = "replace"; // TODO : support further customizations //String valueName = "value"; //boolean keyIsAttr = true; //boolean valueIsAttr = false; NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element childElement = (Element) node; String localName = childElement.getLocalName(); String uri = childElement.getNamespaceURI(); if (localName == null || localName.equals("xmlns") || localName.startsWith("xmlns:")) { continue; } // we could use namespaced attributes to differentiate real spring // attributes from namespace-specific attributes if (!flat && !isEmpty(uri) && localName.equals(entryName)) { String key = childElement.getAttributeNS(uri, keyName); if (key == null || key.length() == 0) { key = defaultKey; } if (key == null) { throw new RuntimeException("No key defined for map " + entryName); } NonNullMetadata keyValue = (NonNullMetadata) getValue(key, mappingMetaData.getPropertyEditor(localName, key), parserContext); Element valueElement = getFirstChildElement(childElement); Metadata value; if (valueElement != null) { value = parserContext.parseElement(Metadata.class, beanMetadata, valueElement); // String valueElUri = valueElement.getNamespaceURI(); // String valueElLocalName = valueElement.getLocalName(); // if (valueElUri == null || // valueElUri.equals(BLUEPRINT_NAMESPACE)) { // if ("bean".equals(valueElLocalName)) { // value = parserContext.parseElement(BeanMetadata.class, beanMetadata, valueElement); // } else { // value = parserContext.parseElement(BeanProperty.class, beanMetadata, valueElement).getValue(); // } // } else { // value = parserContext.parseElement(ValueMetadata.class, beanMetadata, valueElement); // } } else { value = getValue(getElementText(childElement), mappingMetaData.getPropertyEditor(localName, key), parserContext); } addValueToMap(map, keyValue, value, dups, parserContext); } else if (flat && !isEmpty(uri)) { String key = childElement.getAttributeNS(uri, keyName); if (key == null || key.length() == 0) { key = defaultKey; } if (key == null) { throw new RuntimeException("No key defined for map entry " + entryName); } NonNullMetadata keyValue = (NonNullMetadata) getValue(key, mappingMetaData.getPropertyEditor(localName, key), parserContext); childElement = cloneElement(childElement); childElement.removeAttributeNS(uri, keyName); Metadata bdh = parse(childElement, parserContext); addValueToMap(map, keyValue, bdh, dups, parserContext); } } } return map; } /** * Creates a clone of the element and its attribute (though not its content) */ protected Element cloneElement(Element element) { Element answer = element.getOwnerDocument().createElementNS(element.getNamespaceURI(), element.getNodeName()); NamedNodeMap attributes = element.getAttributes(); for (int i = 0, size = attributes.getLength(); i < size; i++) { Attr attribute = (Attr) attributes.item(i); String uri = attribute.getNamespaceURI(); answer.setAttributeNS(uri, attribute.getName(), attribute.getNodeValue()); } return answer; } protected void addValueToMap(MutableMapMetadata map, NonNullMetadata keyValue, Metadata value, String dups, ParserContext parserContext) { if (hasKey(map, keyValue)) { if ("discard".equalsIgnoreCase(dups)) { // Do nothing } else if ("replace".equalsIgnoreCase(dups)) { map.addEntry(keyValue, value); } else if ("allow".equalsIgnoreCase(dups)) { MutableCollectionMetadata l = parserContext.createMetadata(MutableCollectionMetadata.class); l.addValue(get(map, keyValue)); l.addValue(value); map.addEntry(keyValue, l); } else if ("always".equalsIgnoreCase(dups)) { MutableCollectionMetadata l = (MutableCollectionMetadata) get(map, keyValue); l.addValue(value); } } else { if ("always".equalsIgnoreCase(dups)) { MutableCollectionMetadata l = (MutableCollectionMetadata) get(map, keyValue); if (l == null) { l = parserContext.createMetadata(MutableCollectionMetadata.class); map.addEntry(keyValue, l); } l.addValue(value); } else { map.addEntry(keyValue, value); } } } private Metadata get(MutableMapMetadata map, NonNullMetadata keyValue) { for (MapEntry entry : map.getEntries()) { if (equals(entry.getKey(), keyValue)) { return entry.getValue(); } } return null; } private boolean equals(NonNullMetadata key1, NonNullMetadata key2) { if (key1 == key2) return true; if (key1.getClass() != key2.getClass()) return false; if (key1 instanceof RefMetadata) return ((RefMetadata) key1).getComponentId().equals(((RefMetadata) key2).getComponentId()); if (key1 instanceof ReferenceMetadata) { if (((ReferenceMetadata) key1).getTimeout() != ((ReferenceMetadata) key2).getTimeout()) return false; } if (key1 instanceof ServiceReferenceMetadata) { ServiceReferenceMetadata sr1 = (ServiceReferenceMetadata) key1; ServiceReferenceMetadata sr2 = (ServiceReferenceMetadata) key2; return sr1.getAvailability() == sr2.getAvailability() && sr1.getInterface().equals(sr2.getInterface()) && sr1.getComponentName().equals(sr2.getComponentName()) && sr1.getFilter().equals(sr2.getFilter()) && sr1.getReferenceListeners().equals(sr2.getReferenceListeners()) && sr1.getId().equals(sr2.getId()) && sr1.getActivation() == sr2.getActivation() && sr1.getDependsOn().equals(sr2.getDependsOn()); } if (key1 instanceof ValueMetadata) { ValueMetadata v1 = (ValueMetadata) key1; ValueMetadata v2 = (ValueMetadata) key2; if (v1.getStringValue() != null ? v1.getStringValue().equals(v2.getStringValue()) : v2.getStringValue() == null && v1.getType() != null ? v1.getType().equals(v2.getType()) : v2.getType() == null) { return true; } } return false; } private boolean hasKey(MutableMapMetadata map, NonNullMetadata keyValue) { return get(map, keyValue) != null; } protected boolean isEmpty(String uri) { return uri == null || uri.length() == 0; } protected Metadata getValue(String value, String propertyEditorName, ParserContext parserContext) { if (value == null) return null; // // If value is #null then we are explicitly setting the value null instead of an empty string // if (NULL_REFERENCE.equals(value)) { return parserContext.createMetadata(NullMetadata.class); } // // If value starts with # then we have a ref // if (value.startsWith(BEAN_REFERENCE_PREFIX)) { // strip off the # value = value.substring(BEAN_REFERENCE_PREFIX.length()); // if the new value starts with a #, then we had an excaped value (e.g. ##value) if (!value.startsWith(BEAN_REFERENCE_PREFIX)) { MutableRefMetadata ref = parserContext.createMetadata(MutableRefMetadata.class); ref.setComponentId(value); return ref; } } // if( propertyEditor!=null ) { // PropertyEditor p = createPropertyEditor(propertyEditor); // // RootBeanDefinition def = new RootBeanDefinition(); // def.setBeanClass(PropertyEditorFactory.class); // def.getPropertyValues().addPropertyValue("propertyEditor", p); // def.getPropertyValues().addPropertyValue("value", value); // // return def; // } // // Neither null nor a reference // MutableValueMetadata metadata = parserContext.createMetadata(MutableValueMetadata.class); if (propertyEditorName != null) { PropertyEditor propertyEditor; try { propertyEditor = propertyEditors.get(propertyEditorName).newInstance(); } catch (InstantiationException e) { throw new ComponentDefinitionException("Could not create a " + propertyEditorName + " to convert value " + value + " for namespace " + namespace); } catch (IllegalAccessException e) { throw new ComponentDefinitionException("Could not create a " + propertyEditorName + " to convert value " + value + " for namespace " + namespace); } propertyEditor.setAsText(value); value = propertyEditor.getAsText(); } metadata.setStringValue(value); return metadata; } protected Element getFirstChildElement(Element element) { NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { return (Element) node; } } return null; } private boolean isCollectionType(Class propertyType) { if (propertyType == null) { return false; } if (Collection.class.isAssignableFrom(propertyType)) { return true; } if (propertyType.isArray()) { return true; } return false; } public static BeanProperty propertyByName(String name, BeanMetadata meta) { for (BeanProperty prop : meta.getProperties()) { if (name.equals(prop.getName())) { return prop; } } return null; } public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) { return componentMetadata; } private void coerceNamespaceAwarePropertyValues(MutableBeanMetadata bd, Element element, ParserContext parserContext) { // lets check for any QName types BeanInfo beanInfo = getBeanInfo(getClass(bd.getClassName())); if (beanInfo != null) { PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { QNameHelper.coerceNamespaceAwarePropertyValues(bd, element, descriptor, parserContext); } } } private PropertyDescriptor getPropertyDescriptor(String className, String localName) { Class clazz = getClass(className); return getPropertyDescriptor(clazz, localName); } private PropertyDescriptor getPropertyDescriptor(Class clazz, String localName) { BeanInfo beanInfo = getBeanInfo(clazz); if (beanInfo != null) { PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { PropertyDescriptor descriptor = descriptors[i]; String name = descriptor.getName(); if (name.equals(localName)) { return descriptor; } } } return null; } private Class getClass(String className) throws ComponentDefinitionException { if (className == null) { return null; } Class type = managedClassesByName.get(className); if (type == null) { throw new ComponentDefinitionException("Unknown type: " + className); } return type; } private BeanInfo getBeanInfo(Class type) { if (type == null) { return null; } try { return Introspector.getBeanInfo(type); } catch (IntrospectionException e) { throw new ComponentDefinitionException("Failed to introspect type: " + type.getName() + ". Reason: " + e, e); } } private String getElementText(Element element) { StringBuilder buffer = new StringBuilder(); NodeList nodeList = element.getChildNodes(); for (int i = 0, size = nodeList.getLength(); i < size; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) { buffer.append(node.getNodeValue()); } } return buffer.toString(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/QNameNamespaceHandler.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/QNameNamespaceHandle0000644000175000017500000000510311322176276033530 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.context.impl; import java.net.URL; import java.util.Collections; import java.util.Set; import javax.xml.namespace.QName; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @version $Rev: 897559 $ $Date: 2010-01-09 23:01:34 +0100 (sam. 09 janv. 2010) $ */ public class QNameNamespaceHandler implements NamespaceHandler { private static final Set MANAGED_CLASS = Collections.singleton(QName.class); private final QNameHelper qNameHelper = new QNameHelper(); public URL getSchemaLocation(String namespace) { return null; } public Set getManagedClasses() { return MANAGED_CLASS; } public Metadata parse(Element element, ParserContext context) { if ("qname".equals(element.getLocalName())) { return QNameHelper.createQNameMetadata(element, getElementText(element), context); } return null; } public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) { return component; } private String getElementText(Element element) { StringBuilder buffer = new StringBuilder(); NodeList nodeList = element.getChildNodes(); for (int i = 0, size = nodeList.getLength(); i < size; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) { buffer.append(node.getNodeValue()); } } return buffer.toString(); } } xbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/DateEditor.java0000644000175000017500000000307411320711571032536 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.beans.PropertyEditorSupport; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; /** * Editor for java.util.Date */ public class DateEditor extends PropertyEditorSupport { private DateFormat dateFormat = DateFormat.getInstance(); public void setAsText(String text) throws IllegalArgumentException { try { setValue(dateFormat.parse(text)); } catch (ParseException e) { throw new IllegalArgumentException( "Could not convert Date for " + text + ": " + e.getMessage()); } } public String getAsText() { Date value = (Date) getValue(); return (value != null ? dateFormat.format(value) : ""); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/ObjectNameEditor.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/ObjectNameEditor.jav0000644000175000017500000000304211320711571033522 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import java.beans.PropertyEditorSupport; /** * Editor for java.net.URI */ public class ObjectNameEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { try { setValue(new ObjectName(text)); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("Could not convert ObjectName for " + text + ": " + e.getMessage()); } } public String getAsText() { ObjectName value = (ObjectName) getValue(); return (value != null ? value.toString() : ""); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/NamedConstructorArgs.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/NamedConstructorArgs0000644000175000017500000003453411320711571033706 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.mutable.MutableBeanMetadata; import org.apache.aries.blueprint.mutable.MutableValueMetadata; import org.osgi.service.blueprint.container.ComponentDefinitionException; import org.osgi.service.blueprint.reflect.BeanProperty; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * NamedConstructorArgs is a BeanFactoryPostProcessor that converts property declarations into indexed constructor args * based on the the constructor parameter names annotation. This process first selects a constructor and then fills in * the constructor arguments from the properties defined in the bean definition. If a property is not defined in the * bean definition, first the defaultValues map is checked for a value and if a value is not present a Java default * value is provided for the constructor argument (e.g. numbers are assigned 0 and objects are assigned null). * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class NamedConstructorArgs { private Map defaultValues = new HashMap(); /** * Gets the default values that are assigned to constructor arguments without a defined value. * * @return the default values that are assigned to constructor arguments without a defined value */ public List getDefaultValues() { List values = new LinkedList(); for (Map.Entry entry : defaultValues.entrySet()) { PropertyKey key = entry.getKey(); String value = entry.getValue(); values.add(new DefaultProperty(key.name, key.type, value)); } return values; } /** * Sets the default values that are assigned to constructor arguments without a defined value. * * @param defaultValues the values that are assigned to constructor arguments without a defined value */ public void setDefaultValues(List defaultValues) { this.defaultValues.clear(); for (DefaultProperty defaultValue : defaultValues) { addDefaultValue(defaultValue); } } /** * Adds a default value for a property with the specified name and type. * * @param name the name of the property * @param type the type of the property * @param value the default value for a property with the specified name and type */ public void addDefaultValue(String name, Class type, String value) { defaultValues.put(new PropertyKey(name, type), value); } /** * Adds a defautl value for a property. * * @param defaultProperty the default property information */ private void addDefaultValue(DefaultProperty defaultProperty) { defaultValues.put(new PropertyKey(defaultProperty.getName(), defaultProperty.getType()), defaultProperty.getValue()); } public void processParameters(MutableBeanMetadata beanMetadata, MappingMetaData metadata, ParserContext parserContext) { // if this bean already has constructor arguments defined, don't mess with them if (beanMetadata.getArguments().size() > 0) { return; } // try to get a list of constructor arg names to use ConstructionInfo constructionInfo = selectConstructionMethod(beanMetadata, metadata); if (constructionInfo == null) { return; } // remove each named property and add an indexed constructor arg List beanProperties = beanMetadata.getProperties(); LinkedHashMap propMap = new LinkedHashMap(); for (BeanProperty beanProperty : beanProperties) { propMap.put(beanProperty.getName(), beanProperty); } String[] parameterNames = constructionInfo.parameterNames; Class[] parameterTypes = constructionInfo.parameterTypes; for (int i = 0; i < parameterNames.length; i++) { String parameterName = parameterNames[i]; Class parameterType = parameterTypes[i]; BeanProperty beanProperty = propMap.get(parameterName); if (beanProperty != null) { propMap.remove(parameterName); beanMetadata.removeProperty(beanProperty); beanMetadata.addArgument(beanProperty.getValue(), parameterType.getName(), i); } else { String defaultValue = defaultValues.get(new PropertyKey(parameterName, parameterType)); if (defaultValue == null) { defaultValue = DEFAULT_VALUE.get(parameterType); } // if (defaultValue instanceof FactoryBean) { // try { // defaultValue = ((FactoryBean)defaultValue).getObject(); // } catch (Exception e) { // throw new FatalBeanException("Unable to get object value from bean factory", e); // } // } MutableValueMetadata valueMetadata = parserContext.createMetadata(MutableValueMetadata.class); valueMetadata.setStringValue(defaultValue); valueMetadata.setType(parameterType.getName()); beanMetadata.addArgument(valueMetadata, parameterType.getName(), i); } } // todo set any usable default values on the bean definition } private ConstructionInfo selectConstructionMethod(MutableBeanMetadata beanMetadata, MappingMetaData metadata) { Class beanClass = beanMetadata.getRuntimeClass(); // get a set containing the names of the defined properties Set definedProperties = new HashSet(); List values = beanMetadata.getProperties(); for (BeanProperty beanProperty : values) { definedProperties.add(beanProperty.getName()); } // first check for a factory method if (beanMetadata.getFactoryMethod() != null) { return selectFactory(beanClass, beanMetadata, metadata, definedProperties); } else { return selectConstructor(beanClass, metadata, definedProperties); } } private ConstructionInfo selectFactory(Class beanClass, MutableBeanMetadata beanMetadata, MappingMetaData metadata, Set definedProperties) { String factoryMethodName = beanMetadata.getFactoryMethod(); // get the factory methods sorted by longest arg length first Method[] methods = beanClass.getMethods(); List factoryMethods = new ArrayList(methods.length); for (Method method : methods) { if (method.getName().equals(factoryMethodName)) { factoryMethods.add(method); } } Collections.sort(factoryMethods, new MethodArgLengthComparator()); // if a factory method has been annotated as the default constructor we always use that constructor for (Method factoryMethod : factoryMethods) { if (metadata.isDefaultFactoryMethod(beanClass, factoryMethod)) { return new ConstructionInfo(beanClass, factoryMethod, metadata); } } // try to find a constructor for which we have all of the properties defined for (Method factoryMethod : factoryMethods) { ConstructionInfo constructionInfo = new ConstructionInfo(beanClass, factoryMethod, metadata); if (isUsableConstructor(constructionInfo, definedProperties)) { return constructionInfo; } } return null; } private ConstructionInfo selectConstructor(Class beanClass, MappingMetaData metadata, Set definedProperties) { // get the constructors sorted by longest arg length first List constructors = new ArrayList(Arrays.asList(beanClass.getConstructors())); Collections.sort(constructors, new ConstructorArgLengthComparator()); // if a constructor has been annotated as the default constructor we always use that constructor for (Constructor constructor : constructors) { if (metadata.isDefaultConstructor(constructor)) { return new ConstructionInfo(constructor, metadata); } } // try to find a constructor for which we have all of the properties defined for (Constructor constructor : constructors) { ConstructionInfo constructionInfo = new ConstructionInfo(constructor, metadata); if (isUsableConstructor(constructionInfo, definedProperties)) { return constructionInfo; } } return null; } private boolean isUsableConstructor(ConstructionInfo constructionInfo, Set definedProperties) { // if we don't have parameter names this is not the constructor we are looking for String[] parameterNames = constructionInfo.parameterNames; if (parameterNames == null) { return false; } Class[] parameterTypes = constructionInfo.parameterTypes; for (int i = 0; i < parameterNames.length; i++) { String parameterName = parameterNames[i]; Class parameterType = parameterTypes[i]; // can we satify this property using a defined property or default property if (!definedProperties.contains(parameterName) && !defaultValues.containsKey(new PropertyKey(parameterName, parameterType))) { return false; } } return true; } private class ConstructionInfo { private final Class[] parameterTypes; private final String[] parameterNames; public ConstructionInfo(Constructor constructor, MappingMetaData metadata) { this.parameterTypes = constructor.getParameterTypes(); String[] names = metadata.getParameterNames(constructor); // verify that we have enough parameter names int expectedParameterCount = parameterTypes.length; if (names != null && names.length != expectedParameterCount) { throw new ComponentDefinitionException("Excpected " + expectedParameterCount + " parameter names for constructor but only got " + names.length + ": " + constructor.toString()); } if (expectedParameterCount == 0) { names = new String[0]; } this.parameterNames = names; } public ConstructionInfo(Class beanClass, Method factoryMethod, MappingMetaData metadata) { this.parameterTypes = factoryMethod.getParameterTypes(); String[] names = metadata.getParameterNames(beanClass, factoryMethod); // verify that we have enough parameter names int expectedParameterCount = parameterTypes.length; if (names != null && names.length != expectedParameterCount) { throw new ComponentDefinitionException("Excpected " + expectedParameterCount + " parameter names for factory method but only got " + names.length + ": " + factoryMethod.toString()); } if (expectedParameterCount == 0) { names = new String[0]; } this.parameterNames = names; } } private static class MethodArgLengthComparator implements Comparator { public int compare(Method o1, Method o2) { return getArgLength(o2) - getArgLength(o1); } private int getArgLength(Method object) { return object.getParameterTypes().length; } } private static class ConstructorArgLengthComparator implements Comparator { public int compare(Constructor o1, Constructor o2) { return getArgLength(o2) - getArgLength(o1); } private int getArgLength(Constructor object) { return object.getParameterTypes().length; } } private static class PropertyKey { private final String name; private final Class type; public PropertyKey(String name, Class type) { this.name = name; this.type = type; } public boolean equals(Object object) { if (!(object instanceof PropertyKey)) { return false; } PropertyKey defaultProperty = (PropertyKey) object; return name.equals(defaultProperty.name) && type.equals(type); } public int hashCode() { int result = 17; result = 37 * result + name.hashCode(); result = 37 * result + type.hashCode(); return result; } public String toString() { return "[" + name + " " + type + "]"; } } private static final Map DEFAULT_VALUE; static { Map temp = new HashMap(); temp.put(Boolean.TYPE, Boolean.FALSE.toString()); temp.put(Byte.TYPE, "0B"); temp.put(Character.TYPE, "\\u000"); temp.put(Short.TYPE, "0S"); temp.put(Integer.TYPE, "0"); temp.put(Long.TYPE, "0L"); temp.put(Float.TYPE, "0F"); temp.put(Double.TYPE, "0D"); DEFAULT_VALUE = Collections.unmodifiableMap(temp); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/PropertyEditorHelper.javaxbean-3.7/xbean-blueprint/src/main/java/org/apache/xbean/blueprint/context/impl/PropertyEditorHelper0000644000175000017500000000625011320711571033724 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.beans.PropertyEditorManager; /** * A helper method to register some custom editors * * @version $Revision: 896187 $ */ public class PropertyEditorHelper { private static final Log log = LogFactory.getLog(PropertyEditorHelper.class); public static void registerCustomEditors() { registerEditor("java.io.File", "org.apache.xbean.blueprint.context.impl.FileEditor"); registerEditor("java.net.URI", "org.apache.xbean.blueprint.context.impl.URIEditor"); registerEditor("java.util.Date", "org.apache.xbean.blueprint.context.impl.DateEditor"); registerEditor("javax.management.ObjectName", "org.apache.xbean.blueprint.context.impl.ObjectNameEditor"); } protected static void registerEditor(String typeName, String editorName) { Class type = loadClass(typeName); Class editor = loadClass(editorName); if (type != null && editor != null) { PropertyEditorManager.registerEditor(type, editor); } } public static void unregisterCustomEditors() { unregisterEditor("java.io.File"); unregisterEditor("java.net.URI"); unregisterEditor("java.util.Date"); unregisterEditor("javax.management.ObjectName"); } protected static void unregisterEditor(String typeName) { Class type = loadClass(typeName); if (type != null) { PropertyEditorManager.registerEditor(type, null); } } public static Class loadClass(String name) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { try { return contextClassLoader.loadClass(name); } catch (ClassNotFoundException e) { } catch (NoClassDefFoundError e) { } } try { return PropertyEditorHelper.class.getClassLoader().loadClass(name); } catch (ClassNotFoundException e) { log.debug("Could not find class: " + name + " on the classpath"); return null; } catch (NoClassDefFoundError e) { log.debug("Could not load class: " + name + " on the classpath. " + e.getMessage()); return null; } } } xbean-3.7/xbean-blueprint/src/test/0000755000175000017500000000000011610661037017222 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/0000755000175000017500000000000011610661037021234 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/0000755000175000017500000000000011610661037022374 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/0000755000175000017500000000000011610661037024217 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/0000755000175000017500000000000011610661037025006 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/0000755000175000017500000000000011610661037026227 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/0000755000175000017500000000000011610661037027324 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/0000755000175000017500000000000011610661037031330 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/0000755000175000017500000000000011610661037032307 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/xbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000755000175000017500000000000011610661037033325 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/xbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000755000175000017500000000000011610661037033325 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/componentxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000644000175000017500000000164111320711571033326 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # container=org.apache.xbean.spring.example.ContainerBean inner=org.apache.xbean.spring.example.InnerBean ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/soupxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000644000175000017500000000244611321003657033332 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in #TODO blueprint support this?? #package = org.apache.xbean.blueprint.example # Mapping of XML Element localNames to classes soup = org.apache.xbean.blueprint.example.SoupService # Mapping of life-cycle methods soup.initMethod = make soup.destroyMethod = eat soup.factoryMethod = newSoup # Mapping of constructor argument names org.apache.xbean.blueprint.example.SoupService.newSoup(java.lang.String).parameterNames = type # END SNIPPET: config ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/pizza-simplexbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000644000175000017500000000211311320711571033321 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes pizza = org.apache.xbean.spring.example.PizzaService restaurant = org.apache.xbean.spring.example.RestaurantService # END SNIPPET: config ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/restaurantxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000644000175000017500000000241011320711571033321 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes pizza = org.apache.xbean.spring.example.PizzaService restaurant = org.apache.xbean.spring.example.RestaurantService # Mapping of XML Attributes to property names pizza.alias.myTopping = topping # Mapping of nested bean properties restaurant.dinnerMenu.list = dinnerMenu restaurant.favourite = favourite # END SNIPPET: config ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/saladxbean-3.7/xbean-blueprint/src/test/resources/META-INF/services/org/apache/xbean/blueprint/http/xbean0000644000175000017500000000240311320711571033323 0ustar drazzibdrazzib# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # START SNIPPET: config # the default package that POJOs are in package = org.apache.xbean.spring.example # Mapping of XML Element localNames to classes salad = org.apache.xbean.spring.example.SaladService # Mapping of XML Attributes to property names salad.alias.addCroutons = crouton # Mapping of constructor argument names org.apache.xbean.spring.example.SaladService(java.lang.String,java.lang.String,boolean).parameterNames=dressing size crouton # END SNIPPET: config xbean-3.7/xbean-blueprint/src/test/resources/org/0000755000175000017500000000000011610661037022023 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/0000755000175000017500000000000011610661037023244 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/0000755000175000017500000000000011610661037024341 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/0000755000175000017500000000000011610661037026345 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/generator/0000755000175000017500000000000011610661037030333 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/generator/model-test-xsd-validation.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/generator/model-test-xsd-val0000644000175000017500000000356011326105761033714 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/0000755000175000017500000000000011610661037030031 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/spring-extension.xml0000644000175000017500000000221211322176276034072 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/bad-attribute.xml0000644000175000017500000000170211320711571033277 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/flatmap-xbean.xml0000644000175000017500000000242411322411021033256 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/keg-xbean.xml0000644000175000017500000000230511320772036032414 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/qname-xbean.xml0000644000175000017500000000240411322176276032755 0ustar drazzibdrazzib foo:test foo:bar foo:list xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/favorite-xbean.xml0000644000175000017500000000304011322411021033444 0ustar drazzibdrazzib Grey Goose Malbec xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/gin.xml0000644000175000017500000000211611320775234031333 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/bad-element.xml0000644000175000017500000000167611320711571032737 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-xbean-ns.xml0000644000175000017500000000217711320711571033205 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/favorite-normal.xml0000644000175000017500000000311011322411021033635 0ustar drazzibdrazzib Grey Goose Malbec xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/wine-xbean.xml0000644000175000017500000000212211321236753032607 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/recipe-normal.xml0000644000175000017500000000331411320750502033303 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-xbean-null.xml0000644000175000017500000000223111320777560033540 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/bad-namespace.xml0000644000175000017500000000164111320711571033232 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/recipe-xbean.xml0000644000175000017500000000265511320775234033130 0ustar drazzibdrazzib Mash together Food Mash together Food Mash together Food ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/component-blueprint.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/component-blueprint.0000644000175000017500000000221011322411021034013 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean-java.xml0000644000175000017500000000214111322176276033726 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/salad-normal.xml0000644000175000017500000000216611320750502033124 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-normal.xml0000644000175000017500000000212011320711571032746 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-simple.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-sim0000644000175000017500000000305411320750502034021 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/vodka-normal.xml0000644000175000017500000000227211320750502033142 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-xbean-system-prop.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-xbean-system-pr0000644000175000017500000000211611322176276033733 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean-bean-ref.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean-bean-ref0000644000175000017500000000235111322176276033670 0ustar drazzibdrazzib Salami ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-root.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-roo0000644000175000017500000000317411322176276034047 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/socket-address-normal.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/socket-address-norma0000644000175000017500000000323611320750502033777 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/keg-xbean-properties.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/keg-xbean-properties0000644000175000017500000000264411322176276034023 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/qname-normal.xml0000644000175000017500000000300511320775234033143 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/soup-xbean.xml0000644000175000017500000000263111321003657032633 0ustar drazzibdrazzib French Onion ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-normal.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-normal.xm0000644000175000017500000000564211322411021034046 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/wine-normal.xml0000644000175000017500000000210311320750502032771 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean-properties.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean-properti0000644000175000017500000000230411322176276034053 0ustar drazzibdrazzib cheese Edam Salami size 17 xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/socket-address.xml0000644000175000017500000000246511320750502033467 0ustar drazzibdrazzib localhost localhost localhost xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/component-xbean.xml0000644000175000017500000000212011321236753033645 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/soup-normal.xml0000644000175000017500000000322311320750502033021 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean.xml0000644000175000017500000000340311322411021034020 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-normal.xml0000644000175000017500000000217711320750502033177 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-spring-extended.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-spring-ex0000644000175000017500000000542711320750502034060 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/pizza-xbean.xml0000644000175000017500000000214311321236753033005 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-mixed.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/restaurant-xbean-mix0000644000175000017500000000433511326105761034040 0ustar drazzibdrazzib ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/recipe-xbean-mixed.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/recipe-xbean-mixed.x0000644000175000017500000000305111321236753033671 0ustar drazzibdrazzib Mash together Food Mash together Food xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/vodka-xbean.xml0000644000175000017500000000237611320750502032754 0ustar drazzibdrazzib vodkaService Grey Goose org.apache.xbean.blueprint.example.VodkaService ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/favorite-xbean-mixed.xmlxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/favorite-xbean-mixed0000644000175000017500000000323111322411021033753 0ustar drazzibdrazzib Malbec xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/salad-xbean.xml0000644000175000017500000000216011321236753032733 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/context/beer-xbean.xml0000644000175000017500000000211111321236753032560 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/jndi/0000755000175000017500000000000011610661037027271 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/jndi/jndi.xml0000644000175000017500000000324511320750502030735 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/resources/org/apache/xbean/blueprint/jndi/spring.xml0000644000175000017500000000324311320750502031311 0ustar drazzibdrazzib xbean-3.7/xbean-blueprint/src/test/java/0000755000175000017500000000000011610661036020142 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/0000755000175000017500000000000011610661036020731 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/0000755000175000017500000000000011610661036022152 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/0000755000175000017500000000000011610661036023247 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/0000755000175000017500000000000011610661036025253 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/generator/0000755000175000017500000000000011610661036027241 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/generator/CheeseService.java0000644000175000017500000000310111320711571032612 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; /** * Cheezy goodness * * @org.apache.xbean.XBean element="cheese" * * @author Dain Sundstrom * @version $Id$ */ public class CheeseService { private String id; private String name; private long volume; public CheeseService(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public long getVolumeWithPropertyEditor() { return volume; } /** * @org.apache.xbean.Property propertyEditor="org.apache.xbean.blueprint.example.MilliLittersPropertyEditor" */ public void setVolumeWithPropertyEditor(long volume) { this.volume = volume; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/generator/ModelTest.java0000644000175000017500000002210011326105761032001 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.generator; import junit.framework.TestCase; import org.apache.xbean.blueprint.example.BeerService; import org.xml.sax.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.beans.PropertyEditorManager; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class ModelTest extends TestCase { private static final String DEFAULT_NAMESPACE = "http://xbean.apache.org/test"; public void testQdox() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, null); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNotNull(element); AttributeMapping attribute = element.getAttribute("myTopping"); assertNotNull(attribute); assertEquals("topping", attribute.getPropertyName()); ElementMapping beer = defaultNamespace.getElement("beer"); assertNotNull(beer); AttributeMapping beerId = beer.getAttribute("id"); assertNotNull(beerId); AttributeMapping beerName = beer.getAttribute("name"); assertNotNull(beerName); ElementMapping recipeService = defaultNamespace.getElement("recipe-service"); assertNotNull(recipeService); Map flatCollections = recipeService.getFlatCollections(); assertNotNull(flatCollections); assertEquals(1, flatCollections.size()); ElementMapping cheese = defaultNamespace.getElement("cheese"); assertNotNull(cheese); AttributeMapping volume = cheese.getAttribute("volumeWithPropertyEditor"); assertNotNull(volume); assertNotNull(volume.getPropertyEditor()); assertEquals(volume.getType().getName(), "long"); // validate xsd has string for attribute VolumeWithPropertyEditor final AtomicBoolean gotExpected = new AtomicBoolean(false); XsdGenerator generator = new XsdGenerator(null); generator.generateSchema(new PrintWriter("dummy") { @Override public void println(String x) { if (x.indexOf("volumeWithPropertyEditor") != -1) { if (x.indexOf("xs:string") != -1) { gotExpected.set(true); } } } }, defaultNamespace); assertTrue("xsd with string got genereated", gotExpected.get()); } public void testQdoxExcludeClass() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, new String[] { BeerService.class.getName() } ); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNotNull(element); ElementMapping beer = defaultNamespace.getElement("beer"); assertNull(beer); } public void testQdoxExcludePackage() throws Exception{ String basedir = System.getProperties().getProperty("basedir", "."); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, new String[] { "org.apache.xbean.blueprint.example" } ); NamespaceMapping defaultNamespace = getDefaultNamespace(mappingLoader); assertNotNull(defaultNamespace); ElementMapping element = defaultNamespace.getElement("pizza"); assertNull(element); ElementMapping beer = defaultNamespace.getElement("beer"); assertNull(beer); ElementMapping cheese = defaultNamespace.getElement("cheese"); assertNotNull(cheese); } private NamespaceMapping getDefaultNamespace(QdoxMappingLoader mappingLoader) throws IOException { Set namespaces = mappingLoader.loadNamespaces(); assertFalse(namespaces.isEmpty()); NamespaceMapping defaultNamespace = null; for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); if (namespaceMapping.getNamespace().equals(DEFAULT_NAMESPACE)) { defaultNamespace = namespaceMapping; break; } } return defaultNamespace; } public void testPropertyEditor() { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); editorSearchPath.add("org.apache.xbean.blueprint.context.impl"); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); assertTrue(Utils.isSimpleType(Type.newSimpleType("java.net.URI"))); } public void xtestXSDValidation() throws Exception{ InputStream xmlFile = ModelTest.class.getResourceAsStream("model-test-xsd-validation.xml"); File xsd = generateXSD(); validate(xmlFile, xsd); } private File generateXSD() throws IOException { String basedir = System.getProperties().getProperty("basedir", "."); final File targetXSD = new File(basedir, "target/test-data/model-test.xsd"); targetXSD.getParentFile().mkdirs(); QdoxMappingLoader mappingLoader = new QdoxMappingLoader(DEFAULT_NAMESPACE, new File[] { new File(basedir, "/src/test/java")}, null); NamespaceMapping namespaceMapping = getDefaultNamespace(mappingLoader); XsdGenerator generator = new XsdGenerator(targetXSD); generator.setLog(new LogFacade() { public void log(String message) { } public void log(String message, int level) { } }); generator.generate(namespaceMapping); return targetXSD; } private void validate(InputStream xml, final File xsd) throws ParserConfigurationException, SAXException, IOException { assertNotNull(xml); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); final AtomicReference error = new AtomicReference(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { error.set(exception); } public void error(SAXParseException exception) throws SAXException { error.set(exception); } public void fatalError(SAXParseException exception) throws SAXException { error.set(exception); } }); //TODO blueprint what ?? builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // PluggableSchemaResolver springResolver = new PluggableSchemaResolver(getClass().getClassLoader()); InputSource source = null;//springResolver.resolveEntity(publicId, systemId); if (source == null && "http://xbean.apache.org/test.xsd".equals(systemId)) { source = new InputSource(new FileInputStream(xsd)); source.setPublicId(publicId); source.setSystemId(systemId); } return source; } }); builder.parse(xml); if (error.get() != null) { error.get().printStackTrace(); fail("Validation failed: " + error.get().getMessage()); } } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/0000755000175000017500000000000011610661036026706 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/SocketAddressFactory.java0000644000175000017500000000227111320711571033637 0ustar drazzibdrazzib/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.net.SocketAddress; import java.net.InetSocketAddress; /** * @org.apache.xbean.XBean element="socketAddress" contentProperty="value" */ public class SocketAddressFactory { /** * @org.apache.xbean.FactoryMethod */ public static SocketAddress create(String value) { return new InetSocketAddress(value, 42); } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/SaladService.java0000644000175000017500000000326411320711571032121 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * Basic salad. * @org.apache.xbean.XBean * * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ // START SNIPPET: bean public class SaladService { private final String dressing; private final String size; private final boolean crouton; public SaladService(String dressing, String size, boolean crouton) { this.dressing = dressing; this.size = size; this.crouton = crouton; } /** * Dressing What type of dressing do you want? */ public String getDressing() { return dressing; } /** * What size do you want? */ public String getSize() { return size; } /** * Do you want crutons on that? * @org.apache.xbean.Property alias="addCroutons" */ public boolean isCrouton() { return crouton; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/ContainerBean.java0000644000175000017500000000226711321236753032273 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * @org.apache.xbean.XBean element="container" * */ public class ContainerBean { InnerBean[] beans; /** * @return the beans */ public InnerBean[] getBeans() { return beans; } /** * @param beans the beans to set */ public void setBeans(InnerBean[] beans) { this.beans = beans; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/InnerBean.java0000644000175000017500000000225511321236753031421 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * @org.apache.xbean.XBean element="inner" * */ public class InnerBean { public static InnerBean INSTANCE = null; public InnerBean() { Thread.dumpStack(); if (INSTANCE == null) { INSTANCE = this; } else { throw new IllegalStateException("Already instanciated"); } } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/RecipeService.java0000644000175000017500000000275211320711571032305 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.util.List; /** * @org.apache.xbean.XBean element="recipe-service" * @author Dan Diephouse */ public class RecipeService { private List recipes; private Recipe topRecipe; /** * @org.apache.xbean.FlatCollection childElement="recipe" * @return */ public List getRecipes() { return recipes; } public void setRecipes(List recipes) { this.recipes = recipes; } /** * @org.apache.xbean.Flat * @return */ public Recipe getTopRecipe() { return topRecipe; } public void setTopRecipe(Recipe topRecipe) { this.topRecipe = topRecipe; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/QNameService.java0000644000175000017500000000251111320711571032070 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.util.List; import javax.xml.namespace.QName; /** * @org.apache.xbean.XBean element="qname-service" * @author gnodet */ public class QNameService { private QName[] services; private List list; public QName[] getServices() { return services; } public void setServices(QName[] services) { this.services = services; } public List getList() { return list; } public void setList(List list) { this.list = list; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/DummyBean.java0000644000175000017500000000230511320711571031430 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * @org.apache.xbean.XBean element="dummy" * @author gnodet * @since 2.7 */ public class DummyBean { private Object inner; /** * @return the inner */ public Object getInner() { return inner; } /** * @param inner the inner to set */ public void setInner(Object inner) { this.inner = inner; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/KegService.java0000644000175000017500000000312511320711571031577 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; //START SNIPPET: java /** * @org.apache.xbean.XBean element="keg" * * Used to verify that property PropertyEditors work correctly. * * @author chirino */ public class KegService { private long remaining; /** * Gets the amount of beer remaining in the keg (in ml) * * @param remaining */ public long getRemaining() { return remaining; } /** * Sets the amount of beer remaining in the keg (in ml) * * @org.apache.xbean.Property propertyEditor="org.apache.xbean.blueprint.example.MilliLittersPropertyEditor" * @param remaining */ public void setRemaining(long remaining) { this.remaining = remaining; } public long dispense( long amount ) { this.remaining -= amount; return this.remaining; } } // END SNIPPET: java xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/VodkaService.java0000644000175000017500000000320511320711571032134 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * It comes from a potatoe, it must be good. * * @org.apache.xbean.XBean element="vodka" * * @author Dan Diephouse * @version $Id: VodkaService.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 2.0 */ // START SNIPPET: bean public class VodkaService { private String id; private String name; private Class vodkaClass; public VodkaService() { } public String getId() { return id; } public String getName() { return name; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public Class getVodkaClass() { return vodkaClass; } public void setVodkaClass(Class vodkaClass) { this.vodkaClass = vodkaClass; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/RestaurantService.java0000644000175000017500000000473611320711571033232 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import javax.xml.namespace.QName; import java.net.URI; import java.util.List; import java.util.Set; /** * An owner POJO used for testing out nested properties * * @org.apache.xbean.XBean namespace="http://xbean.apache.org/schemas/pizza" element="restaurant" * description="A Restaurant thingy" * * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantService { private PizzaService favourite; private List dinnerMenu; private PizzaService[] lunchMenu; private Set snackMenu; private QName serviceName; private URI uri; /** * @org.apache.xbean.Property nestedType="org.apache.xbean.blueprint.example.PizzaService" */ public List getDinnerMenu() { return dinnerMenu; } public void setDinnerMenu(List dinnerMenu) { this.dinnerMenu = dinnerMenu; } public PizzaService[] getLunchMenu() { return lunchMenu; } public void setLunchMenu(PizzaService[] lunchMenu) { this.lunchMenu = lunchMenu; } public Set getSnackMenu() { return snackMenu; } public void setSnackMenu(Set snackMenu) { this.snackMenu = snackMenu; } public PizzaService getFavourite() { return favourite; } public void setFavourite(PizzaService favourite) { this.favourite = favourite; } public QName getServiceName() { return serviceName; } public void setServiceName(QName name) { this.serviceName = name; } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/WineService.java0000644000175000017500000000245111320711571031774 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * A drop of nice * * @org.apache.xbean.XBean element="wine" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class WineService { private String id; private String name; public WineService(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } } // END SNIPPET: bean ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/MilliLittersPropertyEditor.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/MilliLittersPropertyEdito0000644000175000017500000000403311320711571033776 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.beans.PropertyEditorSupport; import java.util.regex.Matcher; import java.util.regex.Pattern; //START SNIPPET: java /** * * Used to verify that per property PropertyEditors work correctly. * * @author chirino */ public class MilliLittersPropertyEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { Pattern p = Pattern.compile("^(\\d+)\\s*(l(iter)?)?$", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(text); if( m.matches() ) { setValue(new Long(Long.parseLong(m.group(1))*1000)); return; } p = Pattern.compile("^(\\d+)\\s*(ml)?$", Pattern.CASE_INSENSITIVE); m = p.matcher(text); if( m.matches() ) { setValue(new Long(Long.parseLong(m.group(1)))); return; } p = Pattern.compile("^(\\d+)\\s*pints?$", Pattern.CASE_INSENSITIVE); m = p.matcher(text); if( m.matches() ) { long pints = Long.parseLong(m.group(1)); setValue(new Long( (long)(pints * 1750) )); return; } throw new IllegalArgumentException("Could convert not to long (in ml) for "+ text); } public String getAsText() { Long value = (Long) getValue(); return (value != null ? value.toString() : ""); } } //END SNIPPET: java xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/FavoriteService.java0000644000175000017500000000247311320711571032655 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.util.Map; /** * @org.apache.xbean.XBean element="favorite" * * @author Dan Diephouse * @version $Id$ */ // START SNIPPET: bean public class FavoriteService { private Map favorites; /** * @org.apache.xbean.Map entryName="favorite-item" keyName="person" * @return */ public Map getFavorites() { return favorites; } public void setFavorites(Map favorites) { this.favorites = favorites; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/FlatMapService.java0000644000175000017500000000234711320711571032422 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.util.Map; /** * @org.apache.xbean.XBean element="flat-map" * @author gnodet */ public class FlatMapService { private Map services; /** * @org.apache.xbean.Map flat="true" dups="always" keyName="id" defaultKey="others" */ public Map getServices() { return services; } public void setServices(Map services) { this.services = services; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/SocketService.java0000644000175000017500000000231611320711571032322 0ustar drazzibdrazzib/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import java.net.SocketAddress; import java.util.List; /** * @org.apache.xbean.XBean element="socketService" */ public class SocketService { private List addresses; public List getAddresses() { return addresses; } public void setAddresses(List addresses) { this.addresses = addresses; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/PizzaService.java0000644000175000017500000000407511320711571032173 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @org.apache.xbean.XBean element="pizza" * description="This is a tasty Pizza" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class PizzaService { private static final Log log = LogFactory.getLog(PizzaService.class); private String topping; private String cheese; private int size; private double price; public void makePizza() { log.info("Making a pizza with topping: " + topping + " cheese: " + cheese + " with size: " + size); } public String getCheese() { return cheese; } public void setCheese(String cheese) { this.cheese = cheese; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } /** * @org.apache.xbean.Property alias="myTopping" */ public String getTopping() { return topping; } public void setTopping(String topping) { this.topping = topping; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/GinService.java0000644000175000017500000000231111320711571031602 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * Gin is made from the distillation of white grain spirit and juniper berries. * @org.apache.xbean.XBean element="gin" contentProperty="name" * * @version $Revision: 896187 $ */ public class GinService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/SoupService.java0000644000175000017500000000424011320711571032016 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @org.apache.xbean.XBean element="soup" * description="This is a tasty soup" * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class SoupService { private static final Log log = LogFactory.getLog(SoupService.class); /** * @org.apache.xbean.FactoryMethod */ public static SoupService newSoup(String type) { return new SoupService(type, System.currentTimeMillis()); } private final String type; private final long createTime; private boolean exists = false; private SoupService(String type, long createTime) { this.type = type; this.createTime = createTime; } /** * @org.apache.xbean.InitMethod */ public void make() { log.info("Making " + type + "soup"); exists = true; } /** * @org.apache.xbean.DestroyMethod */ public void eat() { log.info("Mummmm " + type + "soup is yummie!"); exists = false; } public boolean exists() { return exists; } /** * What type of soup would you like? */ public String getSoupType() { return type; } public long getCreateTime() { return createTime; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/BeerService.java0000644000175000017500000000277611320711571031761 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * @org.apache.xbean.XBean element="beer" description="Mmmmm beer" * * @author James Strachan * @version $Id$ * @since 2.0 */ // START SNIPPET: bean public class BeerService { private String id; private String name; private String source = "tap"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } } // END SNIPPET: bean xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/example/Recipe.java0000644000175000017500000000255211320711571030762 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.example; /** * @org.apache.xbean.XBean element="recipe" * @author Dan Diephouse */ public class Recipe { private String ingredients; private String instructions; public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/0000755000175000017500000000000011610661036026737 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanTest.0000644000175000017500000000405111322411021033637 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xbean.blueprint.example.RestaurantService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.BeanProperty; import javax.xml.namespace.QName; import java.net.URI; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanTest extends RestaurantUsingBlueprintTest { private static final Log log = LogFactory.getLog(RestaurantUsingXBeanTest.class); public void testPizza() throws Exception { super.testPizza(); BeanMetadataImpl restaurant = (BeanMetadataImpl) reg.getComponentDefinition("restaurant"); ValueMetadata uri = (ValueMetadata) propertyByName("uri", restaurant).getValue(); assertNotNull("URI is null", uri); assertEquals("URI", "http://cheese.com", uri.getStringValue()); log.info("Successfully converted the property to a URI: " + uri); } protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/VodkaUsingXBeanTest.java0000644000175000017500000000220311320776324033434 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id: VodkaUsingXBeanTest.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 2.0 */ public class VodkaUsingXBeanTest extends VodkaUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/vodka-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/QNameUsingXBeanTest.java0000644000175000017500000000200411320776324033370 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; public class QNameUsingXBeanTest extends QNameUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/qname-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingXBeanNSTest.java0000644000175000017500000000211111320776324033504 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author Guillaume Nodet * @version $Id$ * @since 2.2 */ public class BeerUsingXBeanNSTest extends BeerUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/beer-xbean-ns.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BlueprintTestSupport.java0000644000175000017500000001606411332361247034014 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import junit.framework.TestCase; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.apache.aries.blueprint.container.NamespaceHandlerRegistry; import org.apache.aries.blueprint.container.Parser; import org.apache.aries.blueprint.namespace.ComponentDefinitionRegistryImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xbean.blueprint.context.impl.QNameNamespaceHandler; import org.apache.xbean.blueprint.context.impl.XBeanNamespaceHandler; import org.apache.xbean.blueprint.example.MilliLittersPropertyEditor; import org.xml.sax.SAXException; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.osgi.service.blueprint.reflect.BeanArgument; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.BeanMetadata; import javax.xml.validation.Schema; import javax.xml.namespace.QName; import java.beans.PropertyEditor; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.List; import java.util.Map; /** * A useful base class for testing spring based utilities. * * @author James Strachan * @version $Id$ * @since 2.0 */ public abstract class BlueprintTestSupport extends TestCase { protected Log log = LogFactory.getLog(getClass()); private static final URI NAMESPACE_URI = URI.create("http://xbean.apache.org/schemas/pizza"); private static final URI QNAME_URI = URI.create("http://xbean.apache.org/schemas/javax.xml.namespace.QName"); protected ComponentDefinitionRegistryImpl reg; protected void setUp() throws Exception { reg = parse(getPlan()); } protected static ComponentDefinitionRegistryImpl parse(String plan) throws Exception { String schema = "META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/pizza"; return parse(plan, schema); } protected static ComponentDefinitionRegistryImpl parse(String plan, String schema) throws Exception { Properties properties = new Properties(); URL propUrl = BlueprintTestSupport.class.getClassLoader().getResource(schema); InputStream in = propUrl.openStream(); try { properties.load(in); } finally { in.close(); } Set classes = new HashSet(); ClassLoader cl = BlueprintTestSupport.class.getClassLoader(); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); if (!key.contains(".")) { String className = (String) entry.getValue(); Class clazz = cl.loadClass(className); classes.add(clazz); } } classes.add(QName.class); Map> propertyEditors = new HashMap>(); propertyEditors.put(MilliLittersPropertyEditor.class.getName(), MilliLittersPropertyEditor.class); final NamespaceHandler xbeanHandler = new XBeanNamespaceHandler(NAMESPACE_URI.toString(), BlueprintTestSupport.class.getClassLoader().getResource("restaurant.xsd"), classes, propertyEditors, properties); final NamespaceHandler qnameHandler = new QNameNamespaceHandler(); NamespaceHandlerRegistry.NamespaceHandlerSet handlers = new NamespaceHandlerRegistry.NamespaceHandlerSet() { public Set getNamespaces() { return new HashSet(Arrays.asList(NAMESPACE_URI, QNAME_URI)); } public NamespaceHandler getNamespaceHandler(URI namespace) { if (NAMESPACE_URI.equals(namespace)) { return xbeanHandler; } else if (QNAME_URI.equals(namespace)){ return qnameHandler; } return null; } public void removeListener(NamespaceHandlerRegistry.Listener listener) { } public Schema getSchema() throws SAXException, IOException { return null; } public boolean isComplete() { return false; } public void addListener(NamespaceHandlerRegistry.Listener listener) { } public void destroy() { } }; return parse(plan, handlers); } // from aries blueprint core AbstractBlueprintTest protected static ComponentDefinitionRegistryImpl parse(String plan, NamespaceHandlerRegistry.NamespaceHandlerSet handlers) throws Exception { ComponentDefinitionRegistryImpl registry = new ComponentDefinitionRegistryImpl(); Parser parser = new Parser(); parser.parse(Collections.singletonList(BlueprintTestSupport.class.getClassLoader().getResource(plan))); parser.populate(handlers, registry); return registry; } protected abstract String getPlan(); protected static void checkPropertyValue(String name, Object expectedValued, BeanMetadataImpl meta) { BeanProperty prop = propertyByName(name, meta); assertEquals(expectedValued, ((ValueMetadata) prop.getValue()).getStringValue()); } protected static BeanProperty propertyByName(String name, BeanMetadataImpl meta) { List props = meta.getProperties(); for (BeanProperty prop : props) { if (name.equals(prop.getName())) { return prop; } } throw new RuntimeException("No such property: " + name + " in metadata: " + meta); } protected static void checkArgumentValue(int index, String expectedValued, BeanMetadataImpl meta, boolean allowNesting) { List props = meta.getArguments(); Metadata metadata = props.get(index).getValue(); if (allowNesting && metadata instanceof BeanMetadata) { metadata = ((BeanMetadata) metadata).getArguments().get(0).getValue(); } assertEquals(expectedValued, ((ValueMetadata) metadata).getStringValue()); } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingXBeanTest.java0000644000175000017500000000210211320776324033243 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class BeerUsingXBeanTest extends BeerUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/beer-xbean.xml"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingBlueprintTest.j0000644000175000017500000000301111322411021033720 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.PizzaService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingBlueprintTest extends BlueprintTestSupport { public void testPizza() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("pizzaService"); // pizza.makePizza(); checkPropertyValue("topping", "Salami", meta); checkPropertyValue("cheese", "Edam", meta); checkPropertyValue("size", "17", meta); } protected String getPlan() { return "org/apache/xbean/blueprint/context/pizza-normal.xml"; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SocketAddressXBeanTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SocketAddressXBeanTest.ja0000644000175000017500000000211511320776324033573 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SocketAddressXBeanTest extends SocketAddressBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/socket-address.xml"; } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanWithSimplerConfigTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanWithS0000644000175000017500000000214511320776324033724 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanWithSimplerConfigTest extends RestaurantUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-xbean.xml"; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/KegXBeanAndPropertiesTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/KegXBeanAndPropertiesTest0000644000175000017500000000254311332361247033654 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * Used to verify that per Property Editors work correctly with * a PropertyPlaceholderConfigurer used to configure the values. * * @author chirino * @version $Id$ * @since 2.2 */ public class KegXBeanAndPropertiesTest extends KegXBeanTest { @Override public void testBeer() throws Exception { //disabled test } @Override protected void setUp() throws Exception { } protected String getPlan() { return "org/apache/xbean/blueprint/context/keg-xbean-properties.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerNullTest.java0000644000175000017500000000365311322176276032170 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.BeerService; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.NullMetadata; /** * @author Dain Sundstrom * @version $Id$ * @since 2.6 */ public class BeerNullTest extends BlueprintTestSupport { public void testBeer() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("beerService"); checkPropertyValue("name", "Stella", meta); checkPropertyValue("id", "123", meta); //no property set since this is the default // checkPropertyValue("source", "tap", meta); BeanMetadataImpl meta2 = (BeanMetadataImpl) reg.getComponentDefinition("beerService2"); checkPropertyValue("name", "Blue Moon", meta2); checkPropertyValue("id", "123", meta2); assertTrue(propertyByName("source", meta2).getValue() instanceof NullMetadata); } protected String getPlan() { return "org/apache/xbean/blueprint/context/beer-xbean-null.xml"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SaladUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SaladUsingBlueprintTest.j0000644000175000017500000000276211320776324033705 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.SaladService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SaladUsingBlueprintTest extends BlueprintTestSupport { public void testSalad() throws Exception { BeanMetadataImpl salad = (BeanMetadataImpl) reg.getComponentDefinition("saladService"); checkArgumentValue(0, "Cesar", salad, false); checkArgumentValue(1, "Small", salad, false); checkArgumentValue(2, "true", salad, false); } protected String getPlan() { return "org/apache/xbean/blueprint/context/salad-normal.xml"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/VodkaUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/VodkaUsingBlueprintTest.j0000644000175000017500000000317611320776324033725 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.VodkaService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author Dan Diephouse * @version $Id: VodkaUsingSpringTest.java 434369 2006-08-24 10:24:21Z gnodet $ * @since 1.0 */ public class VodkaUsingBlueprintTest extends BlueprintTestSupport { public void testWine() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("vodkaService"); checkPropertyValue("name", "Grey Goose", meta); checkPropertyValue("id", "vodkaService", meta); // Test more complex classes checkPropertyValue("vodkaClass", VodkaService.class.getName(), meta); } protected String getPlan() { return "org/apache/xbean/blueprint/context/vodka-normal.xml"; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWithPropertiesTextNodeTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWithProper0000644000175000017500000000212011320776324033727 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * * @version $Revision: 896313 $ */ public class PizzaUsingXBeanWithPropertiesTextNodeTest extends PizzaUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/pizza-xbean-properties.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/WineUsingXBeanTest.java0000644000175000017500000000210211320776324033270 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class WineUsingXBeanTest extends WineUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/wine-xbean.xml"; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWinBeanRefTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWinBeanRef0000644000175000017500000000326411322176276033620 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.apache.aries.blueprint.reflect.RefMetadataImpl; import org.osgi.service.blueprint.reflect.BeanProperty; /** * @version $Revision: 897559 $ */ public class PizzaUsingXBeanWinBeanRefTest extends PizzaUsingBlueprintTest { public void testPizza() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("pizzaService"); BeanProperty p = propertyByName("topping", meta); assertTrue(p.getValue() instanceof RefMetadataImpl); assertEquals("topping", ((RefMetadataImpl)p.getValue()).getComponentId()); checkPropertyValue("cheese", "#Edam", meta); checkPropertyValue("size", "17", meta); } protected String getPlan() { return "org/apache/xbean/blueprint/context/pizza-xbean-bean-ref.xml"; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingXBeanMixedTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingXBeanMixedTe0000644000175000017500000000213011320776324033646 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class FavoriteUsingXBeanMixedTest extends FavoriteUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/favorite-xbean-mixed.xml"; } }xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BadAttributeTest.java0000644000175000017500000000241211320711571033011 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadAttributeTest extends TestCase { public void testBadNs() throws Exception { try { BlueprintTestSupport.parse("org/apache/xbean/blueprint/context/bad-attribute.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingBlueprintT0000644000175000017500000001171311322411021034017 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import java.util.List; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.apache.aries.blueprint.reflect.ValueMetadataImpl; import org.apache.aries.blueprint.reflect.CollectionMetadataImpl; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.ValueMetadata; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingBlueprintTest extends BlueprintTestSupport { public void testPizza() throws Exception { BeanMetadataImpl restaurant = (BeanMetadataImpl) reg.getComponentDefinition("restaurant"); BeanProperty prop = propertyByName("serviceName", restaurant); BeanMetadataImpl qname = (BeanMetadataImpl) prop.getValue(); assertEquals(3, qname.getArguments().size()); assertEquals("http://acme.com", ((ValueMetadataImpl) qname.getArguments().get(0).getValue()).getStringValue()); assertEquals("xyz", ((ValueMetadataImpl) qname.getArguments().get(1).getValue()).getStringValue()); assertEquals("foo", ((ValueMetadataImpl) qname.getArguments().get(2).getValue()).getStringValue()); // dinners (1-many using list) BeanProperty dinnerProp = propertyByName("dinnerMenu", restaurant); List dinners = ((CollectionMetadata) dinnerProp.getValue()).getValues(); assertNotNull("dinners is null!", dinners); assertEquals("dinners size: " + dinners, 2, dinners.size()); BeanMetadataImpl pizza = (BeanMetadataImpl) dinners.get(0); checkPropertyValue("topping", "Ham", pizza); checkPropertyValue("cheese", "Mozzarella", pizza); //TODO blueprint int value checkPropertyValue("size", "15", pizza); pizza = (BeanMetadataImpl) dinners.get(1); checkPropertyValue("topping", "Eggs", pizza); checkPropertyValue("cheese", "Mozzarella", pizza); //TODO blueprint int value checkPropertyValue("size", "16", pizza); // dinners (1-many using Set) BeanProperty snackProp = propertyByName("snackMenu", restaurant); List snacks = ((CollectionMetadata) snackProp.getValue()).getValues(); assertNotNull("dinners is null!", snacks); assertEquals("dinners size: " + snacks, 2, snacks.size()); for (Metadata snackMeta : snacks) { BeanMetadataImpl snack = (BeanMetadataImpl) snackMeta; BeanProperty toppingProp = propertyByName("topping", snack); String topping = ((ValueMetadataImpl) toppingProp.getValue()).getStringValue(); if ("Tofu".equals(topping)) { checkPropertyValue("cheese", "Parmesan", snack); checkPropertyValue("size", "6", snack); } else if ("Prosciutto".equals(topping)) { checkPropertyValue("cheese", "Blue", snack); checkPropertyValue("size", "8", snack); } else { fail("wrong topping: " + snackMeta); } } // lunches (1-many using array) CollectionMetadataImpl lunches = (CollectionMetadataImpl) propertyByName("lunchMenu", restaurant).getValue(); assertNotNull("lunches is null!", lunches); assertEquals("lunches size: " + lunches, 1, lunches.getValues().size()); pizza = (BeanMetadataImpl) lunches.getValues().get(0); checkPropertyValue("topping", "Chicken", pizza); checkPropertyValue("cheese", "Brie", pizza); checkPropertyValue("size", "17", pizza); // favourite (1-1) BeanProperty favourite = propertyByName("favourite", restaurant); pizza = (BeanMetadataImpl) favourite.getValue(); assertNotNull("Pizza is null!", pizza); // pizza.makePizza(); // checkPropertyValue("topping", "Salami", pizza); checkPropertyValue("cheese", "Edam", pizza); checkPropertyValue("size", "17", pizza); } protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-normal.xml"; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RecipeUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RecipeUsingBlueprintTest.0000644000175000017500000000425311320776324033713 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import java.util.List; import org.apache.xbean.blueprint.example.Recipe; import org.apache.xbean.blueprint.example.RecipeService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.apache.aries.blueprint.reflect.CollectionMetadataImpl; import org.osgi.service.blueprint.reflect.Metadata; public class RecipeUsingBlueprintTest extends BlueprintTestSupport { public void testRecipes() throws Exception { BeanMetadataImpl svc = (BeanMetadataImpl) reg.getComponentDefinition("recipeService"); List list = ((CollectionMetadataImpl)propertyByName("recipes", svc).getValue()).getValues(); assertNotNull(list); assertEquals(2, list.size()); BeanMetadataImpl r = (BeanMetadataImpl) list.get(0); checkPropertyValue("ingredients", "Food", r); checkPropertyValue("instructions", "Mash together", r); r = (BeanMetadataImpl) list.get(1); checkPropertyValue("ingredients", "Food", r); checkPropertyValue("instructions", "Mash together", r); BeanMetadataImpl topRecipe = (BeanMetadataImpl) propertyByName("topRecipe", svc).getValue(); assertNotNull(topRecipe); checkPropertyValue("ingredients", "Food", topRecipe); } protected String getPlan() { return "org/apache/xbean/blueprint/context/recipe-normal.xml"; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/WineUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/WineUsingBlueprintTest.ja0000644000175000017500000000261411320776324033720 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class WineUsingBlueprintTest extends BlueprintTestSupport { public void testWine() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("wineService"); checkArgumentValue(1, "Amarone", meta, false); checkArgumentValue(0, "wineService", meta, false); } protected String getPlan() { return "org/apache/xbean/blueprint/context/wine-normal.xml"; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanAsRootTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanAsRoo0000644000175000017500000000236211322176276033714 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; public class RestaurantUsingXBeanAsRootTest extends RestaurantUsingBlueprintTest { //TODO blueprint disabled. First check is for blueprint namespace. @Override protected void setUp() throws Exception { } @Override public void testPizza() throws Exception { } protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-xbean-root.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BadElementTest.java0000644000175000017500000000240611320711571032442 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadElementTest extends TestCase { public void testBadNs() throws Exception { try { BlueprintTestSupport.parse("org/apache/xbean/blueprint/context/bad-element.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/GinUsingXBeanTest.java0000644000175000017500000000257611322411021033100 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.GinService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class GinUsingXBeanTest extends BlueprintTestSupport { public void testWine() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("ginService"); checkPropertyValue("name", "Bombay Sapphire", meta); } protected String getPlan() { return "org/apache/xbean/blueprint/context/gin.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/KegXBeanTest.java0000644000175000017500000000423311332361247032072 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.KegService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * Used to verify that per propety Property Editors work correctly. * * @author chirino * @version $Id$ * @since 2.2 */ public class KegXBeanTest extends BlueprintTestSupport { public void testBeer() throws Exception { //TODO blueprint value conversion using units?? BeanMetadataImpl ml1000 = (BeanMetadataImpl) reg.getComponentDefinition("ml1000"); BeanMetadataImpl empty = (BeanMetadataImpl) reg.getComponentDefinition("empty"); BeanMetadataImpl pints5 = (BeanMetadataImpl) reg.getComponentDefinition("pints5"); BeanMetadataImpl liter20 = (BeanMetadataImpl) reg.getComponentDefinition("liter20"); checkPropertyValue("remaining", "1000", ml1000); checkPropertyValue("remaining", "0", empty); checkPropertyValue("remaining", "8750", pints5); checkPropertyValue("remaining", "20000", liter20); // checkPropertyValue("remaining", "1000", ml1000); // checkPropertyValue("remaining", "0", empty); // checkPropertyValue("remaining", "8750", pints5); // checkPropertyValue("remaining", "20000", liter20); } protected String getPlan() { return "org/apache/xbean/blueprint/context/keg-xbean.xml"; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RecipeUsingXBeanMixedTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RecipeUsingXBeanMixedTest0000644000175000017500000000202211320776324033645 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; public class RecipeUsingXBeanMixedTest extends RecipeUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/recipe-xbean-mixed.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/ComponentTest.java0000644000175000017500000000406411322411021032373 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import junit.framework.TestCase; import org.apache.xbean.blueprint.example.InnerBean; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.CollectionMetadata; public class ComponentTest extends TestCase { protected void setUp() throws Exception { InnerBean.INSTANCE = null; } public void test1() throws Exception { test("org/apache/xbean/blueprint/context/component-blueprint.xml"); } public void test2() throws Exception { test("org/apache/xbean/blueprint/context/component-xbean.xml"); } protected void test(String file) throws Exception { ComponentDefinitionRegistry f = BlueprintTestSupport.parse(file); BeanMetadataImpl meta = (BeanMetadataImpl) f.getComponentDefinition("container"); assertNotNull(meta); CollectionMetadata list = (CollectionMetadata) BlueprintTestSupport.propertyByName("beans", meta).getValue(); assertEquals(1, list.getValues().size()); assertEquals(InnerBean.class.getName(), ((BeanMetadata)list.getValues().get(0)).getClassName()); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingBlueprintTes0000644000175000017500000000604211322411021033775 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import java.util.List; import java.util.Map; import org.apache.xbean.blueprint.example.FavoriteService; import org.apache.xbean.blueprint.example.GinService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.MapEntry; import org.osgi.service.blueprint.reflect.MapMetadata; import org.osgi.service.blueprint.reflect.ValueMetadata; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class FavoriteUsingBlueprintTest extends BlueprintTestSupport { public void testFavs() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("favoriteService"); assertEquals(1, meta.getProperties().size()); BeanProperty prop = propertyByName("favorites", meta); MapMetadata favorites = (MapMetadata) prop.getValue(); assertEquals(3, favorites.getEntries().size()); MapEntry me = favorites.getEntries().get(0); assertEquals("Dan", ((ValueMetadata) me.getKey()).getStringValue()); assertEquals("Grey Goose", ((ValueMetadata) me.getValue()).getStringValue()); me = favorites.getEntries().get(1); assertEquals("IndecisiveDan", ((ValueMetadata) me.getKey()).getStringValue()); CollectionMetadata cm = (CollectionMetadata) me.getValue(); assertEquals(2, cm.getValues().size()); assertEquals("Malbec", ((ValueMetadata) cm.getValues().get(0)).getStringValue()); assertEquals("0", ((ValueMetadata) ((BeanMetadata)cm.getValues().get(1)).getArguments().get(0).getValue()).getStringValue()); me = favorites.getEntries().get(2); assertEquals("WithInnerBean", ((ValueMetadata) me.getKey()).getStringValue()); BeanMetadata bm = (BeanMetadata) me.getValue(); assertEquals(GinService.class.getName(), bm.getClassName()); assertEquals("Bombay Sapphire", ((ValueMetadata)bm.getProperties().get(0).getValue()).getStringValue()); } protected String getPlan() { return "org/apache/xbean/blueprint/context/favorite-normal.xml"; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingResourceXmlApplicationContextTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingResourceXm0000644000175000017500000000215311320776324034043 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingResourceXmlApplicationContextTest extends RestaurantUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SoupUsingXBeanTest.java0000644000175000017500000000237011321003657033314 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class SoupUsingXBeanTest extends SoupUsingBlueprintTest { @Override protected void setUp() throws Exception { reg = parse(getPlan(), "META-INF/services/org/apache/xbean/blueprint/http/xbean.apache.org/schemas/soup"); } protected String getPlan() { return "org/apache/xbean/blueprint/context/soup-xbean.xml"; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWithJavaNamespaceTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanWithJavaNa0000644000175000017500000000214011320776324033622 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingXBeanWithJavaNamespaceTest extends PizzaUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/pizza-xbean-java.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SaladUsingXBeanTest.java0000644000175000017500000000210511320776324033415 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class SaladUsingXBeanTest extends SaladUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/salad-xbean.xml"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/QNameUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/QNameUsingBlueprintTest.j0000644000175000017500000000430011320776324033650 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import java.util.List; import javax.xml.namespace.QName; import org.apache.xbean.blueprint.example.QNameService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.apache.aries.blueprint.reflect.CollectionMetadataImpl; import org.osgi.service.blueprint.reflect.Metadata; public class QNameUsingBlueprintTest extends BlueprintTestSupport { public void testQName() throws Exception { BeanMetadataImpl svc = (BeanMetadataImpl) reg.getComponentDefinition("qnameService"); List services = ((CollectionMetadataImpl)propertyByName("services", svc).getValue()).getValues(); assertNotNull(services); assertEquals(2, services.size()); checkQName("urn:foo", "test", services.get(0)); checkQName("urn:foo", "bar", services.get(1)); List list = ((CollectionMetadataImpl)propertyByName("list", svc).getValue()).getValues(); assertNotNull(list); assertEquals(1, list.size()); checkQName("urn:foo", "list", list.get(0)); } protected void checkQName(String namespace, String local, Metadata meta) { checkArgumentValue(0, namespace, (BeanMetadataImpl) meta, false); checkArgumentValue(1, local, (BeanMetadataImpl) meta, false); } protected String getPlan() { return "org/apache/xbean/blueprint/context/qname-normal.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BadNamespaceTest.java0000644000175000017500000000241211320711571032742 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import junit.framework.TestCase; /** * @author Guillaume Nodet * @version $Id$ * @since 2.3 */ public class BadNamespaceTest extends TestCase { public void testBadNs() throws Exception { try { BlueprintTestSupport.parse("org/apache/xbean/blueprint/context/bad-namespace.xml"); fail("This should have thrown an exception"); } catch (Exception e) { System.out.println(e.getMessage()); } } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RecipeUsingXBeanTest.java0000644000175000017500000000200711320776324033601 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; public class RecipeUsingXBeanTest extends RecipeUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/recipe-xbean.xml"; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SoupUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SoupUsingBlueprintTest.ja0000644000175000017500000000377211320776324033752 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SoupUsingBlueprintTest extends BlueprintTestSupport { private static final long time = System.currentTimeMillis(); public void testSoup() throws Exception { BeanMetadataImpl soup = (BeanMetadataImpl) reg.getComponentDefinition("soupService"); BeanMetadataImpl nestedBean = (BeanMetadataImpl) reg.getComponentDefinition("nestedBean"); BeanMetadataImpl nestedValue = (BeanMetadataImpl) reg.getComponentDefinition("nestedValue"); asssertValidSoup(soup); asssertValidSoup(nestedBean); asssertValidSoup(nestedValue); // reg.; // assertFalse(soup.exists()); // assertFalse(nestedBean.exists()); // assertFalse(nestedValue.exists()); } private void asssertValidSoup(BeanMetadataImpl soup) { checkArgumentValue(0, "French Onion", soup, true); // assertTrue(soup.getCreateTime() >= time); assertNotNull(soup.getInitMethod()); } protected String getPlan() { return "org/apache/xbean/blueprint/context/soup-normal.xml"; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingSpringExtendedTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingSpringExte0000644000175000017500000000244511322411021034021 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingSpringExtendedTest extends RestaurantUsingBlueprintTest { @Override public void testPizza() throws Exception { //this test does not use any xbean, not sure how to make the QNameNamespaceHandler find attributes after the fact. } protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-spring-extended.xml"; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanMixedTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/RestaurantUsingXBeanMixed0000644000175000017500000000213711320776324033735 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class RestaurantUsingXBeanMixedTest extends RestaurantUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/restaurant-xbean-mixed.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/impl/0000755000175000017500000000000011610661036027700 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/impl/JexlTest.java0000644000175000017500000000323311333220747032310 0ustar drazzibdrazzib/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.xbean.blueprint.context.impl; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.xbean.blueprint.cm.JexlExpressionParser; /** * @version $Rev: 907189 $ $Date: 2010-02-06 09:01:43 +0100 (sam. 06 févr. 2010) $ */ public class JexlTest extends TestCase { public void testJexl() throws Exception { Map vars = new HashMap (); vars.put("foo", 1); vars.put("bar", 2); JexlExpressionParser parser = new JexlExpressionParser(vars); assertEquals(3, parser.evaluate("${foo + bar}")); vars.put("ServerHostname", "localhost"); vars.put("ActiveMQPort", 63636); vars.put("PortOffset", 10); assertEquals("tcp://localhost:63646", parser.evaluate("tcp://${ServerHostname}:${ActiveMQPort + PortOffset}")); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/impl/NamedConstructorArgsTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/impl/NamedConstructorArgs0000644000175000017500000001042211320711571033727 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context.impl; import java.io.ByteArrayInputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Properties; import junit.framework.TestCase; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class NamedConstructorArgsTest extends TestCase { private Properties properties = new Properties(); public void testPropertyParsing() { assertEquals("bar", properties.getProperty("foo")); assertEquals("blah", properties.getProperty("foo,chese")); assertEquals("StringBuffer", properties.getProperty("java.lang.String(java.lang.StringBuffer)")); assertEquals("char[]", properties.getProperty("java.lang.String([C)")); assertEquals("byte[],int,int", properties.getProperty("java.lang.String([B,int,int)")); assertEquals("URL[],ClassLoader", properties.getProperty("java.net.URLClassLoader([Ljava.net.URL;,java.lang.ClassLoader)")); } public void testMappingMetaData() throws Exception { MappingMetaData mappingMetaData = new MappingMetaData(properties); Constructor constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); assertTrue(mappingMetaData.isDefaultConstructor(constructor)); assertEquals(Arrays.asList(new String[] { "urls", "parent" }), Arrays.asList(mappingMetaData.getParameterNames(constructor))); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); assertFalse(mappingMetaData.isDefaultConstructor(constructor)); assertEquals(Arrays.asList(new String[] { "bytes", "offset", "length" }), Arrays.asList(mappingMetaData.getParameterNames(constructor))); } protected void setUp() throws Exception { StringBuffer buf = new StringBuffer(); buf.append("# test properties\n"); buf.append("foo=bar\n"); buf.append("foo,chese=blah\n"); Constructor constructor = String.class.getConstructor(new Class[] { StringBuffer.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=StringBuffer\n"); constructor = String.class.getConstructor(new Class[] { char[].class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=char[]\n"); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=byte[],int,int\n"); constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); buf.append(MappingMetaData.constructorToPropertyName(constructor) + "=URL[],ClassLoader\n"); properties.load(new ByteArrayInputStream(buf.toString().getBytes())); constructor = URLClassLoader.class.getConstructor(new Class[] { URL[].class, ClassLoader.class}); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".default", "true"); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".parameterNames", "urls,parent"); constructor = String.class.getConstructor(new Class[] { byte[].class, int.class, int.class}); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".default", "false"); properties.put(MappingMetaData.constructorToPropertyName(constructor) + ".parameterNames", "bytes,offset,length"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingBlueprintTest.ja0000644000175000017500000000276411321003657033672 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; /** * @author James Strachan * @version $Id$ * @since 1.0 */ public class BeerUsingBlueprintTest extends BlueprintTestSupport { public void testBeer() throws Exception { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("beerService"); checkPropertyValue("name", "Stella", meta); checkPropertyValue("id", "123", meta); assertEquals("id", "beerService", meta.getId()); } protected String getPlan() { return "org/apache/xbean/blueprint/context/beer-normal.xml"; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SocketAddressBlueprintTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SocketAddressBlueprintTes0000644000175000017500000000510011320776324033762 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Arrays; import java.util.List; import org.apache.xbean.blueprint.example.SocketService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.CollectionMetadata; /** * @author Dain Sundstrom * @version $Id$ * @since 1.0 */ public class SocketAddressBlueprintTest extends BlueprintTestSupport { public void testSocketService() throws Exception { BeanMetadataImpl socketService = (BeanMetadataImpl) reg.getComponentDefinition("socketService"); // System.out.println(); // System.out.println("==========================="); // System.out.println(socketService.getAddresses()); // System.out.println("==========================="); // System.out.println(); // List expected = Arrays.asList(new InetSocketAddress("localhost", 42), new InetSocketAddress("localhost", 42)); assertEquals(1, socketService.getProperties().size()); CollectionMetadata collection = (CollectionMetadata) socketService.getProperties().get(0).getValue(); assertEquals(2, collection.getValues().size()); } public void testSocketAddress() throws Exception { BeanMetadataImpl socketAddress = (BeanMetadataImpl) reg.getComponentDefinition("socketAddress"); // System.out.println(); // System.out.println("==========================="); // System.out.println(socketAddress); // System.out.println("==========================="); // System.out.println(); assertNotNull(socketAddress); } protected String getPlan() { return "org/apache/xbean/blueprint/context/socket-address-normal.xml"; } }././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingXBeanTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FavoriteUsingXBeanTest.ja0000644000175000017500000000211611320776324033623 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class FavoriteUsingXBeanTest extends FavoriteUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/favorite-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/PizzaUsingXBeanTest.java0000644000175000017500000000211311320776324033465 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author James Strachan * @version $Id$ * @since 2.0 */ public class PizzaUsingXBeanTest extends PizzaUsingBlueprintTest { protected String getPlan() { return "org/apache/xbean/blueprint/context/pizza-xbean.xml"; } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/FlatMapTest.java0000644000175000017500000000556711332361247032005 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; import org.apache.xbean.blueprint.example.KegService; import org.apache.aries.blueprint.reflect.BeanMetadataImpl; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.MapEntry; import org.osgi.service.blueprint.reflect.MapMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.ValueMetadata; /** * @author gnodet */ public class FlatMapTest extends BlueprintTestSupport { public void testFlatMap() { BeanMetadataImpl meta = (BeanMetadataImpl) reg.getComponentDefinition("flat-map"); MapMetadata c = (MapMetadata) propertyByName("services", meta).getValue(); assertEquals(3, c.getEntries().size()); MapEntry me = c.getEntries().get(0); assertEquals("key1", ((ValueMetadata) me.getKey()).getStringValue()); CollectionMetadata l = (CollectionMetadata) me.getValue(); assertEquals(2, l.getValues().size()); checkEntry(l.getValues().get(0), "1000"); checkEntry(l.getValues().get(1), "8750"); me = c.getEntries().get(1); assertEquals("key2", ((ValueMetadata) me.getKey()).getStringValue()); l = (CollectionMetadata) me.getValue(); assertEquals(1, l.getValues().size()); checkEntry(l.getValues().get(0), "20000"); me = c.getEntries().get(2); assertEquals("others", ((ValueMetadata) me.getKey()).getStringValue()); l = (CollectionMetadata) me.getValue(); assertEquals(1, l.getValues().size()); checkEntry(l.getValues().get(0), "0"); } private void checkEntry(Metadata me, String value) { BeanMetadataImpl beanMetadata = (BeanMetadataImpl) me; assertEquals(KegService.class.getName(), beanMetadata.getClassName()); assertEquals(1, beanMetadata.getProperties().size()); assertEquals(value, ((ValueMetadata) beanMetadata.getProperties().get(0).getValue()).getStringValue()); } protected String getPlan() { return "org/apache/xbean/blueprint/context/flatmap-xbean.xml"; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingXBeanSystemPropTest.javaxbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/BeerUsingXBeanSystemPropT0000644000175000017500000000245311322176276033670 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author Hiram Chirino * @version $Id$ * @since 2.0 */ public class BeerUsingXBeanSystemPropTest extends BeerUsingBlueprintTest { @Override public void testBeer() throws Exception { //disabled } protected String getPlan() { return "org/apache/xbean/blueprint/context/beer-xbean-system-prop.xml"; } protected void setUp() throws Exception { System.setProperty("beerType", "Stella"); super.setUp(); } } xbean-3.7/xbean-blueprint/src/test/java/org/apache/xbean/blueprint/context/SpringExtensionTest.java0000644000175000017500000000224511322176276033613 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.blueprint.context; /** * @author gnodet * @since 2.7 */ public class SpringExtensionTest extends BlueprintTestSupport { @Override protected void setUp() throws Exception { //disabled } public void test() { } protected String getPlan() { return "org/apache/xbean/blueprint/context/spring-extension.xml"; } } xbean-3.7/xbean-blueprint/src/site/0000755000175000017500000000000011610661037017207 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/site/apt/0000755000175000017500000000000011610661037017773 5ustar drazzibdrazzibxbean-3.7/xbean-blueprint/src/site/site.xml0000644000175000017500000000210010473277125020675 0ustar drazzibdrazzib ${parentProject} ${modules} ${reports} xbean-3.7/xbean-reflect/0000755000175000017500000000000011610661033015070 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/pom.xml0000644000175000017500000001174411373256143016424 0ustar drazzibdrazzib 4.0.0 xbean org.apache.xbean 3.7 xbean-reflect bundle Apache XBean :: Reflect xbean-reflect provides very flexible ways to creat objects and graphs of objects for DI frameworks asm asm 3.1 provided true asm asm-commons 3.1 provided true org.apache.xbean xbean-asm-shaded 3.7 provided true log4j log4j 1.2.12 compile true commons-logging commons-logging-api 1.1 compile true org.apache.felix maven-bundle-plugin 2.0.0 true !org.apache.xbean.asm.*,org.apache.xbean.*;version=${pom.version} *,org.apache.log4j;resolution:=optional,org.apache.commons.logging;resolution:=optional,org.objectweb.asm;resolution:=optional;version=3.1,org.objectweb.asm.commons;resolution:=optional;version=3.1,org.apache.xbean.asm;resolution:=optional;version=3.1,org.apache.xbean.asm.commons;resolution:=optional;version=3.1 debug DEBUG org.apache.maven.plugins maven-surefire-plugin 2.2 pertest -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005 -enableassertions ${basedir}/target xbean-3.7/xbean-reflect/src/0000755000175000017500000000000011610661033015657 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/0000755000175000017500000000000011610661033016603 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/resources/0000755000175000017500000000000011610661033020615 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/resources/META-INF/0000755000175000017500000000000011610661033021755 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/0000755000175000017500000000000011610661033017524 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/org/0000755000175000017500000000000011610661033020313 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/org/apache/0000755000175000017500000000000011610661033021534 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/org/apache/xbean/0000755000175000017500000000000011610661033022631 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/org/apache/xbean/recipe/0000755000175000017500000000000011610661033024100 5ustar drazzibdrazzibxbean-3.7/xbean-reflect/src/main/java/org/apache/xbean/recipe/AllPropertiesRecipe.java0000644000175000017500000000401410760333304030661 0ustar drazzibdrazzib/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.recipe; import java.util.Map; import java.util.Properties; import java.lang.reflect.Type; public class AllPropertiesRecipe extends AbstractRecipe { public boolean canCreate(Type type) { return RecipeHelper.isAssignable(type, Properties.class); } protected Object internalCreate(Type expectedType, boolean lazyRefAllowed) throws ConstructionException { Recipe outerRecipe = RecipeHelper.getCaller(); if (!(outerRecipe instanceof ObjectRecipe)) { throw new ConstructionException("UnsetPropertiesRecipe can only be nested in an ObjectRecipe: outerRecipe=" + outerRecipe); } ObjectRecipe objectRecipe = (ObjectRecipe) outerRecipe; Map allProperties = objectRecipe.getProperties(); // copy to a properties object Properties properties = new Properties(); for (Map.Entry entry : allProperties.entrySet()) { properties.put(entry.getKey(), entry.getValue()); } // add to execution context if name is specified if (getName() != null) { ExecutionContext.getContext().addObject(getName(), properties); } return properties; } }xbean-3.7/xbean-reflect/src/main/java/org/apache/xbean/recipe/CollectionRecipe.java0000644000175000017500000002074511176111740030200 0ustar drazzibdrazzib/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.xbean.recipe; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * @version $Rev: 6685 $ $Date: 2005-12-28T00:29:37.967210Z $ */ public class CollectionRecipe extends AbstractRecipe { private final List list; private String typeName; private Class typeClass; private final EnumSet