diff options
Diffstat (limited to '')
113 files changed, 9863 insertions, 0 deletions
diff --git a/sandbox/old/contrib/persistence/common/LICENSE.txt b/sandbox/old/contrib/persistence/common/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/LICENSE.txt @@ -0,0 +1,202 @@ + + 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. diff --git a/sandbox/old/contrib/persistence/common/NOTICE.txt b/sandbox/old/contrib/persistence/common/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +Apache Tuscany is an effort undergoing incubation at The Apache Software +Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is +required of all newly accepted projects until a further review indicates that +the infrastructure, communications, and decision making process have stabilized +in a manner consistent with other successful ASF projects. While incubation +status is not necessarily a reflection of the completeness or stability of the +code, it does indicate that the project has yet to be fully endorsed by the ASF. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/old/contrib/persistence/common/pom.xml.off b/sandbox/old/contrib/persistence/common/pom.xml.off new file mode 100644 index 0000000000..9b5bf4c6ef --- /dev/null +++ b/sandbox/old/contrib/persistence/common/pom.xml.off @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + + <parent> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>persistence-common</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany JPA</name> + <description>Tuscany JPA Integration.</description> + <version>1.0-alpha-incubating-SNAPSHOT</version> + + + <repositories> + <repository> + <id>java.net</id> + <url>https://maven-repository.dev.java.net/nonav/repository</url> + <layout>legacy</layout> + </repository> + <repository> + <id>apache-snapshots</id> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>javax.persistence</groupId> + <artifactId>persistence-api</artifactId> + <version>1.0</version> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.services.transaction</groupId> + <artifactId>tuscany-transaction-geronimo</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-api</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>org.apache.openjpa</groupId> + <artifactId>openjpa-persistence-jdbc</artifactId> + <version>0.9.0-incubating-SNAPSHOT</version> + </dependency> + </dependencies> +</project> diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilder.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilder.java new file mode 100644 index 0000000000..684eee8c09 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilder.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceProvider; +import javax.persistence.spi.PersistenceUnitInfo; + +/** + * Default implementation of the persistence unit builder. + * + * @version $Rev$ $Date$ + */ +public class DefaultPersistenceUnitBuilder implements PersistenceUnitBuilder { + + /** Persistence unit scanner */ + private PersistenceUnitScanner scanner = new PersistenceUnitScanner(); + + /** + * Builds the entity manager factory matching the unit name. All persistence.xml + * files available for the specified classloader is scanned for the specified + * persistence unit. The JPA provider API is used to create the entity manager + * factory. + * + * @param unitName Persistence unit name. + * @param classLoader Classloader. + * @return Entity manager factory. + */ + public EntityManagerFactory newEntityManagerFactory(String unitName, ClassLoader classLoader) { + + PersistenceUnitInfo info = scanner.getPersistenceUnitInfo(unitName, classLoader); + String providerClass = info.getPersistenceProviderClassName(); + try { + Map overrides = new HashMap(); + PersistenceProvider provider = (PersistenceProvider) Class.forName(providerClass).newInstance(); + return provider.createContainerEntityManagerFactory(info, overrides); + } catch (InstantiationException ex) { + throw new TuscanyJpaException(ex); + } catch (IllegalAccessException ex) { + throw new TuscanyJpaException(ex); + } catch (ClassNotFoundException ex) { + throw new TuscanyJpaException(ex); + } + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/EntityManagerProxy.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/EntityManagerProxy.java new file mode 100644 index 0000000000..492bd36689 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/EntityManagerProxy.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.transaction.Synchronization; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +/** + * Proxy for entity manager. + * + * @version $Rev$ $Date$ + */ +public class EntityManagerProxy implements InvocationHandler { + + // Thread local cache of entity managers + private ThreadLocal<EntityManager> entityManagers = new ThreadLocal<EntityManager>(); + + // Properties + private Properties prop; + + // Entity manager factory + private EntityManagerFactory emf; + + // Transaction manager + private TransactionManager txm; + + /** + * Initializes the artifacts required to create an EM. + * + * @param prop EM creation porperty overrides. + * @param emf Entity manager factory to use. + * @param txm Transaction manager to use. + */ + public EntityManagerProxy(Properties prop, EntityManagerFactory emf, TransactionManager txm) { + this.prop = prop; + this.txm = txm; + this.emf = emf; + } + + /** + * Proxies the entity manager. + */ + public Object invoke(Object target, Method method, Object[] parameters) throws Throwable { + + EntityManager entityManager = entityManagers.get(); + if(entityManager != null) { + entityManager = emf.createEntityManager(prop); + entityManagers.set(entityManager); + Transaction tx = txm.getTransaction(); + if(tx != null) { + tx.registerSynchronization(new Synchronization() { + public void afterCompletion(int arg0) { + entityManagers.set(null); + } + public void beforeCompletion() { + } + }); + } + } + return method.invoke(entityManager, parameters); + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/JpaConstants.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/JpaConstants.java new file mode 100644 index 0000000000..04d1c419ca --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/JpaConstants.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +public class JpaConstants { + + public static final String PROPERTY_VALUE = "value"; + + public static final String PROPERTY_NAME = "name"; + + public static final String PROPERTY = "//persistence-unit/properties/property"; + + public static final String TRANSACTION_TYPE = "//persistence-unit/@transaction-type"; + + public static final String NAME = "//persistence-unit/@name"; + + public static final String PROVIDER = "//persistence-unit/provider"; + + public static final String NON_JTA_DATA_SOURCE = "//persistence-unit/non-jta-data-source"; + + public static final String MAPPING_FILE = "//persistence-unit/mapping-file"; + + public static final String CLASS = "//persistence-unit/class"; + + public static final String JTA_DATA_SOURCE = "//persistence-unit/jta-data-source"; + + public static final String JAR_FILE = "//persistence-unit/jar-file"; + + public static final String EXCLUDE_UNLISTED_CLASSES = "//persistence-unit/exclude-unlisted-classes"; + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceContextProcessor.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceContextProcessor.java new file mode 100644 index 0000000000..9d247fae43 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceContextProcessor.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.util.Properties; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; +import javax.persistence.PersistenceProperty; +import javax.transaction.TransactionManager; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.component.RegistrationException; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.InterfaceJavaIntrospector; +import org.apache.tuscany.spi.implementation.java.AbstractPropertyProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.ProcessingException; +import org.apache.tuscany.spi.model.ServiceContract; + +import org.apache.tuscany.core.component.ComponentManager; + +/** + * Annotation processor for injecting <code>PersistenceUnit</code> annotations on properties. + * + * @version $Rev$ $Date$ + */ +public class PersistenceContextProcessor extends AbstractPropertyProcessor<PersistenceContext> { + + /** + * Transaction Manager + */ + private TransactionManager transactionManager; + private ComponentManager componentManager; + private InterfaceJavaIntrospector introspector; + + /** + * Persistence unit builder + */ + private PersistenceUnitBuilder builder = new DefaultPersistenceUnitBuilder(); + + /** + * Injects the implementation processor service. + * + * @param service Implementation processor service. + */ + public PersistenceContextProcessor(@Reference ImplementationProcessorService service) { + super(PersistenceContext.class, service); + } + + @Reference + public void setTransactionManager(TransactionManager transactionManager) { + this.transactionManager = transactionManager; + } + + @Reference + public void setComponentManager(ComponentManager componentManager) { + this.componentManager = componentManager; + } + + @Reference + public void setIntrospector(InterfaceJavaIntrospector introspector) { + this.introspector = introspector; + } + + /** + * Defaults to the field name. + */ + @Override + protected String getName(PersistenceContext persistenceContext) { + return null; + } + + /** + * Initializes the property. + */ + @SuppressWarnings("unchecked") + protected <T> void initProperty(JavaMappedProperty<T> property, + PersistenceContext annotation, + DeploymentContext context) throws ProcessingException { + + String unitName = annotation.unitName(); + URI unitUri = context.getComponentId().resolve(unitName); + EntityManagerFactory emf = (EntityManagerFactory) componentManager.getComponent(unitUri); + + if (emf == null) { + emf = builder.newEntityManagerFactory(unitName, context.getClassLoader()); + try { + ServiceContract<EntityManagerFactory> contract = + (ServiceContract) introspector.introspect(EntityManagerFactory.class); + componentManager.registerJavaObject(unitUri, contract, emf); + } catch (RegistrationException e) { + throw new ProcessingException(e); + } catch (InvalidServiceContractException e) { + throw new ProcessingException(e); + } + } + ObjectFactory factory = new EmObjectFactory(emf, annotation); + property.setDefaultValueFactory(factory); + + } + + private class EmObjectFactory implements ObjectFactory<EntityManager> { + + private EntityManagerFactory emf; + private PersistenceContext annotation; + + public EmObjectFactory(EntityManagerFactory emf, PersistenceContext annotation) { + this.emf = emf; + this.annotation = annotation; + } + + public EntityManager getInstance() { + + PersistenceContextType type = annotation.type(); + if (type == PersistenceContextType.TRANSACTION) { + + Properties props = new Properties(); + for (PersistenceProperty property : annotation.properties()) { + props.put(property.name(), property.value()); + } + + Class[] interfaces = new Class[]{EntityManager.class}; + InvocationHandler handler = new EntityManagerProxy(props, emf, transactionManager); + EntityManager em = + (EntityManager) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, handler); + return em; + + } else { + throw new UnsupportedOperationException("Extended persistence contexts not supported"); + } + + } + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitBuilder.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitBuilder.java new file mode 100644 index 0000000000..d8d30d6811 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitBuilder.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import javax.persistence.EntityManagerFactory; + +/** + * Interface for building persistence units as specified by the JPA specification.. + * + * @version $Rev$ $Date$ + */ +public interface PersistenceUnitBuilder { + + /** + * Builds the entity manager factory matching the unit name. All persistence.xml files available for the specified + * classloader is scanned for the specified persistence unit. The JPA provider API is used to create the entity + * manager factory. + * + * @param unitName Persistence unit name. + * @param classLoader Classloader. + * @return Entity manager factory. + */ + public EntityManagerFactory newEntityManagerFactory(String unitName, ClassLoader classLoader); + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java new file mode 100644 index 0000000000..169f48fec7 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitProcessor.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.lang.reflect.Field; +import java.net.URI; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.RegistrationException; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.InterfaceJavaIntrospector; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorExtension; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ProcessingException; +import org.apache.tuscany.spi.implementation.java.Resource; +import org.apache.tuscany.spi.model.ServiceContract; + +import org.apache.tuscany.core.component.ComponentManager; + +/** + * Annotation processor for injecting <code>PersistenceUnit</code> annotations on properties. + * + * @version $Rev$ $Date$ + */ +public class PersistenceUnitProcessor extends ImplementationProcessorExtension { + /** + * Persistence unit builder + */ + private PersistenceUnitBuilder builder = new DefaultPersistenceUnitBuilder(); + private ComponentManager componentManager; + private InterfaceJavaIntrospector introspector; + + @Reference + public void setComponentManager(ComponentManager componentManager) { + this.componentManager = componentManager; + } + + @Reference + public void setIntrospector(InterfaceJavaIntrospector introspector) { + this.introspector = introspector; + } + + + @SuppressWarnings({"unchecked"}) + public void visitField(Field field, + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type, + DeploymentContext context) throws ProcessingException { + + PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); + if (annotation == null) { + return; + } + String unitName = annotation.unitName(); + URI unitUri = context.getComponentId().resolve(unitName); + AtomicComponent component = (AtomicComponent) componentManager.getComponent(unitUri); + EntityManagerFactory emf; + if (component == null) { + emf = builder.newEntityManagerFactory(unitName, context.getClassLoader()); + try { + ServiceContract<EntityManagerFactory> contract = + (ServiceContract) introspector.introspect(EntityManagerFactory.class); + componentManager.registerJavaObject(unitUri, contract, emf); + } catch (RegistrationException e) { + throw new ProcessingException(e); + } catch (InvalidServiceContractException e) { + throw new ProcessingException(e); + } + } else { + try { + emf = (EntityManagerFactory) component.getTargetInstance(); + } catch (TargetException e) { + throw new ProcessingException(e); + } + } + + ObjectFactory factory = new EmfObjectFactory(emf); + Resource resource = new Resource(unitName, field.getType(), field); + resource.setObjectFactory(factory); + type.add(resource); + } + + private class EmfObjectFactory implements ObjectFactory<EntityManagerFactory> { + + private EntityManagerFactory emf; + + public EmfObjectFactory(EntityManagerFactory emf) { + this.emf = emf; + } + + public EntityManagerFactory getInstance() { + return emf; + } + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScanner.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScanner.java new file mode 100644 index 0000000000..00fd02b891 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScanner.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.spi.PersistenceUnitInfo; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/** + * Scans the classloader for the specified persistence unit. + * + * @version $Rev$ $Date$ + */ +class PersistenceUnitScanner { + + /** Cache of persistence unit info */ + private Map<String, PersistenceUnitInfo> persistenceUnitInfos = new HashMap<String, PersistenceUnitInfo>(); + + /** + * Scans the lassloader for the specified persistence unit and creates + * an immutable representation of the information present in the matching + * persistence.xml file. + * + * @param unitName Persistence unit name. + * @param classLoader Classloader to scan. + * @return Persistence unit information. + */ + PersistenceUnitInfo getPersistenceUnitInfo(String unitName, ClassLoader classLoader) { + + synchronized (persistenceUnitInfos) { + + if(persistenceUnitInfos.containsKey(unitName)) { + return persistenceUnitInfos.get(unitName); + } + + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + Enumeration<URL> persistenceUnitUrls = classLoader.getResources("META-INF/persistence.xml"); + while (persistenceUnitUrls.hasMoreElements()) { + + URL persistenceUnitUrl = persistenceUnitUrls.nextElement(); + Document persistenceDom = db.parse(persistenceUnitUrl.openStream()); + + String rootJarUrl = persistenceUnitUrl.toString(); + rootJarUrl = rootJarUrl.substring(0, rootJarUrl.lastIndexOf("META-INF")); + + PersistenceUnitInfo info = new TuscanyPersistenceUnitInfo(persistenceDom, classLoader, rootJarUrl); + if (!unitName.equals(info.getPersistenceUnitName())) { + continue; + } + + persistenceUnitInfos.put(unitName, info); + return info; + + } + } catch (IOException ex) { + throw new TuscanyJpaException(ex); + } catch (ParserConfigurationException ex) { + throw new TuscanyJpaException(ex); + } catch (SAXException ex) { + throw new TuscanyJpaException(ex); + } + + } + + throw new TuscanyJpaException("Unabel to find persistence unit: " + unitName); + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyJpaException.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyJpaException.java new file mode 100644 index 0000000000..2690f43f7c --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyJpaException.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import org.apache.tuscany.api.TuscanyRuntimeException; + +/** + * Unexpected exception in processing JPA annotations. + * + */ +public class TuscanyJpaException extends TuscanyRuntimeException { + + /** + * Serial version UID. + */ + private static final long serialVersionUID = 2772746952304093785L; + + /** + * Initializes the message. + * @param message Message to be initialized. + */ + public TuscanyJpaException(String message) { + super(message); + } + + /** + * Initializes the underlying cause. + * @param cause Cause to be initialized. + */ + public TuscanyJpaException(Throwable cause) { + super(cause); + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyPersistenceUnitInfo.java b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyPersistenceUnitInfo.java new file mode 100644 index 0000000000..eb1dee24a7 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/java/org/apache/tuscany/service/persistence/common/TuscanyPersistenceUnitInfo.java @@ -0,0 +1,288 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import javax.sql.DataSource; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import static org.apache.tuscany.service.persistence.common.JpaConstants.*; + +/** + * Encpasulates the information in the persistence.xml file. + * + * This class is expected to be interogated by the provider only + * during the creation of the entity manager factory. Hence none + * of the values are cached, rather every time a property is queried + * the underlying DOM is interogated. + * + */ +class TuscanyPersistenceUnitInfo implements PersistenceUnitInfo { + + /** Persistence DOM */ + private Node persistenceDom; + + /** Classloader */ + private ClassLoader classLoader; + + /** Root Url */ + private String rootUrl; + + /** XPath API */ + XPath xpath = XPathFactory.newInstance().newXPath(); + + /** + * Initializes the properties. + * + * @param persistenceDom + * @param classLoader + * @param rootUrl + */ + public TuscanyPersistenceUnitInfo(Node persistenceDom, ClassLoader classLoader, String rootUrl) { + this.persistenceDom = persistenceDom; + this.classLoader = classLoader; + this.rootUrl = rootUrl; + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#addTransformer(javax.persistence.spi.ClassTransformer) + */ + public void addTransformer(ClassTransformer classTransformer) { + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#excludeUnlistedClasses() + */ + public boolean excludeUnlistedClasses() { + return getBooleanValue(persistenceDom, EXCLUDE_UNLISTED_CLASSES); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getClassLoader() + */ + public ClassLoader getClassLoader() { + return classLoader; + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getJarFileUrls() + */ + public List<URL> getJarFileUrls() { + + List<String> jarFiles = getMultipleValues(persistenceDom, JAR_FILE); + try { + List<URL> jarUrls = new LinkedList<URL>(); + for (String jarFile : jarFiles) { + jarUrls.add(new URL(jarFile)); + } + return jarUrls; + } catch (MalformedURLException ex) { + throw new TuscanyJpaException(ex); + } + + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getJtaDataSource() + */ + public DataSource getJtaDataSource() { + + String jtaDsName = getSingleValue(persistenceDom, JTA_DATA_SOURCE); + if (jtaDsName == null || "".equals(jtaDsName)) { + return null; + } + return lookupDataSource(jtaDsName); + + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getManagedClassNames() + */ + public List<String> getManagedClassNames() { + return getMultipleValues(persistenceDom, CLASS); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getMappingFileNames() + */ + public List<String> getMappingFileNames() { + return getMultipleValues(persistenceDom, MAPPING_FILE); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader() + */ + public ClassLoader getNewTempClassLoader() { + return null; + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getNonJtaDataSource() + */ + public DataSource getNonJtaDataSource() { + + String nonJtaDsName = getSingleValue(persistenceDom, NON_JTA_DATA_SOURCE); + if (nonJtaDsName == null || "".equals(nonJtaDsName)) { + return null; + } + return lookupDataSource(nonJtaDsName); + + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getPersistenceProviderClassName() + */ + public String getPersistenceProviderClassName() { + return getSingleValue(persistenceDom, PROVIDER); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getPersistenceUnitName() + */ + public String getPersistenceUnitName() { + return getSingleValue(persistenceDom, NAME); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getPersistenceUnitRootUrl() + */ + public URL getPersistenceUnitRootUrl() { + try { + return new URL(rootUrl); + } catch (MalformedURLException ex) { + throw new TuscanyJpaException(ex); + } + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getProperties() + */ + public Properties getProperties() { + return getProperties(persistenceDom); + } + + /* (non-Javadoc) + * @see javax.persistence.spi.PersistenceUnitInfo#getTransactionType() + */ + public PersistenceUnitTransactionType getTransactionType() { + String transactionType = getSingleValue(persistenceDom, TRANSACTION_TYPE); + return "JTA".equals(transactionType) ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL; + } + + /* + * Extracts additional properties. + */ + private Properties getProperties(Node root) { + + try { + NodeList nodeList = (NodeList) xpath.evaluate(PROPERTY, root, XPathConstants.NODESET); + Properties data = new Properties(); + + for (int i = 0; i < nodeList.getLength(); i++) { + Element property = (Element) nodeList.item(i); + data.put(property.getAttribute(PROPERTY_NAME), property.getAttribute(PROPERTY_VALUE)); + } + + return data; + } catch (XPathExpressionException ex) { + throw new TuscanyJpaException(ex); + } + + } + + /* + * Gets multiple values for the specified expression. + */ + private List<String> getMultipleValues(Node context, String expression) { + + try { + NodeList nodeList = (NodeList) xpath.evaluate(expression, context, XPathConstants.NODESET); + List<String> data = new LinkedList<String>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + data.add(nodeList.item(i).getTextContent()); + } + + return data; + } catch (XPathExpressionException ex) { + throw new TuscanyJpaException(ex); + } + + } + + /* + * Gets single value for the specified expression. + */ + private String getSingleValue(Node context, String expression) { + + try { + return xpath.evaluate(expression, context); + } catch (XPathExpressionException ex) { + throw new TuscanyJpaException(ex); + } + + } + + /* + * Gets single value for the specified expression. + */ + private boolean getBooleanValue(Node context, String expression) { + return Boolean.valueOf(getSingleValue(context, expression)); + } + + /* + * Looks up datasource. + */ + private DataSource lookupDataSource(String dsName) { + Context ctx = null; + try { + ctx = new InitialContext(); + return (DataSource) ctx.lookup(dsName); + } catch (NamingException ex) { + throw new TuscanyJpaException(ex); + } finally { + if (ctx != null) { + try { + ctx.close(); + } catch (NamingException ex) { + throw new TuscanyJpaException(ex); + } + } + } + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/main/resources/META-INF/sca/jpa.scdl b/sandbox/old/contrib/persistence/common/src/main/resources/META-INF/sca/jpa.scdl new file mode 100644 index 0000000000..1166ade155 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/main/resources/META-INF/sca/jpa.scdl @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<!-- + Default system configuration for the launcher environment. + + $Rev$ $Date$ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://tuscany.apache.org/xmlns/system/1.0-SNAPSHOT" + name="org.apache.tuscany.core.Implementation"> + + <!-- Implementation processor for JPA annotations. --> + <component name="jpa.persistenceUnit"> + <system:implementation.system class="org.apache.tuscany.service.persistence.common.PersistenceUnitProcessor"/> + </component> + + <component name="jpa.persistenceContext"> + <system:implementation.system class="org.apache.tuscany.service.persistence.common.PersistenceContextProcessor"/> + </component> + +</composite> diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilderTestCase.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilderTestCase.java new file mode 100644 index 0000000000..cd3a914ab9 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/DefaultPersistenceUnitBuilderTestCase.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import junit.framework.TestCase; + +public class DefaultPersistenceUnitBuilderTestCase extends TestCase { + + public void testNewEntityManagerFactory() { + new DefaultPersistenceUnitBuilder().newEntityManagerFactory("test", getClass().getClassLoader()); + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Department.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Department.java new file mode 100644 index 0000000000..bbbd32fa87 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Department.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Department { + + @Id + private Long id; + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Employee.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Employee.java new file mode 100644 index 0000000000..d90e3284eb --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/Employee.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private Long id; + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScannerTestCase.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScannerTestCase.java new file mode 100644 index 0000000000..b8d7c53d4d --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitScannerTestCase.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.common; + +import junit.framework.TestCase; + +public class PersistenceUnitScannerTestCase extends TestCase { + + public void testGetPersistenceUnitInfo() { + + new PersistenceUnitScanner().getPersistenceUnitInfo("test", getClass().getClassLoader()); + + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitTestCase.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitTestCase.java new file mode 100644 index 0000000000..6b6fb7ad43 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/PersistenceUnitTestCase.java @@ -0,0 +1,32 @@ +package org.apache.tuscany.service.persistence.common; + +import junit.framework.TestCase; + +public class PersistenceUnitTestCase extends TestCase { + + protected void setUp() throws Exception { +/* + addExtension("tuscany.jpa", getClass().getClassLoader().getResource("META-INF/sca/jpa.scdl")); + addExtension("geronimo.jta", getClass().getClassLoader().getResource("META-INF/sca/geronimo.jta.scdl")); + setApplicationSCDL(getClass().getClassLoader().getResource("META-INF/sca/test1.scdl")); + super.setUp(); + RuntimeComponent runtime = (RuntimeComponent) component.getParent().getParent(); + CompositeComponent systemComposite = runtime.getSystemComponent(); + CompositeComponent topLevelComposite = (CompositeComponent) systemComposite.getSystemChild(TUSCANY_SYSTEM); + + JavaAtomicComponent cmp = (JavaAtomicComponent) component.getChild("TestService1"); + TestService1 testService1 = (TestService1) cmp.getTargetInstance(); + testService1.testMethod(); +*/ + } + + protected void tearDown() throws Exception { +/* + super.tearDown(); +*/ + } + + public void testGetComponent() { + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/TestService1.java b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/TestService1.java new file mode 100644 index 0000000000..74052984b9 --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/java/org/apache/tuscany/service/persistence/common/TestService1.java @@ -0,0 +1,26 @@ +package org.apache.tuscany.service.persistence.common; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.transaction.TransactionManager; + +import org.apache.tuscany.api.annotation.Resource; + +public class TestService1 { + + @Resource + protected TransactionManager tx; + + @PersistenceUnit(unitName = "test") + protected EntityManagerFactory emf; + + public void testMethod() throws Exception { + + tx.begin(); + EntityManager em = emf.createEntityManager(); + tx.commit(); + + } + +} diff --git a/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/persistence.xml b/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..0fc71881db --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + --> +<persistence xmlns="http://java.sun.com/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" + version="1.0"> + <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> + <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider> + <class>org.apache.tuscany.service.persistence.common.Employee</class> + <class>org.apache.tuscany.service.persistence.common.Department</class> + <properties> + <property name="openjpa.ConnectionURL" value="jdbc:hsqldb:tutorial_database"/> + <property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/> + <property name="openjpa.ConnectionUserName" value="sa"/> + <property name="openjpa.ConnectionPassword" value=""/> + <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/> + </properties> + </persistence-unit> +</persistence>
\ No newline at end of file diff --git a/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/sca/test1.scdl b/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/sca/test1.scdl new file mode 100644 index 0000000000..4470ca506e --- /dev/null +++ b/sandbox/old/contrib/persistence/common/src/test/resources/META-INF/sca/test1.scdl @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + name="LocalWireComposite"> + + <component name="TestService1"> + <implementation.java class="org.apache.tuscany.service.persistence.common.TestService1"/> + </component> + +</composite>
\ No newline at end of file diff --git a/sandbox/old/contrib/persistence/datasource/.ruleset b/sandbox/old/contrib/persistence/datasource/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/.ruleset @@ -0,0 +1,190 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<ruleset name="pmd-eclipse"> + <description>PMD Plugin preferences rule set</description> + + + <rule ref="rulesets/basic.xml/BooleanInstantiation"/> + <rule ref="rulesets/basic.xml/CollapsibleIfStatements"/> + <rule ref="rulesets/basic.xml/DoubleCheckedLocking"/> +<!--<rule ref="rulesets/basic.xml/EmptyCatchBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyFinallyBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyIfStmt"/>--> + <rule ref="rulesets/basic.xml/EmptyStatementNotInLoop"/> +<!--<rule ref="rulesets/basic.xml/EmptyStaticInitializer"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySwitchStatements"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySynchronizedBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyTryBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyWhileStmt"/>--> + <rule ref="rulesets/basic.xml/ForLoopShouldBeWhileLoop"/> + <rule ref="rulesets/basic.xml/JumbledIncrementer"/> +<!--<rule ref="rulesets/basic.xml/OverrideBothEqualsAndHashcode"/>--> + <rule ref="rulesets/basic.xml/ReturnFromFinallyBlock"/> + <rule ref="rulesets/basic.xml/UnconditionalIfStatement"/> + <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/> + <rule ref="rulesets/basic.xml/UnnecessaryFinalModifier"/> + <rule ref="rulesets/basic.xml/UnnecessaryReturn"/> +<!--<rule ref="rulesets/basic.xml/UselessOverridingMethod"/>--> + +<!--<rule ref="rulesets/braces.xml/ForLoopsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfElseStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/WhileLoopsMustUseBraces"/>--> + +<!--<rule ref="rulesets/clone.xml/CloneMethodMustImplementCloneable"/>--> +<!--<rule ref="rulesets/clone.xml/CloneThrowsCloneNotSupportedException"/>--> +<!--<rule ref="rulesets/clone.xml/ProperCloneImplementation"/>--> + +<!--<rule ref="rulesets/codesize.xml/CyclomaticComplexity"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveClassLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveParameterList"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessivePublicCount"/>--> +<!--<rule ref="rulesets/codesize.xml/TooManyFields"/>--> + +<rule ref="rulesets/controversial.xml/AssignmentInOperand"/> +<!--<rule ref="rulesets/controversial.xml/AtLeastOneConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/CallSuperInConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/DontImportSun"/>--> +<!--<rule ref="rulesets/controversial.xml/NullAssignment"/>--> +<!--<rule ref="rulesets/controversial.xml/OnlyOneReturn"/>--> +<!--<rule ref="rulesets/controversial.xml/SingularField"/>--> +<!--<rule ref="rulesets/controversial.xml/SuspiciousOctalEscape"/>--> +<!--<rule ref="rulesets/controversial.xml/UnnecessaryConstructor"/>--> +<rule ref="rulesets/controversial.xml/UnnecessaryParentheses"/> +<!--<rule ref="rulesets/controversial.xml/UnusedModifier"/>--> + +<!--<rule ref="rulesets/coupling.xml/CouplingBetweenObjects"/>--> +<!--<rule ref="rulesets/coupling.xml/ExcessiveImports"/>--> +<!--<rule ref="rulesets/coupling.xml/LooseCoupling"/>--> + +<!--<rule ref="rulesets/design.xml/AbstractClassWithoutAbstractMethod"/>--> +<!--<rule ref="rulesets/design.xml/AccessorClassGeneration"/>--> +<!--<rule ref="rulesets/design.xml/AssignmentToNonFinalStatic"/>--> +<!--<rule ref="rulesets/design.xml/AvoidDeeplyNestedIfStmts"/>--> +<!--<rule ref="rulesets/design.xml/AvoidInstanceofChecksInCatchClause"/>--> +<rule ref="rulesets/design.xml/AvoidProtectedFieldInFinalClass"/> +<!--<rule ref="rulesets/design.xml/AvoidReassigningParameters"/>--> +<!--<rule ref="rulesets/design.xml/AvoidSynchronizedAtMethodLevel"/>--> +<!--<rule ref="rulesets/design.xml/BadComparison"/>--> +<!--<rule ref="rulesets/design.xml/CloseConnection"/>--> +<!--<rule ref="rulesets/design.xml/CompareObjectsWithEquals"/>--> +<!--<rule ref="rulesets/design.xml/ConfusingTernary"/>--> +<rule ref="rulesets/design.xml/ConstructorCallsOverridableMethod"/> +<!--<rule ref="rulesets/design.xml/DefaultLabelNotLastInSwitchStmt"/>--> +<!--<rule ref="rulesets/design.xml/FinalFieldCouldBeStatic"/>--> +<rule ref="rulesets/design.xml/IdempotentOperations"/> +<!--<rule ref="rulesets/design.xml/ImmutableField"/>--> +<!--<rule ref="rulesets/design.xml/InstantiationToGetClass"/>--> +<!--<rule ref="rulesets/design.xml/MissingBreakInSwitch"/>--> +<!--<rule ref="rulesets/design.xml/MissingStaticMethodInNonInstantiatableClass"/>--> +<!--<rule ref="rulesets/design.xml/NonCaseLabelInSwitchStatement"/>--> +<!--<rule ref="rulesets/design.xml/NonStaticInitializer"/>--> +<rule ref="rulesets/design.xml/OptimizableToArrayCall"/> +<rule ref="rulesets/design.xml/PositionLiteralsFirstInComparisons"/> +<rule ref="rulesets/design.xml/SimplifyBooleanExpressions"/> +<rule ref="rulesets/design.xml/SimplifyBooleanReturns"/> +<rule ref="rulesets/design.xml/SimplifyConditional"/> +<!--<rule ref="rulesets/design.xml/SwitchDensity"/>--> +<!--<rule ref="rulesets/design.xml/SwitchStmtsShouldHaveDefault"/>--> +<rule ref="rulesets/design.xml/UnnecessaryLocalBeforeReturn"/> +<!--<rule ref="rulesets/design.xml/UseLocaleWithCaseConversions"/>--> +<!--<rule ref="rulesets/design.xml/UseNotifyAllInsteadOfNotify"/>--> +<!--<rule ref="rulesets/design.xml/UseSingleton"/>--> + +<!--<rule ref="rulesets/finalizers.xml/EmptyFinalizer"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOnlyCallsSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOverloaded"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeDoesNotCallSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeShouldBeProtected"/>--> +<!--<rule ref="rulesets/finalizers.xml/AvoidCallingFinalize"/>--> + +<!--<rule ref="rulesets/imports.xml/DuplicateImports"/>--> +<!--<rule ref="rulesets/imports.xml/DontImportJavaLang"/>--> +<!--<rule ref="rulesets/imports.xml/UnusedImports"/>--> +<!--<rule ref="rulesets/imports.xml/ImportFromSamePackage"/>--> + +<!--<rule ref="rulesets/javabeans.xml/BeanMembersShouldSerialize"/>--> +<!--<rule ref="rulesets/javabeans.xml/MissingSerialVersionUID"/>--> + +<!--<rule ref="rulesets/junit.xml/JUnitStaticSuite"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitSpelling"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitAssertionsShouldIncludeMessage"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitTestsShouldIncludeAssert"/>--> +<!--<rule ref="rulesets/junit.xml/TestClassWithoutTestCases"/>--> +<!--<rule ref="rulesets/junit.xml/UnnecessaryBooleanAssertion"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertEqualsInsteadOfAssertTrue"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertSameInsteadOfAssertTrue"/>--> + + <!--<rule ref="rulesets/logging-java.xml/AvoidPrintStackTrace"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/MoreThanOneLogger"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/LogBlockWithoutIf"/>--> + <!--<rule ref="rulesets/logging-java.xml/SystemPrintln"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/UseCorrectExceptionLogging"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/ProperLogger"/>--> + + <!--<rule ref="rulesets/naming.xml/ShortVariable"/>--> + <!--<rule ref="rulesets/naming.xml/LongVariable"/>--> + <!--<rule ref="rulesets/naming.xml/ShortMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/VariableNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/MethodNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/ClassNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/AbstractNaming"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidDollarSigns"/>--> + <!--<rule ref="rulesets/naming.xml/MethodWithSameNameAsEnclosingClass"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousHashcodeMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousConstantFieldName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingTypeName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidNonConstructorMethodsWithClassName"/>--> + <!--<rule ref="rulesets/naming.xml/NoPackage"/>--> + <!--<rule ref="rulesets/naming.xml/PackageCase"/>--> + + <!--<rule ref="rulesets/optimizations.xml/LocalVariableCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/MethodArgumentCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/AvoidInstantiatingObjectsInLoops"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseArrayListInsteadOfVector"/>--> + <!--<rule ref="rulesets/optimizations.xml/SimplifyStartsWith"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseStringBufferForStringAppends"/>--> + + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingThrowable"/>--> + <!--<rule ref="rulesets/strictexception.xml/SignatureDeclareThrowsException"/>--> + <!--<rule ref="rulesets/strictexception.xml/ExceptionAsFlowControl"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingNPE"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingRawExceptionTypes"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingNullPointerException"/>--> + + <!--<rule ref="rulesets/strings.xml/AvoidDuplicateLiterals"/>--> + <!--<rule ref="rulesets/strings.xml/StringInstantiation"/>--> + <!--<rule ref="rulesets/strings.xml/StringToString"/>--> + <!--<rule ref="rulesets/strings.xml/AvoidConcatenatingNonLiteralsInStringBuffer"/>--> + <!--<rule ref="rulesets/strings.xml/UnnecessaryCaseChange"/>--> + + <!--<rule ref="rulesets/sunsecure.xml/MethodReturnsInternalArray"/>--> + <!--<rule ref="rulesets/sunsecure.xml/ArrayIsStoredDirectly"/>--> + + <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/> + <!--<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>--> + +</ruleset> diff --git a/sandbox/old/contrib/persistence/datasource/LICENSE.txt b/sandbox/old/contrib/persistence/datasource/LICENSE.txt new file mode 100755 index 0000000000..0084319535 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/LICENSE.txt @@ -0,0 +1,202 @@ + + 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, serviceDefinition 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. diff --git a/sandbox/old/contrib/persistence/datasource/NOTICE.txt b/sandbox/old/contrib/persistence/datasource/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +Apache Tuscany is an effort undergoing incubation at The Apache Software +Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is +required of all newly accepted projects until a further review indicates that +the infrastructure, communications, and decision making process have stabilized +in a manner consistent with other successful ASF projects. While incubation +status is not necessarily a reflection of the completeness or stability of the +code, it does indicate that the project has yet to be fully endorsed by the ASF. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/old/contrib/persistence/datasource/pom.xml.off b/sandbox/old/contrib/persistence/datasource/pom.xml.off new file mode 100644 index 0000000000..be6d9bf0b9 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/pom.xml.off @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + + <parent> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>persistence-datasource</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany Datasource Extension</name> + <description>A DataSource provider for Tuscany.</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + <dependency> + <groupId>commons-dbcp</groupId> + <artifactId>commons-dbcp</artifactId> + <version>1.2.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>hsqldb</groupId> + <artifactId>hsqldb</artifactId> + <version>1.8.0.7</version> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/AmbiguousPropertyException.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/AmbiguousPropertyException.java new file mode 100644 index 0000000000..40bebc58b6 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/AmbiguousPropertyException.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import org.apache.tuscany.spi.loader.LoaderException; + +/** + * Raised when a property cannot be unambiguously inferred using JavaBean introspection rules, e.g. when a method is + * overloaded. + * + * @version $Rev$ $Date$ + */ +public class AmbiguousPropertyException extends LoaderException { + public AmbiguousPropertyException() { + } + + public AmbiguousPropertyException(String message) { + super(message); + } + + public AmbiguousPropertyException(String message, String identifier) { + super(message, identifier); + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoader.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoader.java new file mode 100644 index 0000000000..326c526adf --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoader.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.net.URI; +import javax.sql.DataSource; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.databinding.extension.SimpleTypeMapperExtension; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentTypeLoaderExtension; +import org.apache.tuscany.spi.model.TypeInfo; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +/** + * Loads the component type for a DataSource component. Component type information is currently static, although this + * could be changed in the future to allow for configuration parameter checking for specific providers. + * + * @version $Rev$ $Date$ + */ +public class DSComponentTypeLoader extends ComponentTypeLoaderExtension<DataSourceImplementation> { + private SimpleTypeMapperExtension extension = new SimpleTypeMapperExtension(); + + public DSComponentTypeLoader(@Reference LoaderRegistry loaderRegistry) { + super(loaderRegistry); + } + + protected Class<DataSourceImplementation> getImplementationClass() { + return DataSourceImplementation.class; + } + + public void load(DataSourceImplementation implementation, DeploymentContext ctx) + throws LoaderException { + ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> componentType = + new ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>>(); + componentType.setImplementationScope(Scope.COMPOSITE); + JavaServiceContract serviceContract = new JavaServiceContract(DataSource.class); + ServiceDefinition service = new ServiceDefinition(URI.create("#DataSource"), serviceContract, false); + componentType.add(service); + componentType.setInitLevel(1); + Class<?> provider; + try { + provider = implementation.getClassLoader().loadClass(implementation.getProviderName()); + } catch (ClassNotFoundException e) { + throw new LoaderException(e); + } + introspectProperties(componentType, provider); + implementation.setComponentType(componentType); + } + + /** + * Creates properties by introspecting the provider class an d including all JavaBean setters that take a simple + * type parameter + * + * @param componentType + * @param provider + * @throws AmbiguousPropertyException + */ + @SuppressWarnings("unchecked") + private void introspectProperties(ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> componentType, + Class<?> provider) throws AmbiguousPropertyException { + + Method[] methods = provider.getMethods(); + for (Method method : methods) { + String name = method.getName(); + if (method.getParameterTypes().length == 1 && name.startsWith("set")) { + String propName = Character.toLowerCase(name.charAt(3)) + name.substring(4); + Class<Type> type = (Class<Type>) method.getParameterTypes()[0]; + TypeInfo info = extension.getXMLType(type); + if (info != null) { + // only include methods as properties that take simple type parameters + if (componentType.getProperties().containsKey(propName)) { + throw new AmbiguousPropertyException(propName); + } + JavaMappedProperty<Type> property = + new JavaMappedProperty<Type>(propName, info.getQName(), type); + property.setMember(method); + componentType.add(property); + } + } + } + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceBuilder.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceBuilder.java new file mode 100644 index 0000000000..50f87d07f5 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceBuilder.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.PropertyValue; + +/** + * Builds a {@link DataSourceComponent} from its model representation + * + * @version $Rev$ $Date$ + */ +public class DataSourceBuilder extends ComponentBuilderExtension<DataSourceImplementation> { + protected Class<DataSourceImplementation> getImplementationType() { + return DataSourceImplementation.class; + } + + public Component build(ComponentDefinition<DataSourceImplementation> definition, + DeploymentContext deploymentContext) throws BuilderConfigException { + try { + DataSourceImplementation implementation = definition.getImplementation(); + ClassLoader classLoader = implementation.getClassLoader(); + Class<?> beanClass = classLoader.loadClass(implementation.getProviderName()); + List<Injector> injectors = new ArrayList<Injector>(); + // handle properties + ComponentType type = definition.getImplementation().getComponentType(); + for (PropertyValue<?> property : definition.getPropertyValues().values()) { + ObjectFactory<?> factory = property.getValueFactory(); + if (factory != null) { + String name = property.getName(); + JavaMappedProperty mappedProperty = (JavaMappedProperty) type.getProperties().get(name); + if (mappedProperty == null) { + throw new MissingPropertyException(name); + } + Injector injector = new Injector((Method) mappedProperty.getMember(), factory); + injectors.add(injector); + } + } + ProviderObjectFactory providerFactory = new ProviderObjectFactory(beanClass, injectors); + int initLevel = implementation.getComponentType().getInitLevel(); + return new DataSourceComponent(definition.getUri(), providerFactory, initLevel); + } catch (ClassNotFoundException e) { + throw new BuilderConfigException(e); + } + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceCloseException.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceCloseException.java new file mode 100644 index 0000000000..3398c47913 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceCloseException.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import org.apache.tuscany.spi.component.TargetDestructionException; + +/** + * @version $Rev$ $Date$ + */ +public class DataSourceCloseException extends TargetDestructionException { + + public DataSourceCloseException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceComponent.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceComponent.java new file mode 100644 index 0000000000..c73fce31ef --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceComponent.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.net.URI; +import java.util.List; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.component.InstanceWrapper; +import org.apache.tuscany.spi.component.TargetDestructionException; +import org.apache.tuscany.spi.component.TargetInvokerCreationException; +import org.apache.tuscany.spi.component.TargetResolutionException; +import org.apache.tuscany.spi.extension.AtomicComponentExtension; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.physical.PhysicalOperationDefinition; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.Wire; + +/** + * A system component that creates <code>DataSource</code> instances. The component uses a {@link ProviderObjectFactory} + * to instantiate the actual <code>DataSource</code> + * + * @version $Rev$ $Date$ + */ +public class DataSourceComponent extends AtomicComponentExtension { + private ProviderObjectFactory instanceFactory; + + /** + * Creates a <code>DataSourceComponent</code> + * + * @param uri the uri of the component + * @param instanceFactory the provider factory + * @param initLevel the initialization level + */ + public DataSourceComponent(URI uri, + ProviderObjectFactory instanceFactory, + int initLevel) { + + super(uri, null, null, initLevel, -1, -1); + this.instanceFactory = instanceFactory; + } + + public InstanceWrapper<?> createInstanceWrapper() throws ObjectCreationException { + return null; + } + + public Object createInstance() throws ObjectCreationException { + return instanceFactory.getInstance(); + } + + public Object getTargetInstance() throws TargetResolutionException { + return null; + } + + + public Object getAssociatedTargetInstance() throws TargetResolutionException { + return null; + } + + public void destroy(Object instance) throws TargetDestructionException { + if (instance instanceof DataSourceProvider) { + try { + ((DataSourceProvider) instance).close(); + } catch (ProviderException e) { + throw new DataSourceCloseException("Error closing data source provider", e); + } + } + } + + public List<Wire> getWires(String name) { + return null; + } + + public void attachCallbackWire(Wire wire) { + + } + + public void attachWire(Wire wire) { + + } + + public void attachWires(List<Wire> wires) { + + } + + public TargetInvoker createTargetInvoker(String targetName, Operation operation) + throws TargetInvokerCreationException { + return null; + } + + public TargetInvoker createTargetInvoker(String targetName, PhysicalOperationDefinition operation) + throws TargetInvokerCreationException { + return null; + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementation.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementation.java new file mode 100644 index 0000000000..d0e3413ca8 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementation.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Implementation; + +/** + * Represents a DataSource component implementation + * + * @version $Rev$ $Date$ + */ +public class DataSourceImplementation extends Implementation<ComponentType> { + private String providerName; + private ClassLoader classLoader; + private Map<String, String> configurationParams = new HashMap<String, String>(); + + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public ClassLoader getClassLoader() { + return classLoader; + } + + public void setClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + public Map<String, String> getConfigurationParams() { + return configurationParams; + } + + public void addConfigurationParam(String name, String val) { + this.configurationParams.put(name, val); + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoader.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoader.java new file mode 100644 index 0000000000..4401b0f087 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoader.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.LoaderUtil; +import org.apache.tuscany.spi.model.ModelObject; + +/** + * Loads a DataSource component type from an assembly. This component implementation type provides a + * <code>DataSource</code> system service in the runtime. The actual DataSource provider is pluggable, for example, + * Commons DBCP could be used. DataSource components are configured as follows: + * <pre> + * <p/> + * <component name="MyDataSource"> + * <system:implementation.ds provider="org.foo.FooProvider"/> + * <property name="driverClassName">com.mysql.jdbc.Driver</property> + * <property name="url">jdbc:mysql://localhost:3306/mydb</property> + * <property name="login">foo</property> + * <property name="password">bar</property> + * </component> + * <p/> + * </pre> + * In the above example, <code>org.foo.FooProvider</code> is responsible for bootstrapping the actual DataSource + * implementation. It may implement <code>javax.sql.DataSource</code> directly or the {@link DataSourceProvider} + * interface and must have a public no-args constructor. Configuration parameters are simple types specified as + * properties. Configuration parameters, i.e. properties, will vary are introspected from the provider class. A + * component type containing thse properties is dynamically generated and consists of all JavaBean setter methods that + * take a single simple type parameter. + * + * @version $Rev$ $Date$ + */ +public class DataSourceImplementationLoader extends LoaderExtension { + private static final QName DATASOURCE = + new QName("http://tuscany.apache.org/xmlns/system/1.0-SNAPSHOT", "implementation.ds"); + private static final String PROVIDER = "provider"; + + public DataSourceImplementationLoader(@Reference LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return DATASOURCE; + } + + public ModelObject load( + ModelObject object, + XMLStreamReader reader, + DeploymentContext deploymentContext) throws XMLStreamException, LoaderException { + String driverName = reader.getAttributeValue(null, PROVIDER); + if (driverName == null) { + throw new LoaderException("No provider specified for DataSource"); + } + + DataSourceImplementation implementation = new DataSourceImplementation(); + implementation.setProviderName(driverName); + implementation.setClassLoader(deploymentContext.getClassLoader()); + LoaderUtil.skipToEndElement(reader); + return implementation; + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceProvider.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceProvider.java new file mode 100644 index 0000000000..d29089be6d --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/DataSourceProvider.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import javax.sql.DataSource; + +/** + * DataSource providers may optionally implement this interface to receive callback notifications + * + * @version $Rev$ $Date$ + */ +public interface DataSourceProvider { + + /** + * Signals to the provider to initialize after all parameters have been set + * + * @throws ProviderException if an exception occurs during initialization + */ + void init() throws ProviderException; + + /** + * Signals to the provider to close any open resources and prepare for shutdown + * + * @throws ProviderException if an exception occurs during shutdown + */ + void close() throws ProviderException; + + /** + * Returns a new <code>DataSource</code> instance that will be bound into a composite system service tree. Called + * after initialize. + * + * @throws ProviderException if an error occurs creating a new instance + */ + DataSource getDataSource() throws ProviderException; + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/Injector.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/Injector.java new file mode 100644 index 0000000000..82903afe93 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/Injector.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.ObjectFactory; + +/** + * Injects a value on a method + * + * @version $Rev$ $Date$ + */ +public class Injector { + private final Method method; + private final ObjectFactory<?> objectFactory; + + public Injector(Method method, ObjectFactory<?> objectFactory) { + this.method = method; + this.method.setAccessible(true); + this.objectFactory = objectFactory; + } + + public void inject(Object instance) throws IllegalAccessException, InvocationTargetException { + method.invoke(instance, objectFactory.getInstance()); + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/MissingPropertyException.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/MissingPropertyException.java new file mode 100644 index 0000000000..ac5a8a0b55 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/MissingPropertyException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import org.apache.tuscany.spi.builder.BuilderConfigException; + +/** + * Raised when a property value is specified in an assembly configuration and no corresponding property was found in the + * component type + * + * @version $Rev$ $Date$ + */ +public class MissingPropertyException extends BuilderConfigException { + public MissingPropertyException() { + } + + public MissingPropertyException(String message) { + super(message); + } + + public MissingPropertyException(String message, Throwable cause) { + super(message, cause); + } + + public MissingPropertyException(Throwable cause) { + super(cause); + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderException.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderException.java new file mode 100644 index 0000000000..8ffc24eaab --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderException.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import org.apache.tuscany.api.TuscanyException; + +/** + * Denotes an error during a provider callback + * + * @version $Rev$ $Date$ + */ +public class ProviderException extends TuscanyException { + + public ProviderException(String message, String identifier) { + super(message, identifier); + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactory.java b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactory.java new file mode 100644 index 0000000000..9422a96cdd --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactory.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; + +/** + * Responsible for instantiating a DataSource provider class and initializing the actual <code>DataSource</code> . It + * must have a no-args constructor and may optionally implement {@link DataSourceProvider}. If it does not implement + * <code>DataSourceProvider</code>, then the provider class must implement the <code>DataSource<code> interface. A + * collection of {@link Injector}s is used to inject the provider instance with configuration parameters. + * + * @version $Rev$ $Date$ + */ +public class ProviderObjectFactory implements ObjectFactory<DataSource> { + private Class<?> providerClass; + private List<Injector> injectors; + + public ProviderObjectFactory(Class<?> providerClass, List<Injector> injectors) { + assert providerClass != null; + assert injectors != null; + this.providerClass = providerClass; + this.injectors = injectors; + } + + public DataSource getInstance() throws ObjectCreationException { + try { + Object instance = providerClass.newInstance(); + for (Injector injector : injectors) { + injector.inject(instance); + } + if (instance instanceof DataSourceProvider) { + DataSourceProvider dataSourceProvider = (DataSourceProvider) instance; + try { + dataSourceProvider.init(); + return dataSourceProvider.getDataSource(); + } catch (ProviderException e) { + throw new ObjectCreationException(e); + } + } else { + return (DataSource) instance; + } + } catch (InstantiationException e) { + throw new ObjectCreationException(e); + } catch (IllegalAccessException e) { + throw new ObjectCreationException(e); + } catch (InvocationTargetException e) { + throw new ObjectCreationException(e); + } + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/main/resources/META-INF/sca/dataSource.scdl b/sandbox/old/contrib/persistence/datasource/src/main/resources/META-INF/sca/dataSource.scdl new file mode 100644 index 0000000000..df0375b2dc --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/main/resources/META-INF/sca/dataSource.scdl @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<!-- + Configuration for DataSource support. + + $Rev: 440909 $ $Date: 2006-09-06 17:07:19 -0700 (Wed, 06 Sep 2006) $ +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://tuscany.apache.org/xmlns/system/1.0-SNAPSHOT" + name="org.apache.tuscany.persistence.datasource" + autowire="true"> + + <component name="datasource.dataSourceBuilder"> + <system:implementation.system class="org.apache.tuscany.persistence.datasource.DataSourceBuilder"/> + </component> + <component name="datasource.dsComponentTypeLoader"> + <system:implementation.system class="org.apache.tuscany.persistence.datasource.DSComponentTypeLoader"/> + </component> + <component name="datasource.datasourceLoader"> + <system:implementation.system class="org.apache.tuscany.persistence.datasource.DataSourceImplementationLoader"/> + </component> +</composite> diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoaderTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoaderTestCase.java new file mode 100644 index 0000000000..87c12db9bf --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DSComponentTypeLoaderTestCase.java @@ -0,0 +1,88 @@ +package org.apache.tuscany.persistence.datasource; + +import javax.sql.DataSource; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.model.ComponentType; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class DSComponentTypeLoaderTestCase extends TestCase { + + public void testIntrospection() throws Exception { + DSComponentTypeLoader loader = new DSComponentTypeLoader(null); + DataSourceImplementation implementation = new DataSourceImplementation(); + implementation.setProviderName(Foo.class.getName()); + implementation.setClassLoader(getClass().getClassLoader()); + loader.load(implementation, null); + ComponentType<?, ?, ?> type = implementation.getComponentType(); + assertEquals(2, type.getProperties().size()); + assertNull(type.getProperties().get("object")); + Object bar = type.getProperties().get("bar"); + assertEquals(String.class, ((JavaMappedProperty) bar).getJavaType()); + Object baz = type.getProperties().get("baz"); + assertEquals(Integer.TYPE, ((JavaMappedProperty) baz).getJavaType()); + assertEquals(1, type.getServices().size()); + assertEquals(DataSource.class, type.getServices().get("DataSource").getServiceContract().getInterfaceClass()); + } + + + public void testOverloadedMethod() throws Exception { + DSComponentTypeLoader loader = new DSComponentTypeLoader(null); + DataSourceImplementation implementation = new DataSourceImplementation(); + implementation.setProviderName(BadFoo.class.getName()); + implementation.setClassLoader(getClass().getClassLoader()); + try { + loader.load(implementation, null); + fail(); + } catch (AmbiguousPropertyException e) { + // expected + } + } + + public class Foo { + + private String bar; + + private int baz; + + private Foo object; + + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public int getBaz() { + return baz; + } + + public void setBaz(int baz) { + this.baz = baz; + } + + public Foo getObject() { + return object; + } + + public void setObject(Foo object) { + this.object = object; + } + } + + public class BadFoo { + + public void setBar(String bar) { + } + + public void setBar(Object bar) { + } + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceBuilderTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceBuilderTestCase.java new file mode 100644 index 0000000000..c7daaa6e4d --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceBuilderTestCase.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.net.URI; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class DataSourceBuilderTestCase extends TestCase { + + public void testBuild() throws Exception { + ScopeContainer scope = EasyMock.createMock(ScopeContainer.class); + EasyMock.replay(scope); + DeploymentContext ctx = EasyMock.createMock(DeploymentContext.class); + EasyMock.replay(ctx); + + DataSourceImplementation implementation = new DataSourceImplementation(); + ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> componentType = + new ComponentType<ServiceDefinition, ReferenceDefinition, Property<?>>(); + JavaServiceContract serviceContract = new JavaServiceContract(DataSource.class); + ServiceDefinition service = new ServiceDefinition(URI.create("DataSource"), serviceContract, false); + componentType.add(service); + componentType.setInitLevel(1); + implementation.setComponentType(componentType); + implementation.setProviderName(MockProvider.class.getName()); + implementation.setClassLoader(getClass().getClassLoader()); + + ComponentDefinition<DataSourceImplementation> def = + new ComponentDefinition<DataSourceImplementation>(URI.create("MyDS"), implementation); + + DataSourceBuilder builder = new DataSourceBuilder(); + + DataSourceComponent component = (DataSourceComponent) builder.build(def, ctx); + assertEquals(URI.create("MyDS"), component.getUri()); + + DataSource ds = (DataSource) component.createInstance(); + assertNotNull(ds); + EasyMock.verify(ctx); + EasyMock.verify(scope); + } + + private static class MockProvider implements DataSourceProvider { + + public MockProvider() { + } + + public void init() throws ProviderException { + + } + + public void close() throws ProviderException { + + } + + public DataSource getDataSource() throws ProviderException { + return EasyMock.createNiceMock(DataSource.class); + } + } + + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceComponentTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceComponentTestCase.java new file mode 100644 index 0000000000..e95c1c4123 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceComponentTestCase.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.net.URI; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class DataSourceComponentTestCase extends TestCase { + + public void testDestroy() throws Exception { + DataSourceProvider provider = EasyMock.createMock(DataSourceProvider.class); + provider.close(); + EasyMock.replay(provider); + DataSourceComponent component = new DataSourceComponent(URI.create("ds"), null, 0); + component.destroy(provider); + EasyMock.verify(provider); + } + + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoaderTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoaderTestCase.java new file mode 100644 index 0000000000..49c83bacc7 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/DataSourceImplementationLoaderTestCase.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class DataSourceImplementationLoaderTestCase extends TestCase { + + public void testLoadingNoParameters() throws Exception { + LoaderRegistry registry = EasyMock.createNiceMock(LoaderRegistry.class); + EasyMock.replay(registry); + DataSourceImplementationLoader loader = new DataSourceImplementationLoader(registry); + XMLStreamReader reader = EasyMock.createMock(XMLStreamReader.class); + EasyMock.expect(reader.getAttributeValue(null, "provider")).andReturn("org.foo.MyDriver"); + EasyMock.expect(reader.next()).andReturn(END_ELEMENT); + EasyMock.replay(reader); + DeploymentContext ctx = EasyMock.createMock(DeploymentContext.class); + EasyMock.expect(ctx.getClassLoader()).andReturn(getClass().getClassLoader()); + EasyMock.replay(ctx); + DataSourceImplementation implementation = (DataSourceImplementation) loader.load(null, reader, ctx); + assertEquals("org.foo.MyDriver", implementation.getProviderName()); + assertEquals(getClass().getClassLoader(), implementation.getClassLoader()); + EasyMock.verify(reader); + EasyMock.verify(ctx); + } + + public void testNoDriverName() throws Exception { + LoaderRegistry registry = EasyMock.createNiceMock(LoaderRegistry.class); + EasyMock.replay(registry); + DataSourceImplementationLoader loader = new DataSourceImplementationLoader(registry); + XMLStreamReader reader = EasyMock.createMock(XMLStreamReader.class); + EasyMock.expect(reader.getAttributeValue(null, "provider")).andReturn(null); + EasyMock.replay(reader); + try { + loader.load(null, reader, null); + fail(); + } catch (LoaderException e) { + // expected + } + EasyMock.verify(reader); + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/InjectorTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/InjectorTestCase.java new file mode 100644 index 0000000000..8d5a6f06a4 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/InjectorTestCase.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.ObjectFactory; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class InjectorTestCase extends TestCase { + + @SuppressWarnings("unchecked") + public void testInject() throws Exception { + Method m = Foo.class.getMethod("setVal", String.class); + ObjectFactory factory = EasyMock.createMock(ObjectFactory.class); + EasyMock.expect(factory.getInstance()).andReturn("foo"); + EasyMock.replay(factory); + Injector injector = new Injector(m, factory); + Foo foo = new Foo(); + injector.inject(foo); + assertEquals("foo", foo.val); + EasyMock.verify(factory); + } + + private class Foo { + private String val; + + public void setVal(String val) { + this.val = val; + } + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactoryTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactoryTestCase.java new file mode 100644 index 0000000000..d335dcc4d1 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/ProviderObjectFactoryTestCase.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource; + +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class ProviderObjectFactoryTestCase extends TestCase { + + public void testInstantiation() throws Exception { + List<Injector> injectors = new ArrayList<Injector>(); + Method m = Provider.class.getMethod("setVal", Integer.TYPE); + injectors.add(new Injector(m, new MockFactory(1))); + ProviderObjectFactory factory = new ProviderObjectFactory(Provider.class, injectors); + DataSource ds = factory.getInstance(); + Provider provider = (Provider) ds; + assertEquals(1, provider.getVal()); + } + + public void testInitInstantiation() throws Exception { + List<Injector> injectors = new ArrayList<Injector>(); + Method m = DSProvider.class.getMethod("setVal", Integer.TYPE); + injectors.add(new Injector(m, new MockFactory(1))); + ProviderObjectFactory factory = new ProviderObjectFactory(DSProvider.class, injectors); + assertNotNull(factory.getInstance()); + + } + + public static class Provider implements DataSource { + private int val; + + public Provider() { + } + + public int getVal() { + return val; + } + + public void setVal(int val) { + this.val = val; + } + + public Connection getConnection() throws SQLException { + return null; + } + + public Connection getConnection(String username, String password) throws SQLException { + return null; + } + + public PrintWriter getLogWriter() throws SQLException { + return null; + } + + public void setLogWriter(PrintWriter out) throws SQLException { + + } + + public void setLoginTimeout(int seconds) throws SQLException { + + } + + public int getLoginTimeout() throws SQLException { + return 0; + } + } + + public static class DSProvider implements DataSourceProvider { + private int val; + private boolean initialized; + + public DSProvider() { + } + + public int getVal() { + return val; + } + + public void setVal(int val) { + this.val = val; + } + + public boolean isInitialized() { + return initialized; + } + + public void init() { + if (val != 1) { + fail(); + } + initialized = true; + } + + + public void close() { + + } + + public DataSource getDataSource() throws ProviderException { + if (!initialized) { + fail(); + } + return EasyMock.createNiceMock(DataSource.class); + } + } + + private class MockFactory implements ObjectFactory<Integer> { + private Integer instance; + + public MockFactory(Integer instance) { + this.instance = instance; + } + + public Integer getInstance() throws ObjectCreationException { + return instance; + } + } + + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/DHCPBootstrapTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/DHCPBootstrapTestCase.java new file mode 100644 index 0000000000..a94ab25f3b --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/DHCPBootstrapTestCase.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource.integration; + +import java.net.URL; +import java.sql.Connection; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.AtomicComponent; + +import junit.framework.TestCase; + +/** + * Verifies bootstrapping of a datasource implementation using Commons DBCP and HSQLDB + * + * @version $Rev$ $Date$ + */ +public class DHCPBootstrapTestCase extends TestCase { + + public void testBasicConnection() throws Exception { +// DataSource ds = (DataSource) ((AtomicComponent) component.getSystemChild("TestDS")).getTargetInstance(); +// assertNotNull(ds); +// Connection conn = ds.getConnection(); +// conn.createStatement().execute("CREATE TABLE foo (bar char(20));"); + } + + protected void setUp() throws Exception { +// URL url = getClass().getResource("/META-INF/sca/dataSource.scdl"); +// addExtension("DataSourceExtension", url); +// setApplicationSCDL(getClass().getResource("/META-INF/sca/dbcp.scdl")); +// super.setUp(); + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/ProviderBootstrapTestCase.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/ProviderBootstrapTestCase.java new file mode 100644 index 0000000000..23dab05e65 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/ProviderBootstrapTestCase.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource.integration; + +import java.net.URL; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.AtomicComponent; + +import org.apache.tuscany.persistence.datasource.integration.mock.Provider; +import junit.framework.TestCase; + +/** + * Verifies bootstrapping of a datasource implementation as a system service in an application composite using a mock + * Provider + * + * @version $Rev$ $Date$ + */ +public class ProviderBootstrapTestCase extends TestCase { + + public void testBoot() throws Exception { +// DataSource ds = (DataSource) ((AtomicComponent)component.getSystemChild("TestDS")).getTargetInstance(); +// assertNotNull(ds); +// assertEquals("value", ((Provider) ds).getTest()); + } + + protected void setUp() throws Exception { +// URL url = getClass().getResource("/META-INF/sca/dataSource.scdl"); +// addExtension("DataSourceExtension", url); +// setApplicationSCDL(getClass().getResource("/META-INF/sca/provider.scdl")); + super.setUp(); + } + +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/mock/Provider.java b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/mock/Provider.java new file mode 100644 index 0000000000..558b73e700 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/java/org/apache/tuscany/persistence/datasource/integration/mock/Provider.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.datasource.integration.mock; + +import java.sql.Connection; +import java.sql.SQLException; +import java.io.PrintWriter; +import javax.sql.DataSource; + +import org.apache.tuscany.persistence.datasource.DataSourceProvider; +import org.apache.tuscany.persistence.datasource.ProviderException; + +/** + * @version $Rev$ $Date$ + */ +public class Provider implements DataSourceProvider, DataSource { + + private String test; + + public void setTest(String test) { + this.test = test; + } + + public String getTest() { + return test; + } + + public void init() throws ProviderException { + + } + + public void close() throws ProviderException { + + } + + public DataSource getDataSource() throws ProviderException { + return this; + } + + public Connection getConnection() throws SQLException { + return null; + } + + public Connection getConnection(String username, String password) throws SQLException { + return null; + } + + public PrintWriter getLogWriter() throws SQLException { + return null; + } + + public void setLogWriter(PrintWriter out) throws SQLException { + + } + + public void setLoginTimeout(int seconds) throws SQLException { + + } + + public int getLoginTimeout() throws SQLException { + return 0; + } +} diff --git a/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/dbcp.scdl b/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/dbcp.scdl new file mode 100644 index 0000000000..6cdc7102fa --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/dbcp.scdl @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://tuscany.apache.org/xmlns/system/1.0-SNAPSHOT" + name="bootTest"> + + <component name="TestDS"> + <system:implementation.ds provider="org.apache.commons.dbcp.BasicDataSource"/> + <property name="driverClassName">org.hsqldb.jdbcDriver</property> + <property name="url">jdbc:hsqldb:mem:testdb</property> + </component> + +</composite> diff --git a/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/provider.scdl b/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/provider.scdl new file mode 100644 index 0000000000..0dc4c866b1 --- /dev/null +++ b/sandbox/old/contrib/persistence/datasource/src/test/resources/META-INF/sca/provider.scdl @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<composite xmlns="http://www.osoa.org/xmlns/sca/1.0" + xmlns:system="http://tuscany.apache.org/xmlns/system/1.0-SNAPSHOT" + name="bootTest"> + + <component name="TestDS"> + <system:implementation.ds provider="org.apache.tuscany.persistence.datasource.integration.mock.Provider"/> + <property name="test">value</property> + <property name="loginTimeout">1</property> + </component> + +</composite> diff --git a/sandbox/old/contrib/persistence/openjpa/.ruleset b/sandbox/old/contrib/persistence/openjpa/.ruleset new file mode 100644 index 0000000000..3886f07f2d --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/.ruleset @@ -0,0 +1,190 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<ruleset name="pmd-eclipse"> + <description>PMD Plugin preferences rule set</description> + + + <rule ref="rulesets/basic.xml/BooleanInstantiation"/> + <rule ref="rulesets/basic.xml/CollapsibleIfStatements"/> + <rule ref="rulesets/basic.xml/DoubleCheckedLocking"/> +<!--<rule ref="rulesets/basic.xml/EmptyCatchBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyFinallyBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyIfStmt"/>--> + <rule ref="rulesets/basic.xml/EmptyStatementNotInLoop"/> +<!--<rule ref="rulesets/basic.xml/EmptyStaticInitializer"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySwitchStatements"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySynchronizedBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyTryBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyWhileStmt"/>--> + <rule ref="rulesets/basic.xml/ForLoopShouldBeWhileLoop"/> + <rule ref="rulesets/basic.xml/JumbledIncrementer"/> +<!--<rule ref="rulesets/basic.xml/OverrideBothEqualsAndHashcode"/>--> + <rule ref="rulesets/basic.xml/ReturnFromFinallyBlock"/> + <rule ref="rulesets/basic.xml/UnconditionalIfStatement"/> + <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/> + <rule ref="rulesets/basic.xml/UnnecessaryFinalModifier"/> + <rule ref="rulesets/basic.xml/UnnecessaryReturn"/> +<!--<rule ref="rulesets/basic.xml/UselessOverridingMethod"/>--> + +<!--<rule ref="rulesets/braces.xml/ForLoopsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfElseStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/WhileLoopsMustUseBraces"/>--> + +<!--<rule ref="rulesets/clone.xml/CloneMethodMustImplementCloneable"/>--> +<!--<rule ref="rulesets/clone.xml/CloneThrowsCloneNotSupportedException"/>--> +<!--<rule ref="rulesets/clone.xml/ProperCloneImplementation"/>--> + +<!--<rule ref="rulesets/codesize.xml/CyclomaticComplexity"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveClassLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveParameterList"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessivePublicCount"/>--> +<!--<rule ref="rulesets/codesize.xml/TooManyFields"/>--> + +<rule ref="rulesets/controversial.xml/AssignmentInOperand"/> +<!--<rule ref="rulesets/controversial.xml/AtLeastOneConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/CallSuperInConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/DontImportSun"/>--> +<!--<rule ref="rulesets/controversial.xml/NullAssignment"/>--> +<!--<rule ref="rulesets/controversial.xml/OnlyOneReturn"/>--> +<!--<rule ref="rulesets/controversial.xml/SingularField"/>--> +<!--<rule ref="rulesets/controversial.xml/SuspiciousOctalEscape"/>--> +<!--<rule ref="rulesets/controversial.xml/UnnecessaryConstructor"/>--> +<rule ref="rulesets/controversial.xml/UnnecessaryParentheses"/> +<!--<rule ref="rulesets/controversial.xml/UnusedModifier"/>--> + +<!--<rule ref="rulesets/coupling.xml/CouplingBetweenObjects"/>--> +<!--<rule ref="rulesets/coupling.xml/ExcessiveImports"/>--> +<!--<rule ref="rulesets/coupling.xml/LooseCoupling"/>--> + +<!--<rule ref="rulesets/design.xml/AbstractClassWithoutAbstractMethod"/>--> +<!--<rule ref="rulesets/design.xml/AccessorClassGeneration"/>--> +<!--<rule ref="rulesets/design.xml/AssignmentToNonFinalStatic"/>--> +<!--<rule ref="rulesets/design.xml/AvoidDeeplyNestedIfStmts"/>--> +<!--<rule ref="rulesets/design.xml/AvoidInstanceofChecksInCatchClause"/>--> +<rule ref="rulesets/design.xml/AvoidProtectedFieldInFinalClass"/> +<!--<rule ref="rulesets/design.xml/AvoidReassigningParameters"/>--> +<!--<rule ref="rulesets/design.xml/AvoidSynchronizedAtMethodLevel"/>--> +<!--<rule ref="rulesets/design.xml/BadComparison"/>--> +<!--<rule ref="rulesets/design.xml/CloseConnection"/>--> +<!--<rule ref="rulesets/design.xml/CompareObjectsWithEquals"/>--> +<!--<rule ref="rulesets/design.xml/ConfusingTernary"/>--> +<rule ref="rulesets/design.xml/ConstructorCallsOverridableMethod"/> +<!--<rule ref="rulesets/design.xml/DefaultLabelNotLastInSwitchStmt"/>--> +<!--<rule ref="rulesets/design.xml/FinalFieldCouldBeStatic"/>--> +<rule ref="rulesets/design.xml/IdempotentOperations"/> +<!--<rule ref="rulesets/design.xml/ImmutableField"/>--> +<!--<rule ref="rulesets/design.xml/InstantiationToGetClass"/>--> +<!--<rule ref="rulesets/design.xml/MissingBreakInSwitch"/>--> +<!--<rule ref="rulesets/design.xml/MissingStaticMethodInNonInstantiatableClass"/>--> +<!--<rule ref="rulesets/design.xml/NonCaseLabelInSwitchStatement"/>--> +<!--<rule ref="rulesets/design.xml/NonStaticInitializer"/>--> +<rule ref="rulesets/design.xml/OptimizableToArrayCall"/> +<rule ref="rulesets/design.xml/PositionLiteralsFirstInComparisons"/> +<rule ref="rulesets/design.xml/SimplifyBooleanExpressions"/> +<rule ref="rulesets/design.xml/SimplifyBooleanReturns"/> +<rule ref="rulesets/design.xml/SimplifyConditional"/> +<!--<rule ref="rulesets/design.xml/SwitchDensity"/>--> +<!--<rule ref="rulesets/design.xml/SwitchStmtsShouldHaveDefault"/>--> +<rule ref="rulesets/design.xml/UnnecessaryLocalBeforeReturn"/> +<!--<rule ref="rulesets/design.xml/UseLocaleWithCaseConversions"/>--> +<!--<rule ref="rulesets/design.xml/UseNotifyAllInsteadOfNotify"/>--> +<!--<rule ref="rulesets/design.xml/UseSingleton"/>--> + +<!--<rule ref="rulesets/finalizers.xml/EmptyFinalizer"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOnlyCallsSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOverloaded"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeDoesNotCallSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeShouldBeProtected"/>--> +<!--<rule ref="rulesets/finalizers.xml/AvoidCallingFinalize"/>--> + +<!--<rule ref="rulesets/imports.xml/DuplicateImports"/>--> +<!--<rule ref="rulesets/imports.xml/DontImportJavaLang"/>--> +<!--<rule ref="rulesets/imports.xml/UnusedImports"/>--> +<!--<rule ref="rulesets/imports.xml/ImportFromSamePackage"/>--> + +<!--<rule ref="rulesets/javabeans.xml/BeanMembersShouldSerialize"/>--> +<!--<rule ref="rulesets/javabeans.xml/MissingSerialVersionUID"/>--> + +<!--<rule ref="rulesets/junit.xml/JUnitStaticSuite"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitSpelling"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitAssertionsShouldIncludeMessage"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitTestsShouldIncludeAssert"/>--> +<!--<rule ref="rulesets/junit.xml/TestClassWithoutTestCases"/>--> +<!--<rule ref="rulesets/junit.xml/UnnecessaryBooleanAssertion"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertEqualsInsteadOfAssertTrue"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertSameInsteadOfAssertTrue"/>--> + + <!--<rule ref="rulesets/logging-java.xml/AvoidPrintStackTrace"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/MoreThanOneLogger"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/LogBlockWithoutIf"/>--> + <!--<rule ref="rulesets/logging-java.xml/SystemPrintln"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/UseCorrectExceptionLogging"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/ProperLogger"/>--> + + <!--<rule ref="rulesets/naming.xml/ShortVariable"/>--> + <!--<rule ref="rulesets/naming.xml/LongVariable"/>--> + <!--<rule ref="rulesets/naming.xml/ShortMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/VariableNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/MethodNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/ClassNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/AbstractNaming"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidDollarSigns"/>--> + <!--<rule ref="rulesets/naming.xml/MethodWithSameNameAsEnclosingClass"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousHashcodeMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousConstantFieldName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingTypeName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidNonConstructorMethodsWithClassName"/>--> + <!--<rule ref="rulesets/naming.xml/NoPackage"/>--> + <!--<rule ref="rulesets/naming.xml/PackageCase"/>--> + + <!--<rule ref="rulesets/optimizations.xml/LocalVariableCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/MethodArgumentCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/AvoidInstantiatingObjectsInLoops"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseArrayListInsteadOfVector"/>--> + <!--<rule ref="rulesets/optimizations.xml/SimplifyStartsWith"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseStringBufferForStringAppends"/>--> + + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingThrowable"/>--> + <!--<rule ref="rulesets/strictexception.xml/SignatureDeclareThrowsException"/>--> + <!--<rule ref="rulesets/strictexception.xml/ExceptionAsFlowControl"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingNPE"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingRawExceptionTypes"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingNullPointerException"/>--> + + <!--<rule ref="rulesets/strings.xml/AvoidDuplicateLiterals"/>--> + <!--<rule ref="rulesets/strings.xml/StringInstantiation"/>--> + <!--<rule ref="rulesets/strings.xml/StringToString"/>--> + <!--<rule ref="rulesets/strings.xml/AvoidConcatenatingNonLiteralsInStringBuffer"/>--> + <!--<rule ref="rulesets/strings.xml/UnnecessaryCaseChange"/>--> + + <!--<rule ref="rulesets/sunsecure.xml/MethodReturnsInternalArray"/>--> + <!--<rule ref="rulesets/sunsecure.xml/ArrayIsStoredDirectly"/>--> + + <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/> + <!--<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>--> + +</ruleset> diff --git a/sandbox/old/contrib/persistence/openjpa/LICENSE.txt b/sandbox/old/contrib/persistence/openjpa/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/LICENSE.txt @@ -0,0 +1,202 @@ + + 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. diff --git a/sandbox/old/contrib/persistence/openjpa/NOTICE.txt b/sandbox/old/contrib/persistence/openjpa/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +Apache Tuscany is an effort undergoing incubation at The Apache Software +Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is +required of all newly accepted projects until a further review indicates that +the infrastructure, communications, and decision making process have stabilized +in a manner consistent with other successful ASF projects. While incubation +status is not necessarily a reflection of the completeness or stability of the +code, it does indicate that the project has yet to be fully endorsed by the ASF. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/old/contrib/persistence/openjpa/pom.xml.off b/sandbox/old/contrib/persistence/openjpa/pom.xml.off new file mode 100644 index 0000000000..51a429fda3 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/pom.xml.off @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <parent> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>openjpa</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany OpenJPA</name> + <description>TuscanyOpenJPA Integration.</description> + + + <repositories> + <repository> + <id>apache-snapshots</id> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + </repository> + </repositories> + + + <dependencies> + <dependency> + <groupId>org.apache.openjpa</groupId> + <artifactId>openjpa-persistence-jdbc</artifactId> + <version>0.9.0-incubating-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.java new file mode 100644 index 0000000000..820f57bcad --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/Constants.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +/** + * Constants used by the JPA extension + * + * @version $Rev$ $Date$ + */ +public final class Constants { + + public static final String PERSISTENCE_UNIT = "persistenceUnit"; + public static final String CONFIG_PROPERTIES = "configProperties"; + + private Constants() { + } + + +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java new file mode 100644 index 0000000000..d818f145bd --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryImplementation.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.model.AtomicImplementation; +import org.apache.tuscany.spi.model.ComponentType; + +/** + * Represents the implementation type of a system service that manages JPA + * <code>EntityManagerFactoryImplementation</code> implementations + * + * @version $Rev$ $Date$ + */ +public class EntityManagerFactoryImplementation extends AtomicImplementation<ComponentType> { + + public EntityManagerFactoryImplementation() { + } + + public EntityManagerFactoryImplementation(ComponentType componentType) { + super(componentType); + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryNotConfiguredException.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryNotConfiguredException.java new file mode 100644 index 0000000000..34e69b8951 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerFactoryNotConfiguredException.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.implementation.java.ProcessingException; + +/** + * @version $Rev$ $Date$ + */ +public class EntityManagerFactoryNotConfiguredException extends ProcessingException { + + public EntityManagerFactoryNotConfiguredException() { + super("Entity manager factory not configured"); + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java new file mode 100644 index 0000000000..45d4e1a077 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerObjectFactory.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.util.Map; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; + +/** + * Creates a JPA <code>EntityManager</code> to be injected on a component implementation instance. + * + * @version $Rev$ $Date$ + */ +public class EntityManagerObjectFactory implements ObjectFactory<EntityManager> { + + private EntityManagerFactory emf; + private Map props; + + public EntityManagerObjectFactory(EntityManagerFactory emf) { + this.emf = emf; + } + + public EntityManagerObjectFactory(EntityManagerFactory emf, Map props) { + this.emf = emf; + this.props = props; + } + + public EntityManager getInstance() throws ObjectCreationException { + if (props == null) { + return emf.createEntityManager(); + } else { + return emf.createEntityManager(props); + } + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java new file mode 100644 index 0000000000..8046c0a7c0 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/EntityManagerProcessor.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.lang.reflect.Member; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.TargetException; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.AbstractPropertyProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.ProcessingException; +import org.apache.tuscany.spi.wire.InboundWire; + + +/** + * Evaluates constructors, methods, and fields annotated with {@link PersistenceContext }, creating a mapped property + * that will inject an {@link EntityManager} on an implementation instance. + * + * @version $Rev$ $Date$ + */ +public class EntityManagerProcessor extends AbstractPropertyProcessor<PersistenceContext> { + + public EntityManagerProcessor(@Autowire ImplementationProcessorService service) { + super(PersistenceContext.class, service); + } + + protected String getName(PersistenceContext annotation) { + String name = annotation.unitName(); + if (name == null) { + return "_defaultJPAPersistenceUnit"; + } + return name; + } + + protected <T> JavaMappedProperty<T> createProperty(String name, + Class<T> javaType, + Member member) throws ProcessingException { + if (!EntityManager.class.equals(javaType)) { + throw new InvalidInjectionSite("Injection site must by of type " + EntityManager.class.getName(), name); + } + return super.createProperty(name, javaType, member); + } + + @SuppressWarnings("unchecked") + protected <T> void initProperty(JavaMappedProperty<T> property, + PersistenceContext annotation, + CompositeComponent parent, + DeploymentContext context) throws ProcessingException { + EntityManagerFactory emf; + try { + InboundWire wire = parent.resolveSystemAutowire(EntityManagerFactory.class); + if (wire == null) { + throw new EntityManagerFactoryNotConfiguredException(); + } + Object o = wire.getTargetService(); + assert o instanceof EntityManagerFactory; + emf = (EntityManagerFactory) o; + } catch (TargetException e) { + throw new ProcessingException(e); + } + ObjectFactory factory = new EntityManagerObjectFactory(emf); + property.setDefaultValueFactory(factory); + } + +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java new file mode 100644 index 0000000000..0ac5e9ffa1 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/InvalidInjectionSite.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.implementation.java.ProcessingException; + +/** + * @version $Rev$ $Date$ + */ +public class InvalidInjectionSite extends ProcessingException { + + public InvalidInjectionSite(String message) { + super(message); + } + + public InvalidInjectionSite(String message, String identifier) { + super(message, identifier); + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java new file mode 100644 index 0000000000..df74625b49 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAAtomicComponent.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.util.Map; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.TargetResolutionException; +import org.apache.tuscany.spi.extension.SystemAtomicComponentExtension; + +/** + * A system service that manages a JPA <code>EntityManagerFactory</code>. This service is used by {@link + * EntityManagerProcessor} to inject an <code>EntityManager<code> on a constructor parameter, field, or method of an + * implementation instance. Since a JPA persistence context is specific to an application, this system service is scoped + * to the application composite. That is, it is contained as a system child of the application composite. + * + * @version $Rev$ $Date$ + */ +public class JPAAtomicComponent extends SystemAtomicComponentExtension { + private EntityManagerFactory factory; + private String persistenceUnit; + private Map<Object, Object> configProps; + + public JPAAtomicComponent(String name, + CompositeComponent parent, + ScopeContainer scopeContainer, + String persistenceUnit, + Map<Object, Object> configProps, + int initLevel) { + super(name, parent, initLevel); + assert persistenceUnit != null; + this.persistenceUnit = persistenceUnit; + this.configProps = configProps; + } + + public Object createInstance() throws ObjectCreationException { + if (configProps != null) { + factory = Persistence.createEntityManagerFactory(persistenceUnit, configProps); + } else { + factory = Persistence.createEntityManagerFactory(persistenceUnit); + } + return factory; + } + + public Object getTargetInstance() throws TargetResolutionException { + return factory; + } + + +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.java new file mode 100644 index 0000000000..d979b93ca2 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAComponentBuilder.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.ComponentBuilderExtension; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.Property; + +import static org.apache.tuscany.service.openjpa.Constants.PERSISTENCE_UNIT; + +/** + * @version $Rev$ $Date$ + */ +public class JPAComponentBuilder extends ComponentBuilderExtension { + protected Class getImplementationType() { + return null; + } + + public Component build(CompositeComponent parent, ComponentDefinition definition, DeploymentContext ctx) + throws BuilderConfigException { +// String name = definition.getName(); +// ScopeContainer moduleScope = ctx.getCompositeScope(); +// Integer initLevel = definition.getInitLevel(); + ComponentType<?, ?, ?> type = definition.getImplementation().getComponentType(); + Property<?> persistenceUnit = type.getProperties().get(PERSISTENCE_UNIT); + if (persistenceUnit == null) { + throw new BuilderConfigException("Persistence Unit not specified in JPA import in composite", + parent.getName()); + } +// Property<?> configProps = type.getProperties().get(PERSISTENCE_UNIT); + return null; +// return new JPAAtomicComponent(name, parent, moduleScope, initLevel); + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.java b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.java new file mode 100644 index 0000000000..94508e5408 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/main/java/org/apache/tuscany/service/openjpa/JPAImportLoader.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.extension.LoaderExtension; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.model.ModelObject; + +/** + * @version $Rev$ $Date$ + */ +public class JPAImportLoader extends LoaderExtension { + private static final QName IMPORT = new QName(XML_NAMESPACE_1_0, "import.jpa"); + + public JPAImportLoader(@Autowire LoaderRegistry registry) { + super(registry); + } + + public QName getXMLType() { + return IMPORT; + } + + public ModelObject load(CompositeComponent parent, ModelObject object, XMLStreamReader reader, + DeploymentContext deploymentContext) + throws XMLStreamException, LoaderException { + //ComponentDefinition definition = new ComponentDefinition() + // TODO read in persisitence unit setting and properties, and set them as properties on the component + return null; + } +} diff --git a/sandbox/old/contrib/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java b/sandbox/old/contrib/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java new file mode 100644 index 0000000000..a32c850e32 --- /dev/null +++ b/sandbox/old/contrib/persistence/openjpa/src/test/java/org/apache/tuscany/service/openjpa/EntityManagerProcessorTestCase.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.openjpa; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.wire.InboundWire; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class EntityManagerProcessorTestCase extends TestCase { + + private ImplementationProcessor processor; + private CompositeComponent parent; + + public void testVisitMethod() throws Exception { + Method method = Foo.class.getMethod("setBar", EntityManager.class); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitMethod(parent, method, type, null); + JavaMappedProperty<?> prop = type.getProperties().get("bar"); + assertEquals(EntityManagerObjectFactory.class, prop.getDefaultValueFactory().getClass()); + } + + public void testVisitBadMethod() throws Exception { + Method method = Foo.class.getMethod("setBadBar", String.class); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitMethod(parent, method, type, null); + fail(); + } catch (InvalidInjectionSite e) { + // expected + } + } + + public void testVisitField() throws Exception { + Field field = Foo.class.getDeclaredField("bar"); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitField(parent, field, type, null); + JavaMappedProperty<?> prop = type.getProperties().get("bar"); + assertEquals(EntityManagerObjectFactory.class, prop.getDefaultValueFactory().getClass()); + } + + public void testBadVisitField() throws Exception { + Field field = Foo.class.getDeclaredField("badField"); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitField(null, field, type, null); + fail(); + } catch (InvalidInjectionSite e) { + // expected + } + } + + @SuppressWarnings("unchecked") + protected void setUp() throws Exception { + super.setUp(); + EntityManagerFactory emf = EasyMock.createMock(EntityManagerFactory.class); + EasyMock.replay(emf); + + InboundWire wire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(wire.getTargetService()).andReturn(emf); + EasyMock.replay(wire); + + parent = EasyMock.createMock(CompositeComponent.class); + EasyMock.expect(parent.resolveSystemAutowire(EntityManagerFactory.class)).andReturn(wire).atLeastOnce(); + EasyMock.replay(parent); + ImplementationProcessorService service = EasyMock.createMock(ImplementationProcessorService.class); + service.addName(EasyMock.isA(List.class), EasyMock.eq(0), EasyMock.isA(String.class)); + EasyMock.expectLastCall().andStubAnswer(new IAnswer() { + @SuppressWarnings({"unchecked"}) + public Object answer() throws Throwable { + ((List<Object>) EasyMock.getCurrentArguments()[0]).add(EasyMock.getCurrentArguments()[2]); + return null; + } + }); + EasyMock.replay(service); + processor = new EntityManagerProcessor(service); + } + + private static class Foo { + + + @PersistenceContext + protected EntityManager bar; + + @PersistenceContext + protected String badField; + + @PersistenceContext + public void setBar(EntityManager d) { + } + + @PersistenceContext + public void setBadBar(String d) { + } + + } +} diff --git a/sandbox/old/contrib/persistence/pom.xml.off b/sandbox/old/contrib/persistence/pom.xml.off new file mode 100644 index 0000000000..8ec39069c7 --- /dev/null +++ b/sandbox/old/contrib/persistence/pom.xml.off @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <parent> + <groupId>org.apache.tuscany.sca.services</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <packaging>pom</packaging> + <name>Tuscany SCA Persistence Services</name> + + <!-- definition of repositories where the parent pom can be found --> + <repositories> + <repository> + <id>apache.snapshots</id> + <name>Apache Snapshot Repository</name> + <url>http://people.apache.org/repo/m2-snapshot-repository</url> + <releases> + <enabled>false</enabled> + </releases> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>apache.incubator</id> + <name>Apache Incubator Repository</name> + <url>http://people.apache.org/repo/m2-incubating-repository/</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + + <modules> + <module>common</module> + <module>openjpa</module> + <module>datasource</module> + <module>store.jdbc</module> + <module>store.journal</module> + </modules> +</project> diff --git a/sandbox/old/contrib/persistence/store.jdbc/.ruleset b/sandbox/old/contrib/persistence/store.jdbc/.ruleset new file mode 100644 index 0000000000..a1547fea92 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/.ruleset @@ -0,0 +1,190 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<ruleset name="pmd-eclipse"> + <description>PMD Plugin preferences rule set</description> + + + <rule ref="rulesets/basic.xml/BooleanInstantiation"/> + <rule ref="rulesets/basic.xml/CollapsibleIfStatements"/> + <rule ref="rulesets/basic.xml/DoubleCheckedLocking"/> +<!--<rule ref="rulesets/basic.xml/EmptyCatchBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyFinallyBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyIfStmt"/>--> + <rule ref="rulesets/basic.xml/EmptyStatementNotInLoop"/> +<!--<rule ref="rulesets/basic.xml/EmptyStaticInitializer"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySwitchStatements"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySynchronizedBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyTryBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyWhileStmt"/>--> + <rule ref="rulesets/basic.xml/ForLoopShouldBeWhileLoop"/> + <rule ref="rulesets/basic.xml/JumbledIncrementer"/> +<!--<rule ref="rulesets/basic.xml/OverrideBothEqualsAndHashcode"/>--> + <rule ref="rulesets/basic.xml/ReturnFromFinallyBlock"/> + <rule ref="rulesets/basic.xml/UnconditionalIfStatement"/> + <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/> + <rule ref="rulesets/basic.xml/UnnecessaryFinalModifier"/> + <rule ref="rulesets/basic.xml/UnnecessaryReturn"/> +<!--<rule ref="rulesets/basic.xml/UselessOverridingMethod"/>--> + +<!--<rule ref="rulesets/braces.xml/ForLoopsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfElseStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/WhileLoopsMustUseBraces"/>--> + +<!--<rule ref="rulesets/clone.xml/CloneMethodMustImplementCloneable"/>--> +<!--<rule ref="rulesets/clone.xml/CloneThrowsCloneNotSupportedException"/>--> +<!--<rule ref="rulesets/clone.xml/ProperCloneImplementation"/>--> + +<!--<rule ref="rulesets/codesize.xml/CyclomaticComplexity"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveClassLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveParameterList"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessivePublicCount"/>--> +<!--<rule ref="rulesets/codesize.xml/TooManyFields"/>--> + +<!--<rule ref="rulesets/controversial.xml/AssignmentInOperand"/>--> +<!--<rule ref="rulesets/controversial.xml/AtLeastOneConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/CallSuperInConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/DontImportSun"/>--> +<!--<rule ref="rulesets/controversial.xml/NullAssignment"/>--> +<!--<rule ref="rulesets/controversial.xml/OnlyOneReturn"/>--> +<!--<rule ref="rulesets/controversial.xml/SingularField"/>--> +<!--<rule ref="rulesets/controversial.xml/SuspiciousOctalEscape"/>--> +<!--<rule ref="rulesets/controversial.xml/UnnecessaryConstructor"/>--> +<rule ref="rulesets/controversial.xml/UnnecessaryParentheses"/> +<!--<rule ref="rulesets/controversial.xml/UnusedModifier"/>--> + +<!--<rule ref="rulesets/coupling.xml/CouplingBetweenObjects"/>--> +<!--<rule ref="rulesets/coupling.xml/ExcessiveImports"/>--> +<!--<rule ref="rulesets/coupling.xml/LooseCoupling"/>--> + +<!--<rule ref="rulesets/design.xml/AbstractClassWithoutAbstractMethod"/>--> +<!--<rule ref="rulesets/design.xml/AccessorClassGeneration"/>--> +<!--<rule ref="rulesets/design.xml/AssignmentToNonFinalStatic"/>--> +<!--<rule ref="rulesets/design.xml/AvoidDeeplyNestedIfStmts"/>--> +<!--<rule ref="rulesets/design.xml/AvoidInstanceofChecksInCatchClause"/>--> +<rule ref="rulesets/design.xml/AvoidProtectedFieldInFinalClass"/> +<!--<rule ref="rulesets/design.xml/AvoidReassigningParameters"/>--> +<!--<rule ref="rulesets/design.xml/AvoidSynchronizedAtMethodLevel"/>--> +<!--<rule ref="rulesets/design.xml/BadComparison"/>--> +<!--<rule ref="rulesets/design.xml/CloseConnection"/>--> +<!--<rule ref="rulesets/design.xml/CompareObjectsWithEquals"/>--> +<!--<rule ref="rulesets/design.xml/ConfusingTernary"/>--> +<rule ref="rulesets/design.xml/ConstructorCallsOverridableMethod"/> +<!--<rule ref="rulesets/design.xml/DefaultLabelNotLastInSwitchStmt"/>--> +<!--<rule ref="rulesets/design.xml/FinalFieldCouldBeStatic"/>--> +<rule ref="rulesets/design.xml/IdempotentOperations"/> +<!--<rule ref="rulesets/design.xml/ImmutableField"/>--> +<!--<rule ref="rulesets/design.xml/InstantiationToGetClass"/>--> +<!--<rule ref="rulesets/design.xml/MissingBreakInSwitch"/>--> +<!--<rule ref="rulesets/design.xml/MissingStaticMethodInNonInstantiatableClass"/>--> +<!--<rule ref="rulesets/design.xml/NonCaseLabelInSwitchStatement"/>--> +<!--<rule ref="rulesets/design.xml/NonStaticInitializer"/>--> +<rule ref="rulesets/design.xml/OptimizableToArrayCall"/> +<rule ref="rulesets/design.xml/PositionLiteralsFirstInComparisons"/> +<rule ref="rulesets/design.xml/SimplifyBooleanExpressions"/> +<rule ref="rulesets/design.xml/SimplifyBooleanReturns"/> +<rule ref="rulesets/design.xml/SimplifyConditional"/> +<!--<rule ref="rulesets/design.xml/SwitchDensity"/>--> +<!--<rule ref="rulesets/design.xml/SwitchStmtsShouldHaveDefault"/>--> +<rule ref="rulesets/design.xml/UnnecessaryLocalBeforeReturn"/> +<!--<rule ref="rulesets/design.xml/UseLocaleWithCaseConversions"/>--> +<!--<rule ref="rulesets/design.xml/UseNotifyAllInsteadOfNotify"/>--> +<!--<rule ref="rulesets/design.xml/UseSingleton"/>--> + +<!--<rule ref="rulesets/finalizers.xml/EmptyFinalizer"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOnlyCallsSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOverloaded"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeDoesNotCallSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeShouldBeProtected"/>--> +<!--<rule ref="rulesets/finalizers.xml/AvoidCallingFinalize"/>--> + +<!--<rule ref="rulesets/imports.xml/DuplicateImports"/>--> +<!--<rule ref="rulesets/imports.xml/DontImportJavaLang"/>--> +<!--<rule ref="rulesets/imports.xml/UnusedImports"/>--> +<!--<rule ref="rulesets/imports.xml/ImportFromSamePackage"/>--> + +<!--<rule ref="rulesets/javabeans.xml/BeanMembersShouldSerialize"/>--> +<!--<rule ref="rulesets/javabeans.xml/MissingSerialVersionUID"/>--> + +<!--<rule ref="rulesets/junit.xml/JUnitStaticSuite"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitSpelling"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitAssertionsShouldIncludeMessage"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitTestsShouldIncludeAssert"/>--> +<!--<rule ref="rulesets/junit.xml/TestClassWithoutTestCases"/>--> +<!--<rule ref="rulesets/junit.xml/UnnecessaryBooleanAssertion"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertEqualsInsteadOfAssertTrue"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertSameInsteadOfAssertTrue"/>--> + + <!--<rule ref="rulesets/logging-java.xml/AvoidPrintStackTrace"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/MoreThanOneLogger"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/LogBlockWithoutIf"/>--> + <!--<rule ref="rulesets/logging-java.xml/SystemPrintln"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/UseCorrectExceptionLogging"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/ProperLogger"/>--> + + <!--<rule ref="rulesets/naming.xml/ShortVariable"/>--> + <!--<rule ref="rulesets/naming.xml/LongVariable"/>--> + <!--<rule ref="rulesets/naming.xml/ShortMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/VariableNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/MethodNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/ClassNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/AbstractNaming"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidDollarSigns"/>--> + <!--<rule ref="rulesets/naming.xml/MethodWithSameNameAsEnclosingClass"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousHashcodeMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousConstantFieldName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingTypeName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidNonConstructorMethodsWithClassName"/>--> + <!--<rule ref="rulesets/naming.xml/NoPackage"/>--> + <!--<rule ref="rulesets/naming.xml/PackageCase"/>--> + + <!--<rule ref="rulesets/optimizations.xml/LocalVariableCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/MethodArgumentCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/AvoidInstantiatingObjectsInLoops"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseArrayListInsteadOfVector"/>--> + <!--<rule ref="rulesets/optimizations.xml/SimplifyStartsWith"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseStringBufferForStringAppends"/>--> + + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingThrowable"/>--> + <!--<rule ref="rulesets/strictexception.xml/SignatureDeclareThrowsException"/>--> + <!--<rule ref="rulesets/strictexception.xml/ExceptionAsFlowControl"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingNPE"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingRawExceptionTypes"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingNullPointerException"/>--> + + <!--<rule ref="rulesets/strings.xml/AvoidDuplicateLiterals"/>--> + <!--<rule ref="rulesets/strings.xml/StringInstantiation"/>--> + <!--<rule ref="rulesets/strings.xml/StringToString"/>--> + <!--<rule ref="rulesets/strings.xml/AvoidConcatenatingNonLiteralsInStringBuffer"/>--> + <!--<rule ref="rulesets/strings.xml/UnnecessaryCaseChange"/>--> + + <!--<rule ref="rulesets/sunsecure.xml/MethodReturnsInternalArray"/>--> + <!--<rule ref="rulesets/sunsecure.xml/ArrayIsStoredDirectly"/>--> + + <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/> + <!--<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>--> + +</ruleset> diff --git a/sandbox/old/contrib/persistence/store.jdbc/LICENSE.txt b/sandbox/old/contrib/persistence/store.jdbc/LICENSE.txt new file mode 100755 index 0000000000..0084319535 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/LICENSE.txt @@ -0,0 +1,202 @@ + + 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, serviceDefinition 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. diff --git a/sandbox/old/contrib/persistence/store.jdbc/NOTICE.txt b/sandbox/old/contrib/persistence/store.jdbc/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +Apache Tuscany is an effort undergoing incubation at The Apache Software +Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is +required of all newly accepted projects until a further review indicates that +the infrastructure, communications, and decision making process have stabilized +in a manner consistent with other successful ASF projects. While incubation +status is not necessarily a reflection of the completeness or stability of the +code, it does indicate that the project has yet to be fully endorsed by the ASF. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/old/contrib/persistence/store.jdbc/pom.xml.off b/sandbox/old/contrib/persistence/store.jdbc/pom.xml.off new file mode 100644 index 0000000000..99030eb722 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/pom.xml.off @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + + <parent> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>persistence-store-jdbc</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany JDBC Store</name> + <description>Defines a JDBC-based persistent store.</description> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-api</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>${sca.version}</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>commons-dbcp</groupId> + <artifactId>commons-dbcp</artifactId> + <version>1.2.1</version> + </dependency> + <dependency> + <groupId>hsqldb</groupId> + <artifactId>hsqldb</artifactId> + <version>1.8.0.7</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + </dependency> + </dependencies> +</project> diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Converter.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Converter.java new file mode 100644 index 0000000000..b37ae6cbe5 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Converter.java @@ -0,0 +1,134 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.PreparedStatement; + +import org.apache.tuscany.spi.services.store.StoreReadException; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +/** + * Converters mediate the particularities of specific databases and JDBC drivers such as data types during read and + * write operations + * + * @version $Rev$ $Date$ + */ +public interface Converter { + + /** + * Returns the SQL statement to select a record for update + * + * @return the SQL statement to select a record for update + */ + String getSelectUpdateSql(); + + /** + * Returns the SQL statement to add a record + * + * @return the SQL statement to add a record + */ + String getInsertSql(); + + /** + * Returns the SQL statement to update a record + * + * @return the SQL statement to update a record + */ + String getUpdateSql(); + + /** + * Returns the SQL statement to retrieve a record + * + * @return the SQL statement to retrieve a record + */ + String getFindSql(); + + /** + * Returns the SQL statement to remove a record + * + * @return the SQL statement to remove a record + */ + String getDeleteSql(); + + /** + * Returns the SQL statement to remove expired records + * + * @return the SQL statement to remove expired records + */ + String getDeleteExpiredSql(); + + String getDeleteRecordSql(); + + /** + * Writes a new record to the underlying store using batch semantics. That is, the insert will be added as a batch + * operation to the prepared statment. It is the responsibility of the client (i.e. the prepared statement "owner") + * to exectute the statement when the batch threshold is reached. Note implementations must assume auto commit is + * false. + * + * @param stmt + * @param ownerId + * @param id + * @param expiration + * @param object + * @throws org.apache.tuscany.spi.services.store.StoreWriteException + * + */ + void insert(PreparedStatement stmt, String ownerId, String id, long expiration, Serializable object) + throws StoreWriteException; + + /** + * @param stmt + * @param ownerId + * @param id + * @param object + * @throws StoreWriteException + */ + void update(PreparedStatement stmt, String ownerId, String id, Serializable object) throws StoreWriteException; + + /** + * @param stmt + * @param ownerId + * @param id + * @return + * @throws StoreWriteException + */ + boolean findAndLock(PreparedStatement stmt, String ownerId, String id) throws StoreWriteException; + + /** + * Reads a record from the underlying store. Note implementations must assume auto commit is false. + * + * @param conn + * @param ownerId + * @param id + * @return + * @throws StoreReadException + */ + Object read(Connection conn, String ownerId, String id) throws StoreReadException; + + /** + * @param stmt + * @param ownerId + * @param id + * @throws StoreWriteException + */ + void delete(PreparedStatement stmt, String ownerId, String id) throws StoreWriteException; + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStore.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStore.java new file mode 100644 index 0000000000..5bd04e98da --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStore.java @@ -0,0 +1,347 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.EagerInit; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Resource; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.event.AbstractEventPublisher; +import org.apache.tuscany.spi.services.store.RecoveryListener; +import org.apache.tuscany.spi.services.store.Store; +import org.apache.tuscany.spi.services.store.StoreMonitor; +import org.apache.tuscany.spi.services.store.StoreReadException; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.apache.tuscany.api.annotation.Monitor; + +/** + * A store implementation that uses a relational database to persist records transactionally. + * <p/> + * Note this implementation does not yet support destruction callbacks for expired. In order to support this, expired + * records must be rehydrated and deleted individually. + * + * @version $Rev$ $Date$ + */ +@Service(Store.class) +@EagerInit +public class JDBCStore extends AbstractEventPublisher implements Store { + private DataSource dataSource; + private StoreMonitor monitor; + private Converter converter; + // TODO integrate with a core threading scheme + @SuppressWarnings({"FieldCanBeLocal"}) + private ScheduledExecutorService scheduler; + private long reaperInterval = 300000; + private long defaultExpirationOffset = 600000; // 10 minutes + + //private + public JDBCStore(@Resource(mappedName = "StoreDS")DataSource dataSource, + @Autowire Converter converter, + @Monitor StoreMonitor monitor) { + this.dataSource = dataSource; + this.converter = converter; + this.monitor = monitor; + } + + /** + * Returns the maximum default expiration offset for records in the store + * + * @return the maximum default expiration offset for records in the store + */ + @Property + public long getExpirationOffset() { + return defaultExpirationOffset; + } + + /** + * Sets the maximum default expiration offset for records in the store + */ + public void setDefaultExpirationOffset(long defaultExpirationOffset) { + this.defaultExpirationOffset = defaultExpirationOffset; + } + + /** + * Sets the interval for expired entry scanning to be performed + */ + @Property + public void setReaperInterval(long reaperInterval) { + this.reaperInterval = reaperInterval; + } + + /** + * Returns the interval for expired entry scanning to be performed + */ + public long getReaperInterval() { + return reaperInterval; + } + + @Init + public void init() { + this.scheduler = Executors.newSingleThreadScheduledExecutor(); + scheduler.scheduleWithFixedDelay(new Reaper(), reaperInterval, reaperInterval, TimeUnit.MILLISECONDS); + monitor.start("JDBC store started"); + } + + @Destroy + public void destroy() { + scheduler.shutdown(); + monitor.stop("JDBC store stopped"); + } + + public void insertRecord(SCAObject owner, String id, Object object, long expiration) throws StoreWriteException { + if (!(object instanceof Serializable)) { + throw new NonSerializableTypeException("Type must implement serializable", owner.getCanonicalName(), id); + } + Serializable serializable = (Serializable) object; + String canonicalName = owner.getCanonicalName(); + Connection conn = null; + PreparedStatement insertStmt = null; + PreparedStatement updateStmt = null; + long now = System.currentTimeMillis(); + try { + conn = dataSource.getConnection(); + if (now < expiration || expiration == NEVER) { + PreparedStatement stmt = conn.prepareStatement(converter.getSelectUpdateSql()); + if (converter.findAndLock(stmt, canonicalName, id)) { + updateStmt = conn.prepareStatement(converter.getUpdateSql()); + converter.update(updateStmt, canonicalName, id, serializable); + } else { + insertStmt = conn.prepareStatement(converter.getInsertSql()); + converter.insert(insertStmt, canonicalName, id, expiration, serializable); + } + } + try { + if (insertStmt != null) { + insertStmt.executeUpdate(); + } + if (updateStmt != null) { + updateStmt.executeUpdate(); + } + conn.commit(); + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e2) { + monitor.error(e2); + } + throw new StoreWriteException(owner.getCanonicalName(), id, e); + } + } catch (SQLException e) { + throw new StoreWriteException(owner.getCanonicalName(), id, e); + } finally { + close(insertStmt); + close(updateStmt); + close(conn); + } + } + + public void updateRecord(SCAObject owner, String id, Object object, long expiration) throws StoreWriteException { + if (!(object instanceof Serializable)) { + throw new NonSerializableTypeException("Type must implement serializable", owner.getCanonicalName(), id); + } + Serializable serializable = (Serializable) object; + String canonicalName = owner.getCanonicalName(); + Connection conn = null; + PreparedStatement insertStmt = null; + PreparedStatement updateStmt = null; + try { + conn = dataSource.getConnection(); + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + updateStmt = conn.prepareStatement(converter.getUpdateSql()); + converter.update(updateStmt, canonicalName, id, serializable); + try { + if (updateStmt != null) { + updateStmt.executeUpdate(); + } + conn.commit(); + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e2) { + monitor.error(e2); + } + throw new StoreWriteException(owner.getCanonicalName(), id, e); + } + } catch (SQLException e) { + throw new StoreWriteException(owner.getCanonicalName(), id, e); + } finally { + close(insertStmt); + close(updateStmt); + close(conn); + } + + } + + public Object readRecord(SCAObject owner, String id) throws StoreReadException { + Connection conn = null; + try { + conn = dataSource.getConnection(); + Object object = converter.read(conn, owner.getCanonicalName(), id); + conn.commit(); + return object; + } catch (SQLException e) { + try { + if (conn != null) { + conn.rollback(); + } + } catch (SQLException e2) { + monitor.error(e2); + } + throw new StoreReadException(owner.getName(), id, e); + } finally { + close(conn); + } + } + + public void removeRecord(SCAObject owner, String id) throws StoreWriteException { + Connection conn = null; + try { + conn = dataSource.getConnection(); + PreparedStatement stmt = conn.prepareStatement(converter.getDeleteRecordSql()); + converter.delete(stmt, owner.getCanonicalName(), id); + stmt.executeUpdate(); + conn.commit(); + } catch (SQLException e) { + try { + if (conn != null) { + conn.rollback(); + } + } catch (SQLException e2) { + monitor.error(e2); + } + throw new StoreWriteException(owner.getCanonicalName(), id, e); + } finally { + close(conn); + } + } + + public void removeRecords() throws StoreWriteException { + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = dataSource.getConnection(); + stmt = conn.prepareStatement(converter.getDeleteSql()); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new StoreWriteException(e); + } finally { + close(stmt, conn); + } + } + + public void recover(RecoveryListener listener) { + throw new UnsupportedOperationException(); + } + + private void close(Connection conn) { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + monitor.error(e); + } + } + } + + private void close(PreparedStatement stmt) { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + monitor.error(e); + } + } + } + + private void close(PreparedStatement stmt, Connection conn) { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + monitor.error(e); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + monitor.error(e); + } + } + } + + /** + * Inner class responsible for clearing out expired entries + */ + private class Reaper implements Runnable { + public void run() { + long now = System.currentTimeMillis(); + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = dataSource.getConnection(); + stmt = conn.prepareStatement(converter.getDeleteExpiredSql()); + stmt.setLong(1, now); + stmt.executeUpdate(); + conn.commit(); + } catch (SQLException e) { + if (conn != null) { + try { + conn.rollback(); + } catch (SQLException e1) { + // ignore + } + } + monitor.error(e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + // ingnore + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + // ignore + } + } + } + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/NonSerializableTypeException.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/NonSerializableTypeException.java new file mode 100644 index 0000000000..75fdde42d0 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/NonSerializableTypeException.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import org.apache.tuscany.spi.services.store.StoreWriteException; + +/** + * @version $Rev$ $Date$ + */ +public class NonSerializableTypeException extends StoreWriteException { + + public NonSerializableTypeException(String message, String owner, String identifier) { + super(message, owner, identifier); + } +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Record.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Record.java new file mode 100644 index 0000000000..e568481e17 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/Record.java @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; + +/** + * Represents a persistent object and its metadata. + * <p/> + * Note this class has a natural ordering that is inconsistent with equals. + * + * @version $Rev$ $Date$ + */ +public class Record implements Comparable { + public static final int INSERT = 0; + public static final int UPDATE = 1; + + private String ownerId; + private String id; + private Serializable object; + private long expiration = JDBCStore.NEVER; + private int operation; + + /** + * Creates a new record + * + * @param ownerId + * @param id the unique id of the record + * @param object the object to serialize + * @param expiration the expirary time, {@link org.apache.tuscany.spi.services.store.Store.NEVER} if there is no + * expiration + * @param operation an <code>INSERT</code> or <code>UPDATE</code> operation + */ + public Record(String ownerId, String id, Serializable object, long expiration, int operation) { + this.id = id; + this.object = object; + this.expiration = expiration; + this.operation = operation; + this.ownerId = ownerId; + } + + /** + * Returns the unique object id + * + * @return the unique object id + */ + public String getId() { + return id; + } + + /** + * Returns the object + * + * @return the object + */ + public Serializable getObject() { + return object; + } + + /** + * Sets the object to serialize + * + * @param object the object + */ + public void setObject(Serializable object) { + this.object = object; + } + + /** + * Returns the expiration time + * + * @return the expiration time + */ + public long getExpiration() { + return expiration; + } + + /** + * Returns the type of operation + * + * @return the type of operation + */ + public int getOperation() { + return operation; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public int compareTo(Object o) { + assert o instanceof Record; + Record record = (Record) o; + if (record.getOperation() == operation) { + return 0; + } else if (record.getOperation() == INSERT) { + return 1; + } else if (record.getOperation() == UPDATE) { + return -1; + } else { + throw new AssertionError(); + } + } +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/TCCLObjectInputStream.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/TCCLObjectInputStream.java new file mode 100644 index 0000000000..1cd18c1b24 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/TCCLObjectInputStream.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; + +/** + * Deserializes an object based on the thread context classloader + * + * @version $Rev$ $Date$ + */ +public class TCCLObjectInputStream extends ObjectInputStream { + private final ClassLoader classLoader; + + public TCCLObjectInputStream(InputStream in) throws IOException, SecurityException { + super(in); + this.classLoader = Thread.currentThread().getContextClassLoader(); + } + + protected Class resolveClass(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException { + return classLoader.loadClass(streamClass.getName()); + } +}
\ No newline at end of file diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverter.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverter.java new file mode 100644 index 0000000000..1419c5a9fe --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverter.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.converter; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.apache.tuscany.service.persistence.store.jdbc.Converter; +import org.apache.tuscany.service.persistence.store.jdbc.TCCLObjectInputStream; + +/** + * Base class for <code>Converter</code> implementations + * + * @version $Rev$ $Date$ + */ +public abstract class AbstractConverter implements Converter { + public static final int OWNER = 1; + public static final int ID = 2; + public static final int EXPIRATION = 3; + public static final int DATA = 4; + public static final int OBJECT_UPDATE = 1; + public static final int OWNER_UPDATE = 2; + public static final int ID_UPDATE = 3; + + protected String findSql = "SELECT * FROM CONVERSATION_STATE WHERE OWNER = ? AND ID = ?"; + protected String insertSql = + "INSERT INTO CONVERSATION_STATE (OWNER, ID, EXPIRATION, OBJECT) VALUES (?, ?, ?, ?)"; + protected String updateSql = "UPDATE CONVERSATION_STATE SET OBJECT = ? WHERE OWNER = ? AND ID = ?"; + protected String selectUpdateSql = + "SELECT ID FROM CONVERSATION_STATE WHERE OWNER = ? AND ID = ? FOR UPDATE"; + protected String deleteSql = "DELETE FROM CONVERSATION_STATE WHERE ID = ?"; + protected String deleteExpiredSql = "DELETE FROM CONVERSATION_STATE WHERE EXPIRATION <= ?"; + protected String deleteRecordSql = "DELETE FROM CONVERSATION_STATE WHERE OWNER = ? AND ID = ?"; + + public String getInsertSql() { + return insertSql; + } + + public String getUpdateSql() { + return updateSql; + } + + public String getFindSql() { + return findSql; + } + + public String getDeleteSql() { + return deleteSql; + } + + public String getDeleteExpiredSql() { + return deleteExpiredSql; + } + + public String getSelectUpdateSql() { + return selectUpdateSql; + } + + public String getDeleteRecordSql() { + return deleteRecordSql; + } + + public boolean findAndLock(PreparedStatement stmt, String ownerId, String id) + throws StoreWriteException { + try { + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + return stmt.executeQuery().next(); + } catch (SQLException e) { + throw new StoreWriteException(e); + } + } + + public void delete(PreparedStatement stmt, String ownerId, String id) throws StoreWriteException { + try { + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + } catch (SQLException e) { + throw new StoreWriteException(e); + } + } + + protected byte[] serialize(Serializable serializable) throws IOException { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bas); + out.writeObject(serializable); + return bas.toByteArray(); + } + + protected Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { + return new TCCLObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverter.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverter.java new file mode 100644 index 0000000000..a85ab5abfa --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverter.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.converter; + +import java.io.IOException; +import java.io.Serializable; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.tuscany.spi.services.store.StoreReadException; + +import org.apache.tuscany.spi.services.store.StoreWriteException; + +/** + * Performs writing and reading operations to HSQLDB + * + * @version $Rev$ $Date$ + */ +public class HSQLDBConverter extends AbstractConverter { + + // HSQLDB does not support SELECT FOR UPDATE + protected String selectUpdateSql = "SELECT ID FROM CONVERSATION_STATE WHERE OWNER = ? AND ID = ?"; + + public String getSelectUpdateSql() { + return selectUpdateSql; + } + + public void insert(PreparedStatement stmt, String ownerId, String id, long expiration, Serializable object) + throws StoreWriteException { + try { + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + stmt.setLong(EXPIRATION, expiration); + stmt.setBytes(DATA, serialize(object)); + } catch (SQLException e) { + throw new StoreWriteException(e); + } catch (IOException e) { + throw new StoreWriteException(e); + } + } + + public void update(PreparedStatement stmt, String ownerId, String id, Serializable object) + throws StoreWriteException { + try { + stmt.setBytes(OBJECT_UPDATE, serialize(object)); + stmt.setString(OWNER_UPDATE, ownerId); + stmt.setString(ID_UPDATE, id); + } catch (SQLException e) { + throw new StoreWriteException(e); + } catch (IOException e) { + throw new StoreWriteException(e); + } + } + + public Object read(Connection conn, String ownerId, String id) throws StoreReadException { + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement(findSql); + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + ResultSet rs = stmt.executeQuery(); + boolean more = rs.next(); + if (!more) { + return null; + } + return deserialize(rs.getBytes(DATA)); + } catch (SQLException e) { + throw new StoreReadException(e); + } catch (IOException e) { + throw new StoreReadException(e); + } catch (ClassNotFoundException e) { + throw new StoreReadException(e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + // ignore + } + } + } + } +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/JDBCConverter.java b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/JDBCConverter.java new file mode 100644 index 0000000000..4ab9ed6749 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/main/java/org/apache/tuscany/service/persistence/store/jdbc/converter/JDBCConverter.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.converter; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.tuscany.spi.services.store.StoreReadException; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +/** + * Performs writing and reading operations to a JDBC driver/database combination that supports Blobs + * + * @version $Rev$ $Date$ + */ +public class JDBCConverter extends AbstractConverter { + + public void insert(PreparedStatement stmt, String ownerId, String id, long expiration, Serializable object) + throws StoreWriteException { + try { + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + stmt.setLong(EXPIRATION, expiration); + byte[] data = serialize(object); + InputStream in = new ByteArrayInputStream(data); + stmt.setBinaryStream(DATA, in, data.length); + } catch (SQLException e) { + throw new StoreWriteException(e); + } catch (IOException e) { + throw new StoreWriteException(e); + } + } + + public void update(PreparedStatement stmt, String ownerId, String id, Serializable object) + throws StoreWriteException { + throw new UnsupportedOperationException(); + } + + public Object read(Connection conn, String ownerId, String id) throws StoreReadException { + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement(findSql); + stmt.setString(OWNER, ownerId); + stmt.setString(ID, id); + ResultSet rs = stmt.executeQuery(); + rs.next(); + Blob blob = rs.getBlob(DATA); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream()); + int b; + byte[] buffer = new byte[1024]; + while ((b = in.read(buffer, 0, 1024)) != -1) { + out.write(buffer, 0, b); + } + return deserialize(out.toByteArray()); + } catch (SQLException e) { + throw new StoreReadException(e); + } catch (IOException e) { + throw new StoreReadException(e); + } catch (ClassNotFoundException e) { + throw new StoreReadException(e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + // ignore + } + } + } + } + +}
\ No newline at end of file diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreInsertTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreInsertTestCase.java new file mode 100644 index 0000000000..3d8afc2e3b --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreInsertTestCase.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.UUID; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.services.store.Store; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.spi.services.store.StoreMonitor; + +import org.apache.tuscany.service.persistence.store.jdbc.converter.AbstractConverter; +import org.apache.tuscany.service.persistence.store.jdbc.converter.HSQLDBConverter; +import org.easymock.EasyMock; + +/** + * Verifies store insert operations using HSQLDB + * + * @version $Rev$ $Date$ + */ +public class JDBCStoreInsertTestCase extends TestCase { + private DataSource ds; + private JDBCStore store; + + public void testInsertMetaData() throws Exception { + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + store.init(); + JDBCStoreInsertTestCase.Foo foo = new JDBCStoreInsertTestCase.Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, Store.NEVER); + Statement stmt = ds.getConnection().createStatement(); + ResultSet rs = stmt.executeQuery(TestUtils.SELECT_SQL); + rs.next(); + assertEquals(id, rs.getString(AbstractConverter.ID)); + Assert.assertEquals(Store.NEVER, rs.getLong(AbstractConverter.EXPIRATION)); + } + + public void testInsertRead() throws Exception { + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + JDBCStoreInsertTestCase.Foo foo = new JDBCStoreInsertTestCase.Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, Store.NEVER); + Foo foo2 = (Foo) store.readRecord(object, id); + assertEquals("test", foo2.data); + } + + public void testInsertOverwriteRead() throws Exception { + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + JDBCStoreInsertTestCase.Foo foo = new JDBCStoreInsertTestCase.Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, Store.NEVER); + foo.data = "test2"; + store.insertRecord(object, id, foo, Store.NEVER); + Foo foo2 = (Foo) store.readRecord(object, id); + assertEquals("test2", foo2.data); + } + + /** + * Verifies multiple resources belonging to different owners but sharing the same id are inserted + */ + public void testMultipleInsert() throws Exception { + SCAObject owner1 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner1.getCanonicalName()).andReturn("baz").atLeastOnce(); + EasyMock.replay(owner1); + SCAObject owner2 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner2.getCanonicalName()).andReturn("bar").atLeastOnce(); + EasyMock.replay(owner2); + store.init(); + Foo foo1 = new Foo("test"); + String id1 = UUID.randomUUID().toString(); + Foo foo2 = new Foo("test2"); + store.insertRecord(owner1, id1, foo1, Store.NEVER); + store.insertRecord(owner2, id1, foo2, Store.NEVER); + Foo retFoo1 = (Foo) store.readRecord(owner1, id1); + assertEquals("test", retFoo1.data); + Foo retFoo2 = (Foo) store.readRecord(owner2, id1); + assertEquals("test2", retFoo2.data); + } + + + protected void setUp() throws Exception { + super.setUp(); + ds = TestUtils.createTables(); + store = new JDBCStore(ds, new HSQLDBConverter(), EasyMock.createNiceMock(StoreMonitor.class)); + } + + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanup(ds); + } + + @SuppressWarnings({"SerializableHasSerializationMethods"}) + public static class Foo implements Serializable { + private static final long serialVersionUID = -4284779882741318884L; + private String data; + + public Foo(String data) { + this.data = data; + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreTestCase.java new file mode 100644 index 0000000000..418899be86 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreTestCase.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; +import java.util.UUID; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.SCAObject; + +import junit.framework.TestCase; +import static org.apache.tuscany.spi.services.store.Store.NEVER; +import org.apache.tuscany.spi.services.store.StoreMonitor; +import org.apache.tuscany.service.persistence.store.jdbc.converter.HSQLDBConverter; +import org.easymock.EasyMock; + +/** + * Verifies store operations using HSQLDB + * + * @version $Rev$ $Date$ + */ +public class JDBCStoreTestCase extends TestCase { + private DataSource ds; + private JDBCStore store; + + public void testNotFound() throws Exception { + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + String id = UUID.randomUUID().toString(); + assertNull(store.readRecord(object, id)); + } + + public void testRemoveRecord() throws Exception { + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + Foo foo = new Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, NEVER); + Foo foo2 = (Foo) store.readRecord(object, id); + assertEquals("test", foo2.data); + store.removeRecord(object, id); + assertNull(store.readRecord(object, id)); + } + + public void testExpirationFromStore() throws Exception { + store.setReaperInterval(10); + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + Foo foo = new Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, System.currentTimeMillis() + 20); + Thread.sleep(100); + assertNull(store.readRecord(object, id)); + } + + protected void setUp() throws Exception { + super.setUp(); + ds = TestUtils.createTables(); + store = new JDBCStore(ds, new HSQLDBConverter(), EasyMock.createNiceMock(StoreMonitor.class)); + } + + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanup(ds); + } + + @SuppressWarnings({"SerializableHasSerializationMethods"}) + public static class Foo implements Serializable { + private static final long serialVersionUID = -4284779882741318884L; + private String data; + + public Foo(String data) { + this.data = data; + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreUpdateTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreUpdateTestCase.java new file mode 100644 index 0000000000..b9b0500572 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/JDBCStoreUpdateTestCase.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.io.Serializable; +import java.util.UUID; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.component.SCAObject; + +import junit.framework.TestCase; +import org.apache.tuscany.spi.services.store.Store; +import static org.apache.tuscany.spi.services.store.Store.NEVER; +import org.apache.tuscany.spi.services.store.StoreMonitor; +import org.apache.tuscany.service.persistence.store.jdbc.converter.HSQLDBConverter; +import org.easymock.EasyMock; + +/** + * Verifies store operations using HSQLDB + * + * @version $Rev$ $Date$ + */ +public class JDBCStoreUpdateTestCase extends TestCase { + private DataSource ds; + private JDBCStore store; + + public void testMultipleUpdate() throws Exception { + SCAObject owner1 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner1.getCanonicalName()).andReturn("baz").atLeastOnce(); + EasyMock.replay(owner1); + SCAObject owner2 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner2.getCanonicalName()).andReturn("bar").atLeastOnce(); + EasyMock.replay(owner2); + store.init(); + Foo foo1 = new Foo("test"); + String id1 = UUID.randomUUID().toString(); + Foo foo2 = new Foo("test2"); + store.insertRecord(owner1, id1, foo1, Store.NEVER); + store.insertRecord(owner2, id1, foo2, Store.NEVER); + foo1.data = "testA"; + foo2.data = "test2A"; + store.updateRecord(owner1, id1, foo1, Store.NEVER); + store.updateRecord(owner2, id1, foo2, Store.NEVER); + Foo retFoo1 = (Foo) store.readRecord(owner1, id1); + assertEquals("testA", retFoo1.data); + Foo retFoo2 = (Foo) store.readRecord(owner2, id1); + assertEquals("test2A", retFoo2.data); + } + + public void testUpdateRead() throws Exception { + store.init(); + SCAObject object = EasyMock.createMock(SCAObject.class); + EasyMock.expect(object.getCanonicalName()).andReturn("foo").atLeastOnce(); + EasyMock.replay(object); + Foo foo = new Foo("test"); + String id = UUID.randomUUID().toString(); + store.insertRecord(object, id, foo, NEVER); + foo.data = "test2"; + store.updateRecord(object, id, foo, Store.NEVER); + Foo foo2 = (Foo) store.readRecord(object, id); + assertEquals("test2", foo2.data); + } + + + protected void setUp() throws Exception { + super.setUp(); + ds = TestUtils.createTables(); + store = new JDBCStore(ds, new HSQLDBConverter(), EasyMock.createNiceMock(StoreMonitor.class)); + } + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanup(ds); + } + + @SuppressWarnings({"SerializableHasSerializationMethods"}) + public static class Foo implements Serializable { + private static final long serialVersionUID = -4284779882741318884L; + private String data; + + public Foo(String data) { + this.data = data; + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/RecordTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/RecordTestCase.java new file mode 100644 index 0000000000..660e906cef --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/RecordTestCase.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.util.UUID; + +import junit.framework.TestCase; +import static org.apache.tuscany.spi.services.store.Store.NEVER; + +/** + * @version $Rev$ $Date$ + */ +public class RecordTestCase extends TestCase { + + public void testInsertCompare() { + Record record = new Record(null, UUID.randomUUID().toString(), "foo", NEVER, Record.INSERT); + Record record2 = new Record(null, UUID.randomUUID().toString(), "bar", NEVER, Record.INSERT); + assertEquals(0, record.compareTo(record2)); + } + + public void testUpdateCompare() { + Record record = new Record(null, UUID.randomUUID().toString(), "foo", NEVER, Record.UPDATE); + Record record2 = new Record(null, UUID.randomUUID().toString(), "bar", NEVER, Record.UPDATE); + assertEquals(0, record.compareTo(record2)); + } + + public void testInsertUpdateCompare() { + Record record = new Record(null, UUID.randomUUID().toString(), "foo", NEVER, Record.INSERT); + Record record2 = new Record(null, UUID.randomUUID().toString(), "bar", NEVER, Record.UPDATE); + assertEquals(-1, record.compareTo(record2)); + } + + public void testUpdateInsertCompare() { + Record record = new Record(null, UUID.randomUUID().toString(), "foo", NEVER, Record.UPDATE); + Record record2 = new Record(null, UUID.randomUUID().toString(), "bar", NEVER, Record.INSERT); + assertEquals(1, record.compareTo(record2)); + } + + public void testAssertion() { + Record record = new Record(null, UUID.randomUUID().toString(), "foo", NEVER, 4); + Record record2 = new Record(null, UUID.randomUUID().toString(), "bar", NEVER, 5); + try { + record.compareTo(record2); + fail(); + } catch (AssertionError e) { + // expected + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/TestUtils.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/TestUtils.java new file mode 100644 index 0000000000..8fb1c966c9 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/TestUtils.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc; + +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; + +import org.apache.commons.dbcp.BasicDataSource; + +/** + * @version $Rev$ $Date$ + */ +public final class TestUtils { + + public static final String CREATE_TABLE = + "CREATE TABLE CONVERSATION_STATE(OWNER VARCHAR, ID VARCHAR, EXPIRATION BIGINT, " + + "OBJECT LONGVARBINARY);"; + + public static final String DROP_TABLE = "DROP TABLE CONVERSATION_STATE IF EXISTS"; + public static final String SELECT_SQL = "SELECT * FROM CONVERSATION_STATE"; + + private TestUtils() { + } + + public static DataSource createTables() throws SQLException { + BasicDataSource ds = new BasicDataSource(); + ds.setDriverClassName("org.hsqldb.jdbcDriver"); + ds.setUrl("jdbc:hsqldb:mem:test"); + Connection conn = null; + try { + conn = ds.getConnection(); + conn.createStatement().execute(CREATE_TABLE); + conn.commit(); + } finally { + if (conn != null) { + conn.close(); + } + } + return ds; + } + + public static void cleanup(DataSource ds) throws SQLException { + Connection conn = null; + try { + conn = ds.getConnection(); + conn.createStatement().execute(DROP_TABLE); + conn.createStatement().execute("SHUTDOWN"); + conn.commit(); + } finally { + if (conn != null) { + conn.close(); + } + } + } +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverterTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverterTestCase.java new file mode 100644 index 0000000000..0d8f48e126 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/AbstractConverterTestCase.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.converter; + +import java.io.IOException; +import java.io.Serializable; +import java.sql.Connection; +import java.sql.PreparedStatement; + +import org.apache.tuscany.spi.services.store.StoreReadException; + +import junit.framework.TestCase; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +/** + * @version $Rev$ $Date$ + */ +public class AbstractConverterTestCase extends TestCase { + + public void testSerializeDeserialize() throws Exception { + TestConverter converter = new TestConverter(); + Foo foo = new Foo(); + foo.data = "test"; + byte[] bytes = converter.serialize(foo); + Foo foo2 = (Foo) converter.deserialize(bytes); + assertEquals("test", foo2.data); + } + + private class TestConverter extends AbstractConverter { + + public void insert(PreparedStatement stmt, String ownerId, String id, long expiration, Serializable object) + throws StoreWriteException { + + } + + public void update(PreparedStatement stmt, String ownerId, String id, Serializable object) + throws StoreWriteException { + + } + + public boolean findAndLock(PreparedStatement stmt, + String ownerId, + String id + ) throws StoreWriteException { + return false; + } + + public Object read(Connection conn, String ownerId, String id) throws StoreReadException { + return null; + } + + public void delete(PreparedStatement stmt, String ownerId, String id) throws StoreWriteException { + + } + + @Override + public byte[] serialize(Serializable serializable) throws IOException { + return super.serialize(serializable); + } + + @Override + public Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { + return super.deserialize(bytes); + } + } + + @SuppressWarnings({"SerializableHasSerializationMethods"}) + private static class Foo implements Serializable { + private static final long serialVersionUID = -3774909621298751358L; + private String data; + } +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverterTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverterTestCase.java new file mode 100644 index 0000000000..472c523217 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/converter/HSQLDBConverterTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.converter; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.UUID; +import javax.sql.DataSource; + +import org.apache.tuscany.spi.services.store.Store; + +import junit.framework.TestCase; +import org.apache.tuscany.service.persistence.store.jdbc.Converter; +import static org.apache.tuscany.service.persistence.store.jdbc.TestUtils.cleanup; +import static org.apache.tuscany.service.persistence.store.jdbc.TestUtils.createTables; + +/** + * @version $Rev$ $Date$ + */ +public class HSQLDBConverterTestCase extends TestCase { + + private Converter converter; + private DataSource ds; + + public void testWriteRead() throws Exception { + Connection conn = ds.getConnection(); + conn.setAutoCommit(false); + PreparedStatement stmt = conn.prepareStatement(converter.getInsertSql()); + String id = UUID.randomUUID().toString(); + Foo foo = new Foo(); + foo.data = "test"; + converter.insert(stmt, "foo", id, Store.NEVER, foo); + stmt.addBatch(); + stmt.execute(); + stmt.close(); + conn.commit(); + conn.close(); + conn = ds.getConnection(); + conn.setAutoCommit(false); + Foo foo2 = (Foo) converter.read(conn, "foo", id); + assertEquals("test", foo2.data); + conn.commit(); + conn.close(); + } + + public void testNotFound() throws Exception { + Connection conn = ds.getConnection(); + conn.setAutoCommit(false); + String id = UUID.randomUUID().toString(); + assertNull(converter.read(conn, null, id)); + conn.commit(); + conn.close(); + } + + protected void setUp() throws Exception { + super.setUp(); + converter = new HSQLDBConverter(); + ds = createTables(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + cleanup(ds); + } + + @SuppressWarnings({"SerializableHasSerializationMethods"}) + private static class Foo implements Serializable { + private static final long serialVersionUID = -6119188073169441225L; + private String data; + } + +} diff --git a/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/integration/BootstrapTestCase.java b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/integration/BootstrapTestCase.java new file mode 100644 index 0000000000..4225cf65ba --- /dev/null +++ b/sandbox/old/contrib/persistence/store.jdbc/src/test/java/org/apache/tuscany/service/persistence/store/jdbc/integration/BootstrapTestCase.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.service.persistence.store.jdbc.integration; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class BootstrapTestCase extends TestCase { + + public void testBoot() throws Exception { + // TODO + } + + protected void setUp() throws Exception { + super.setUp(); + + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/.ruleset b/sandbox/old/contrib/persistence/store.journal/.ruleset new file mode 100644 index 0000000000..a1547fea92 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/.ruleset @@ -0,0 +1,190 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<ruleset name="pmd-eclipse"> + <description>PMD Plugin preferences rule set</description> + + + <rule ref="rulesets/basic.xml/BooleanInstantiation"/> + <rule ref="rulesets/basic.xml/CollapsibleIfStatements"/> + <rule ref="rulesets/basic.xml/DoubleCheckedLocking"/> +<!--<rule ref="rulesets/basic.xml/EmptyCatchBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyFinallyBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyIfStmt"/>--> + <rule ref="rulesets/basic.xml/EmptyStatementNotInLoop"/> +<!--<rule ref="rulesets/basic.xml/EmptyStaticInitializer"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySwitchStatements"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySynchronizedBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyTryBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyWhileStmt"/>--> + <rule ref="rulesets/basic.xml/ForLoopShouldBeWhileLoop"/> + <rule ref="rulesets/basic.xml/JumbledIncrementer"/> +<!--<rule ref="rulesets/basic.xml/OverrideBothEqualsAndHashcode"/>--> + <rule ref="rulesets/basic.xml/ReturnFromFinallyBlock"/> + <rule ref="rulesets/basic.xml/UnconditionalIfStatement"/> + <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/> + <rule ref="rulesets/basic.xml/UnnecessaryFinalModifier"/> + <rule ref="rulesets/basic.xml/UnnecessaryReturn"/> +<!--<rule ref="rulesets/basic.xml/UselessOverridingMethod"/>--> + +<!--<rule ref="rulesets/braces.xml/ForLoopsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfElseStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/WhileLoopsMustUseBraces"/>--> + +<!--<rule ref="rulesets/clone.xml/CloneMethodMustImplementCloneable"/>--> +<!--<rule ref="rulesets/clone.xml/CloneThrowsCloneNotSupportedException"/>--> +<!--<rule ref="rulesets/clone.xml/ProperCloneImplementation"/>--> + +<!--<rule ref="rulesets/codesize.xml/CyclomaticComplexity"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveClassLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveParameterList"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessivePublicCount"/>--> +<!--<rule ref="rulesets/codesize.xml/TooManyFields"/>--> + +<!--<rule ref="rulesets/controversial.xml/AssignmentInOperand"/>--> +<!--<rule ref="rulesets/controversial.xml/AtLeastOneConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/CallSuperInConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/DontImportSun"/>--> +<!--<rule ref="rulesets/controversial.xml/NullAssignment"/>--> +<!--<rule ref="rulesets/controversial.xml/OnlyOneReturn"/>--> +<!--<rule ref="rulesets/controversial.xml/SingularField"/>--> +<!--<rule ref="rulesets/controversial.xml/SuspiciousOctalEscape"/>--> +<!--<rule ref="rulesets/controversial.xml/UnnecessaryConstructor"/>--> +<rule ref="rulesets/controversial.xml/UnnecessaryParentheses"/> +<!--<rule ref="rulesets/controversial.xml/UnusedModifier"/>--> + +<!--<rule ref="rulesets/coupling.xml/CouplingBetweenObjects"/>--> +<!--<rule ref="rulesets/coupling.xml/ExcessiveImports"/>--> +<!--<rule ref="rulesets/coupling.xml/LooseCoupling"/>--> + +<!--<rule ref="rulesets/design.xml/AbstractClassWithoutAbstractMethod"/>--> +<!--<rule ref="rulesets/design.xml/AccessorClassGeneration"/>--> +<!--<rule ref="rulesets/design.xml/AssignmentToNonFinalStatic"/>--> +<!--<rule ref="rulesets/design.xml/AvoidDeeplyNestedIfStmts"/>--> +<!--<rule ref="rulesets/design.xml/AvoidInstanceofChecksInCatchClause"/>--> +<rule ref="rulesets/design.xml/AvoidProtectedFieldInFinalClass"/> +<!--<rule ref="rulesets/design.xml/AvoidReassigningParameters"/>--> +<!--<rule ref="rulesets/design.xml/AvoidSynchronizedAtMethodLevel"/>--> +<!--<rule ref="rulesets/design.xml/BadComparison"/>--> +<!--<rule ref="rulesets/design.xml/CloseConnection"/>--> +<!--<rule ref="rulesets/design.xml/CompareObjectsWithEquals"/>--> +<!--<rule ref="rulesets/design.xml/ConfusingTernary"/>--> +<rule ref="rulesets/design.xml/ConstructorCallsOverridableMethod"/> +<!--<rule ref="rulesets/design.xml/DefaultLabelNotLastInSwitchStmt"/>--> +<!--<rule ref="rulesets/design.xml/FinalFieldCouldBeStatic"/>--> +<rule ref="rulesets/design.xml/IdempotentOperations"/> +<!--<rule ref="rulesets/design.xml/ImmutableField"/>--> +<!--<rule ref="rulesets/design.xml/InstantiationToGetClass"/>--> +<!--<rule ref="rulesets/design.xml/MissingBreakInSwitch"/>--> +<!--<rule ref="rulesets/design.xml/MissingStaticMethodInNonInstantiatableClass"/>--> +<!--<rule ref="rulesets/design.xml/NonCaseLabelInSwitchStatement"/>--> +<!--<rule ref="rulesets/design.xml/NonStaticInitializer"/>--> +<rule ref="rulesets/design.xml/OptimizableToArrayCall"/> +<rule ref="rulesets/design.xml/PositionLiteralsFirstInComparisons"/> +<rule ref="rulesets/design.xml/SimplifyBooleanExpressions"/> +<rule ref="rulesets/design.xml/SimplifyBooleanReturns"/> +<rule ref="rulesets/design.xml/SimplifyConditional"/> +<!--<rule ref="rulesets/design.xml/SwitchDensity"/>--> +<!--<rule ref="rulesets/design.xml/SwitchStmtsShouldHaveDefault"/>--> +<rule ref="rulesets/design.xml/UnnecessaryLocalBeforeReturn"/> +<!--<rule ref="rulesets/design.xml/UseLocaleWithCaseConversions"/>--> +<!--<rule ref="rulesets/design.xml/UseNotifyAllInsteadOfNotify"/>--> +<!--<rule ref="rulesets/design.xml/UseSingleton"/>--> + +<!--<rule ref="rulesets/finalizers.xml/EmptyFinalizer"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOnlyCallsSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOverloaded"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeDoesNotCallSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeShouldBeProtected"/>--> +<!--<rule ref="rulesets/finalizers.xml/AvoidCallingFinalize"/>--> + +<!--<rule ref="rulesets/imports.xml/DuplicateImports"/>--> +<!--<rule ref="rulesets/imports.xml/DontImportJavaLang"/>--> +<!--<rule ref="rulesets/imports.xml/UnusedImports"/>--> +<!--<rule ref="rulesets/imports.xml/ImportFromSamePackage"/>--> + +<!--<rule ref="rulesets/javabeans.xml/BeanMembersShouldSerialize"/>--> +<!--<rule ref="rulesets/javabeans.xml/MissingSerialVersionUID"/>--> + +<!--<rule ref="rulesets/junit.xml/JUnitStaticSuite"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitSpelling"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitAssertionsShouldIncludeMessage"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitTestsShouldIncludeAssert"/>--> +<!--<rule ref="rulesets/junit.xml/TestClassWithoutTestCases"/>--> +<!--<rule ref="rulesets/junit.xml/UnnecessaryBooleanAssertion"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertEqualsInsteadOfAssertTrue"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertSameInsteadOfAssertTrue"/>--> + + <!--<rule ref="rulesets/logging-java.xml/AvoidPrintStackTrace"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/MoreThanOneLogger"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/LogBlockWithoutIf"/>--> + <!--<rule ref="rulesets/logging-java.xml/SystemPrintln"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/UseCorrectExceptionLogging"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/ProperLogger"/>--> + + <!--<rule ref="rulesets/naming.xml/ShortVariable"/>--> + <!--<rule ref="rulesets/naming.xml/LongVariable"/>--> + <!--<rule ref="rulesets/naming.xml/ShortMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/VariableNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/MethodNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/ClassNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/AbstractNaming"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidDollarSigns"/>--> + <!--<rule ref="rulesets/naming.xml/MethodWithSameNameAsEnclosingClass"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousHashcodeMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousConstantFieldName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingTypeName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidNonConstructorMethodsWithClassName"/>--> + <!--<rule ref="rulesets/naming.xml/NoPackage"/>--> + <!--<rule ref="rulesets/naming.xml/PackageCase"/>--> + + <!--<rule ref="rulesets/optimizations.xml/LocalVariableCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/MethodArgumentCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/AvoidInstantiatingObjectsInLoops"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseArrayListInsteadOfVector"/>--> + <!--<rule ref="rulesets/optimizations.xml/SimplifyStartsWith"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseStringBufferForStringAppends"/>--> + + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingThrowable"/>--> + <!--<rule ref="rulesets/strictexception.xml/SignatureDeclareThrowsException"/>--> + <!--<rule ref="rulesets/strictexception.xml/ExceptionAsFlowControl"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingNPE"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingRawExceptionTypes"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingNullPointerException"/>--> + + <!--<rule ref="rulesets/strings.xml/AvoidDuplicateLiterals"/>--> + <!--<rule ref="rulesets/strings.xml/StringInstantiation"/>--> + <!--<rule ref="rulesets/strings.xml/StringToString"/>--> + <!--<rule ref="rulesets/strings.xml/AvoidConcatenatingNonLiteralsInStringBuffer"/>--> + <!--<rule ref="rulesets/strings.xml/UnnecessaryCaseChange"/>--> + + <!--<rule ref="rulesets/sunsecure.xml/MethodReturnsInternalArray"/>--> + <!--<rule ref="rulesets/sunsecure.xml/ArrayIsStoredDirectly"/>--> + + <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/> + <!--<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>--> + +</ruleset> diff --git a/sandbox/old/contrib/persistence/store.journal/LICENSE.txt b/sandbox/old/contrib/persistence/store.journal/LICENSE.txt new file mode 100755 index 0000000000..0084319535 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/LICENSE.txt @@ -0,0 +1,202 @@ + + 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, serviceDefinition 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. diff --git a/sandbox/old/contrib/persistence/store.journal/NOTICE.txt b/sandbox/old/contrib/persistence/store.journal/NOTICE.txt new file mode 100644 index 0000000000..d83ebbe236 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/NOTICE.txt @@ -0,0 +1,14 @@ +${pom.name} +Copyright (c) 2005 - 2006 The Apache Software Foundation + +Apache Tuscany is an effort undergoing incubation at The Apache Software +Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is +required of all newly accepted projects until a further review indicates that +the infrastructure, communications, and decision making process have stabilized +in a manner consistent with other successful ASF projects. While incubation +status is not necessarily a reflection of the completeness or stability of the +code, it does indicate that the project has yet to be fully endorsed by the ASF. + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/old/contrib/persistence/store.journal/pom.xml.off b/sandbox/old/contrib/persistence/store.journal/pom.xml.off new file mode 100644 index 0000000000..679dcfe649 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/pom.xml.off @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + + <parent> + <groupId>org.apache.tuscany.sca.services.persistence</groupId> + <artifactId>parent</artifactId> + <version>1.0-incubator-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>persistence-store-journal</artifactId> + <packaging>jar</packaging> + <name>Apache Tuscany Journal Store</name> + <description>Defines a journal-based persistent store.</description> + <repositories> + <repository> + <id>objectweb</id> + <name>ObjectWeb repo</name> + <url>http://maven.objectweb.org/maven2</url> + <releases> + <enabled>true</enabled> + </releases> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-api</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.apache.tuscany.sca.kernel</groupId> + <artifactId>tuscany-spi</artifactId> + <version>1.0-alpha-incubating-SNAPSHOT</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>journalPerfTest</scope> + </dependency> + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymockclassextension</artifactId> + <scope>journalPerfTest</scope> + </dependency> + <dependency> + <groupId>org.objectweb.howl</groupId> + <artifactId>howl</artifactId> + <version>1.0.1-1</version> + </dependency> + </dependencies> +</project> diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/CacheEventListener.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/CacheEventListener.java new file mode 100644 index 0000000000..df6d3452e2 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/CacheEventListener.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +/** + * A listener interface for cache events + * + * @version $Rev$ $Date$ + */ +public interface CacheEventListener { + + /** + * Callback when an entry is evicted from the cache + */ + void onEviction(RecordKey key, RecordEntry entry); + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Header.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Header.java new file mode 100644 index 0000000000..f2cae6218a --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Header.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +/** + * A header entry for a record written to the log. A header contains the following information: + * <pre> + * <ul> + * <li><strong>Owner id</strong> - the unique id of the owner, typically the SCAObject canonical name + * <li><strong>Operation</strong> - if the record is an INSERT, UPDATE, or DELETE + * <li><strong>Most Significant bits</strong> - the most signficant bits of the <code>java.util.UUID</code> + * representing the id of the persisted instance + * <li><strong>Least Significant bits</strong> - the least signficant bits of the <code>java.util.UUID</code> + * representing the id of the persisted instance + * <li><strong>Expiration</strong> - the expiration time in milliseconds when the record is set to expire + * <li><strong>Number of blocks</strong> - the number of blocks the record is written across + * <li><strong>Fields</strong> - any other data associated with the header + * </ul> + * </pre> + * + * @version $Rev$ $Date$ + */ +public class Header { + public static final short INSERT = 0; + public static final short UPDATE = 1; + public static final short DELETE = 2; + + protected byte[][] fields; + private short operation; + private String ownerId; + private String id; + private long expiration; + private int numBlocks; + + public Header() { + } + + /** + * Returns the record operation type + * + * @return the record operation type + */ + public short getOperation() { + return operation; + } + + /** + * Sets the record operation type + */ + public void setOperation(short operation) { + this.operation = operation; + } + + /** + * Returns the number of blocks the record is written across + * + * @return the number of blocks the record is written across + */ + public int getNumBlocks() { + return numBlocks; + } + + /** + * Sets the number of blocks the record is written across + */ + public void setNumBlocks(int numBlocks) { + this.numBlocks = numBlocks; + } + + /** + * Returns the unique owner id + * + * @return the unique owner id + */ + public String getOwnerId() { + return ownerId; + } + + /** + * Sets the unique owner id + */ + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + /** + * Returns the record id + * + * @return the record id + */ + public String getId() { + return id; + } + + /** + * Sets the most significant bits of the record UUID + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns the time in milliseconds the record is set to expire + * + * @return the time in milliseconds the record is set to expire + */ + public long getExpiration() { + return expiration; + } + + /** + * Sets the time the record is set to expire in milliseconds + */ + public void setExpiration(long expiration) { + this.expiration = expiration; + } + + /** + * Returns additional header data + * + * @return additional header data + */ + public byte[][] getFields() { + return fields; + } + + /** + * Sets additional header data + */ + public void setFields(byte[][] fields) { + this.fields = fields; + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Journal.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Journal.java new file mode 100644 index 0000000000..b8dfd072c5 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/Journal.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.IOException; + +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.objectweb.howl.log.Configuration; +import org.objectweb.howl.log.LogClosedException; +import org.objectweb.howl.log.LogFileOverflowException; +import org.objectweb.howl.log.LogRecordSizeException; +import org.objectweb.howl.log.Logger; + +/** + * Extends the HOWL logger implementation adding convenience methods for processing records + * + * @version $Rev$ $Date$ + */ +public class Journal extends Logger { + public static final short HEADER = 0; + public static final short RECORD = 1; + + public Journal() throws IOException { + } + + public Journal(Configuration config) throws IOException { + super(config); + } + + /** + * Writes a header record to the log. The format of the header is defined by {@link + * SerializationHelper#createHeader(short, int, String, String, long)} + * + * @param bytes the record as a byte array + * @param force true if the disk write should be forced + * @return the log entry key + * @throws StoreWriteException + */ + public long writeHeader(byte[] bytes, boolean force) throws StoreWriteException { + try { + return put(HEADER, new byte[][]{bytes}, force); + } catch (LogRecordSizeException e) { + throw new StoreWriteException(e); + } catch (LogFileOverflowException e) { + throw new StoreWriteException(e); + } catch (IOException e) { + throw new StoreWriteException(e); + } catch (LogClosedException e) { + throw new StoreWriteException(e); + } catch (InterruptedException e) { + throw new StoreWriteException(e); + } + } + + /** + * Writes a record block to the log. The block may be the complete number of bytes or a chunked part of thereof if + * it does not fit within HOWL's block size limit. + * + * @param data the data to write + * @param id the unique record id consisting of the owner id and the UUID + * @param force true if the disk write should be force. For records that are written in multiple blocks, only the + * last write should be forced. + * @return the log entry key + * @throws StoreWriteException + */ + public long writeBlock(byte[] data, byte[] id, boolean force) throws StoreWriteException { + try { + return put(RECORD, new byte[][]{id, data}, force); + } catch (LogRecordSizeException e) { + throw new StoreWriteException(e); + } catch (LogFileOverflowException e) { + throw new StoreWriteException(e); + } catch (IOException e) { + throw new StoreWriteException(e); + } catch (LogClosedException e) { + throw new StoreWriteException(e); + } catch (InterruptedException e) { + throw new StoreWriteException(e); + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalIinitializationException.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalIinitializationException.java new file mode 100644 index 0000000000..910598fc61 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalIinitializationException.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import org.apache.tuscany.spi.services.store.StoreException; + +/** + * Denotes an error starting the journal + * + * @version $Rev$ $Date$ + */ +public class JournalIinitializationException extends StoreException { + + public JournalIinitializationException(Throwable cause) { + super(cause); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalRecord.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalRecord.java new file mode 100644 index 0000000000..ec2e491c1d --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalRecord.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +/** + * Represents a record read from the log + * + * @version $Rev$ $Date$ + */ +public class JournalRecord { + + private Header header; + private byte[] data; + + public JournalRecord(byte[] data) { + this.data = data; + } + + /** + * Returns the record header + * + * @return the record header + */ + public Header getHeader() { + return header; + } + + /** + * Sets the record header + */ + public void setHeader(Header header) { + this.header = header; + } + + /** + * Returns the serialized data portion of the record which may be assembled from multiple blocks + * + * @return the serialized data portion of the record which may be assembled from multiple blocks + */ + public byte[] getData() { + return data; + } + + /** + * Sets the serialized data portion of the record which may be written across multiple blocks + */ + public void setData(byte[] data) { + this.data = data; + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalShutdownException.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalShutdownException.java new file mode 100644 index 0000000000..945a77753a --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalShutdownException.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import org.apache.tuscany.spi.services.store.StoreException; + +/** + * Denotes an error shutting down the journal + * + * @version $Rev$ $Date$ + */ +public class JournalShutdownException extends StoreException { + + public JournalShutdownException(Throwable cause) { + super(cause); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStore.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStore.java new file mode 100644 index 0000000000..422c074790 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStore.java @@ -0,0 +1,595 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.IOException; +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import org.osoa.sca.annotations.Constructor; +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.EagerInit; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.event.AbstractEventPublisher; +import org.apache.tuscany.spi.services.store.RecoveryListener; +import org.apache.tuscany.spi.services.store.Store; +import org.apache.tuscany.spi.services.store.StoreExpirationEvent; +import org.apache.tuscany.spi.services.store.StoreMonitor; +import org.apache.tuscany.spi.services.store.StoreReadException; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.apache.tuscany.api.annotation.Monitor; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.partition; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serialize; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeHeader; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeRecordId; +import org.objectweb.howl.log.Configuration; +import org.objectweb.howl.log.InvalidFileSetException; +import org.objectweb.howl.log.InvalidLogBufferException; +import org.objectweb.howl.log.InvalidLogKeyException; +import org.objectweb.howl.log.LogClosedException; +import org.objectweb.howl.log.LogConfigurationException; +import org.objectweb.howl.log.LogEventListener; +import org.objectweb.howl.log.LogException; +import org.objectweb.howl.log.LogFileOverflowException; +import org.objectweb.howl.log.LogRecord; +import org.objectweb.howl.log.LogRecordSizeException; + +/** + * A journal-based store service that uses HOWL for reliable persistence and recovery of object instances. Insert, + * update, and delete operations, as well as object instances, are written to a binary log. Delete operations are + * written as a single header block as defined by {@link SerializationHelper#serializeHeader(short,int,String,String, + *long)}. Insert and update operations are written using multiple blocks consisting of at least one header and 1..n + * additional blocks containing the object byte array. If the byte array size is greater than the log block size (the + * HOWL default is 4K), it must be partitioned into smaller units using {@link SerializationHelper#partition(byte[], + *int)} and written across multiple blocks. The header contains the number of ensuing blocks a record occupies. Since + * block writes to the log may be interleaved, blocks for a given record may not be consecutive. In order to identify + * the record a block belongs to, the first byte array of written data for the block contains the serialized owner id + * and UUID associated with the record. + * <p/> + * A cache of all active persisted instances is maintained in memory and is used for read operations. When an instance + * is persisted, a log record is written and an entry is added to the cache containing the instance. When an instance is + * deleted, a delete record is written to the log and its corresponding cache entry is removed. During recovery, the + * instance cache is reconstituted by reading the log and deserializing active records. + * <p/> + * The journal store is designed for reliable, performant persistence and therefore avoids the overhead associated with + * using a relational database. This does, however, impose two configuration requirements. The first is that a log file + * must be larger than the size of all <bold>active</bold> instances in the runtime. As a log file begins to fill, the + * store will copy active records (expired records will be ignored) to a new file and the old log will be recycled. A + * second requirement is that all active instances must fit within the memory limits of the runtime JVM since the store + * does not perform passivation and a table of all active instances is maintained for querying. + * + * @version $Rev$ $Date$ + */ +@Service(Store.class) +@EagerInit +public class JournalStore extends AbstractEventPublisher implements Store { + private static final int UNITIALIZED = -99; + + // the cache of active records + private ConcurrentHashMap<RecordKey, RecordEntry> cache; + // private ReadWriteLock lock = new ReentrantReadWriteLock(); + private final Object shutdownLock = new Object(); + // TODO integrate with a core threading scheme + private ScheduledExecutorService scheduler; + private StoreMonitor monitor; + private Journal journal; + private long defaultExpirationOffset = 600000; // 10 minutes + private long reaperInterval = 1000; + private int blockSize = 4096; // 4k standard for HOWL + + private Configuration config; + // HOWL properties - cf. <code>org.objectweb.howl.log.Configuration</code> + private boolean checksumEnabled; + private int bufferSize = UNITIALIZED; + private String bufferClassName; + private int maxBuffers = UNITIALIZED; + private int minBuffers = UNITIALIZED; + private int flushSleepTime = UNITIALIZED; + private boolean flushPartialBuffers; + private int threadsWaitingForceThreshold = UNITIALIZED; + private int maxBlocksPerFile = UNITIALIZED; + private int maxLogFiles = UNITIALIZED; + private String logFileDir = "../stores"; + private String logFileExt = "store"; + private String logFileName = "tuscany"; + private String logFileMode; + // end HOWL properties + + /** + * Creates a new store instance + * + * @param monitor the monitor for recording store events + */ + @Constructor + public JournalStore(@Monitor StoreMonitor monitor) { + this.monitor = monitor; + config = new Configuration(); + } + + /** + * Protected constructor for unit testing + * + * @param monitor the monitor for recording store events + * @param journal the journal the store should write to, typically a mock + */ + protected JournalStore(StoreMonitor monitor, Journal journal) { + this.monitor = monitor; + this.journal = journal; + config = new Configuration(); + } + + public int getBlockSize() { + return blockSize; + } + + /** + * Returns the maximum default expiration offset for records in the store + * + * @return the maximum default expiration offset for records in the store + */ + @Property + public long getExpirationOffset() { + return defaultExpirationOffset; + } + + /** + * Sets the maximum default expiration offset for records in the store + */ + public void setDefaultExpirationOffset(long defaultExpirationOffset) { + this.defaultExpirationOffset = defaultExpirationOffset; + } + + @Property + public void setBlockSize(int blockSize) { + this.blockSize = blockSize; + } + + public boolean isChecksumEnabled() { + return checksumEnabled; + } + + @Property + public void setChecksumEnabled(boolean val) { + config.setChecksumEnabled(val); + this.checksumEnabled = val; + } + + public int getBufferSize() { + return bufferSize; + } + + @Property + public void setBufferSize(int bufferSize) throws JournalStorePropertyException { + try { + config.setBufferSize(bufferSize); + this.bufferSize = bufferSize; + } catch (LogConfigurationException e) { + throw new JournalStorePropertyException(e); + } + } + + public String getBufferClassName() { + return bufferClassName; + } + + @Property + public void setBufferClassName(String bufferClassName) { + config.setBufferClassName(bufferClassName); + this.bufferClassName = bufferClassName; + } + + public int getMaxBuffers() { + return maxBuffers; + } + + @Property + public void setMaxBuffers(int maxBuffers) throws JournalStorePropertyException { + try { + config.setMaxBuffers(maxBuffers); + this.maxBuffers = maxBuffers; + } catch (LogConfigurationException e) { + throw new JournalStorePropertyException(e); + } + } + + public int getMinBuffers() { + return minBuffers; + } + + @Property + public void setMinBuffers(int minBuffers) throws JournalStorePropertyException { + try { + config.setMinBuffers(minBuffers); + this.minBuffers = minBuffers; + } catch (LogConfigurationException e) { + throw new JournalStorePropertyException(e); + } + } + + public int getFlushSleepTime() { + return flushSleepTime; + } + + @Property + public void setFlushSleepTime(int time) { + config.setFlushSleepTime(time); + this.flushSleepTime = time; + } + + public boolean isFlushPartialBuffers() { + return flushPartialBuffers; + } + + @Property + public void setFlushPartialBuffers(boolean val) { + config.setFlushPartialBuffers(val); + this.flushPartialBuffers = val; + } + + public int getThreadsWaitingForceThreshold() { + return threadsWaitingForceThreshold; + } + + @Property + public void setThreadsWaitingForceThreshold(int threshold) { + config.setThreadsWaitingForceThreshold(threshold); + this.threadsWaitingForceThreshold = threshold; + } + + public int getMaxBlocksPerFile() { + return maxBlocksPerFile; + } + + @Property + public void setMaxBlocksPerFile(int maxBlocksPerFile) { + config.setMaxBlocksPerFile(maxBlocksPerFile); + this.maxBlocksPerFile = maxBlocksPerFile; + } + + public int getMaxLogFiles() { + return maxLogFiles; + } + + @Property + public void setMaxLogFiles(int maxLogFiles) { + config.setMaxLogFiles(maxLogFiles); + this.maxLogFiles = maxLogFiles; + } + + public String getLogFileDir() { + return logFileDir; + } + + @Property + public void setLogFileDir(String dir) { + config.setLogFileDir(dir); + this.logFileDir = dir; + } + + public String getLogFileExt() { + return logFileExt; + } + + @Property + public void setLogFileExt(String logFileExt) { + config.setLogFileExt(logFileExt); + this.logFileExt = logFileExt; + } + + public String getLogFileName() { + return logFileName; + } + + @Property + public void setLogFileName(String logFileName) { + config.setLogFileName(logFileName); + this.logFileName = logFileName; + } + + public String getLogFileMode() { + return logFileMode; + } + + public void setLogFileMode(String logFileMode) throws JournalStorePropertyException { + try { + config.setLogFileMode(logFileMode); + this.logFileMode = logFileMode; + } catch (LogConfigurationException e) { + throw new JournalStorePropertyException(e); + } + } + + /** + * Initializes the store by opening the journal and starting the checkpoint daemon + * + * @throws JournalIinitializationException + * + */ + @Init + public void init() throws JournalIinitializationException { + try { + cache = new ConcurrentHashMap<RecordKey, RecordEntry>(); + if (journal == null) { + config.setLogFileName(logFileName); + config.setLogFileExt(logFileExt); + config.setLogFileDir(logFileDir); + journal = new Journal(config); + } + journal.setLogEventListener(new JournalLogEventListener()); + journal.open(); + scheduler = Executors.newSingleThreadScheduledExecutor(); + scheduler.scheduleWithFixedDelay(new Reaper(), reaperInterval, reaperInterval, MILLISECONDS); + monitor.start("Started journal store"); + } catch (IOException e) { + throw new JournalIinitializationException(e); + } catch (LogConfigurationException e) { + throw new JournalIinitializationException(e); + } catch (InvalidLogBufferException e) { + throw new JournalIinitializationException(e); + } catch (InterruptedException e) { + throw new JournalIinitializationException(e); + } catch (InvalidFileSetException e) { + throw new JournalIinitializationException(e); + } + } + + /** + * Performs an orderly close of the journal and checkpoint daemon + * + * @throws JournalShutdownException + */ + @Destroy + public void destroy() throws JournalShutdownException { + try { + // avoid potential deadlock by acquiring write lock since the reaper thread can block when calling a + // synchronized journal method (e.g. journal.put) since journal.close() below holds a synchronization lock. + // This deadlock will prevent the scheduler.shutdown from completing, hanging this store shutdown + synchronized (shutdownLock) { + scheduler.shutdown(); + journal.close(); + monitor.stop("Stopped journal store"); + } + } catch (IOException e) { + throw new JournalShutdownException(e); + } catch (InterruptedException e) { + throw new JournalShutdownException(e); + } + } + + public void insertRecord(SCAObject owner, String id, Object object, long expiration) throws StoreWriteException { + write(owner, id, object, expiration, Header.INSERT); + } + + public void updateRecord(SCAObject owner, String id, Object object, long expiration) throws StoreWriteException { + write(owner, id, object, expiration, Header.UPDATE); + } + + public Object readRecord(SCAObject owner, String id) throws StoreReadException { + RecordEntry record; + RecordKey key = new RecordKey(id, owner); + record = cache.get(key); + if (record == null) { + return null; + } + if (record.getExpiration() != Store.NEVER && record.getExpiration() < System.currentTimeMillis()) { + cache.remove(key); + } + return record.getObject(); + } + + public void removeRecord(SCAObject owner, String id) throws StoreWriteException { + try { + journal.writeHeader(serializeHeader(Header.DELETE, 0, owner.getUri().toString(), id, NEVER), true); + RecordKey key = new RecordKey(id, owner); + // remove from the cache + cache.remove(key); + } catch (IOException e) { + throw new StoreWriteException(e); + } + + } + + public void removeRecords() throws StoreWriteException { + + } + + public void recover(RecoveryListener listener) throws StoreReadException { + } + + /** + * Writes a record to the log. If a record needs to be written in multiple blocks, only the last block write is + * forced. + * + * @param owner + * @param id + * @param object + * @param expiration + * @param operation + * @throws StoreWriteException + */ + private void write(SCAObject owner, String id, Object object, long expiration, short operation) + throws StoreWriteException { + if (!(object instanceof Serializable)) { + String name = object.getClass().getName(); + throw new StoreWriteException("Type must implement serializable", name, id); + } + Serializable serializable = (Serializable) object; + String name = owner.getUri().toString(); + List<byte[]> bytes; + try { + bytes = partition(serialize(serializable), blockSize); + } catch (IOException e) { + throw new StoreWriteException(e); + } + try { + byte[] header = serializeHeader(operation, bytes.size(), name, id, expiration); + long headerKey = journal.writeHeader(header, false); + // write chunked records in non-forced mode except last one + byte[] recordId = serializeRecordId(name, id); + long[] keys = new long[bytes.size() + 1]; + keys[0] = headerKey; + for (int i = 0; i < bytes.size() - 1; i++) { + byte[] chunk = bytes.get(i); + keys[i + 1] = journal.writeBlock(chunk, recordId, false); + } + // add last record using a forced write + journal.writeBlock(bytes.get(bytes.size() - 1), recordId, true); + RecordKey key = new RecordKey(id, owner); + // add to the entry in the cache + cache.put(key, new RecordEntry(serializable, operation, keys, expiration)); + } catch (IOException e) { + throw new StoreWriteException(e); + } + } + + /** + * Handles log overflow events + */ + private class JournalLogEventListener implements LogEventListener { + + public void logOverflowNotification(long overflowFence) { + assert overflowFence != 0; + long newMark = Long.MAX_VALUE; + long now = System.currentTimeMillis(); + try { + for (Map.Entry<RecordKey, RecordEntry> entry : cache.entrySet()) { + RecordEntry record = entry.getValue(); + long[] journalKey = record.getJournalKeys(); + if (journalKey[0] > overflowFence) { + // do not copy to new log but check if this is the new mark + if (journalKey[0] < newMark) { + newMark = journalKey[0]; + } + continue; + } + if (entry.getValue().getExpiration() > now) { + // copy the blocks associayed with the record to the new journal only if it is not expired + for (long key : journalKey) { + LogRecord lrecord = journal.get(null, key); + journal.put(lrecord.getFields(), false); + + } + } + } + if (newMark == Long.MAX_VALUE) { + newMark = overflowFence; + } + // force write + journal.mark(newMark, true); + } catch (LogRecordSizeException e) { + monitor.error(e); + } catch (LogFileOverflowException e) { + monitor.error(e); + } catch (LogConfigurationException e) { + monitor.error(e); + } catch (IOException e) { + monitor.error(e); + } catch (InvalidLogBufferException e) { + monitor.error(e); + } catch (LogClosedException e) { + monitor.error(e); + } catch (LogException e) { + monitor.error(e); + } catch (InterruptedException e) { + monitor.error(e); + } + } + + public boolean isLoggable(int level) { + return false; + } + + public void log(int level, String message) { + + } + + public void log(int level, String message, Throwable thrown) { + + } + } + + /** + * Periodically scans the instance cache, clearing out expired entries + */ + private class Reaper implements Runnable { + + public void run() { + try { + synchronized (shutdownLock) { + boolean force = false; + long now = System.currentTimeMillis(); + long oldest = Long.MAX_VALUE; + for (Map.Entry<RecordKey, RecordEntry> entry : cache.entrySet()) { + RecordKey key = entry.getKey(); + RecordEntry record = entry.getValue(); + if (record.getExpiration() <= now) { + try { + String ownerName = key.getOwner().getUri().toString(); + String id = key.getId(); + byte[] header = + SerializationHelper.serializeHeader(Header.DELETE, 0, ownerName, id, Store.NEVER); + journal.writeHeader(header, false); + // notify listeners + SCAObject owner = key.getOwner(); + Object instance = record.getObject(); + // notify listeners of the expiration + StoreExpirationEvent event = new StoreExpirationEvent(this, owner, instance); + publish(event); + } catch (IOException e) { + monitor.error(e); + } catch (StoreWriteException e) { + monitor.error(e); + } + force = true; + cache.remove(entry.getKey()); // semantics of ConcurrentHashMap allow this + } else { + if (record.getJournalKeys()[0] < oldest) { + oldest = record.getJournalKeys()[0]; + } + } + } + if (force) { + // perform a forced write and update the journal mark + journal.mark(oldest, true); + } + } + } catch (IOException e) { + monitor.error(e); + } catch (LogClosedException e) { + monitor.error(e); + } catch (InvalidLogKeyException e) { + monitor.error(e); + } catch (InterruptedException e) { + monitor.error(e); + } + } + } + + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStorePropertyException.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStorePropertyException.java new file mode 100644 index 0000000000..275bad21f7 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/JournalStorePropertyException.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import org.apache.tuscany.spi.services.store.StoreException; + +/** + * Denotes an error setting a property on the journal store + * + * @version $Rev$ $Date$ + */ +public class JournalStorePropertyException extends StoreException { + + public JournalStorePropertyException(Throwable cause) { + super(cause); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordEntry.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordEntry.java new file mode 100644 index 0000000000..28fa9c43ac --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordEntry.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.Serializable; + +/** + * A journal store cache entry for a record + * + * @version $Rev$ $Date$ + */ +public class RecordEntry { + private Serializable object; + private short operation; + private long expiration; + private long[] journalKeys; + + + /** + * Creates a new cached record + * + * @param object the object to serialize + * @param operation an <code>INSERT</code> or <code>UPDATE</code> operation + * @param journalKey the journal key for the block where the record is written + */ + public RecordEntry(Serializable object, short operation, long[] journalKey, long expiration) { + assert object != null; + this.object = object; + this.operation = operation; + this.journalKeys = journalKey; + this.expiration = expiration; + } + + /** + * Returns the object + * + * @return the object + */ + public Serializable getObject() { + return object; + } + + /** + * Returns the type of operation + * + * @return the type of operation + */ + public short getOperation() { + return operation; + } + + public long getExpiration() { + return expiration; + } + + public long[] getJournalKeys() { + return journalKeys; + } + + public void setJournalKeys(long[] journalKeys) { + this.journalKeys = journalKeys; + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordKey.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordKey.java new file mode 100644 index 0000000000..7293fddb55 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/RecordKey.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import org.apache.tuscany.spi.component.SCAObject; + +/** + * Used by the store cache to retrieve record entries + * + * @version $Rev$ $Date$ + */ +public class RecordKey { + + private String id; + private SCAObject owner; + + public RecordKey(String id, SCAObject owner) { + this.id = id; + this.owner = owner; + } + + public String getId() { + return id; + } + + public SCAObject getOwner() { + return owner; + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final RecordKey recordKey = (RecordKey) o; + if (id != null ? !id.equals(recordKey.id) : recordKey.id != null) { + return false; + } + return !(owner != null ? !owner.getUri().equals(recordKey.owner.getUri()) : + recordKey.owner != null); + } + + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (owner != null ? owner.hashCode() : 0); + return result; + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/SerializationHelper.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/SerializationHelper.java new file mode 100644 index 0000000000..0a7197b014 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/SerializationHelper.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.SCAExternalizable; +import org.apache.tuscany.spi.component.WorkContext; + +/** + * Utility methods for processing journal records + * + * @version $Rev$ $Date$ + */ +public final class SerializationHelper { + + private SerializationHelper() { + } + + /** + * Serializes and object + * + * @param serializable the object to serialize + * @throws IOException + */ + public static byte[] serialize(Serializable serializable) throws IOException { + ByteArrayOutputStream bas = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bas); + out.writeObject(serializable); + return bas.toByteArray(); + } + + /** + * Deserializes an object using the TCCL + * + * @param bytes the serialized object byte array + * @param workContext the current work context + */ + public static Object deserialize(byte[] bytes, WorkContext workContext) throws IOException, ClassNotFoundException { + Object o = new TCCLObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); + if (o instanceof SCAExternalizable) { + SCAExternalizable externalizable = (SCAExternalizable) o; + externalizable.setWorkContext(workContext); + externalizable.reactivate(); + } + return o; + } + + /** + * Breaks a byte array into a series of blocks of the given size + * + * @param bytes the byte array to partition + * @param size the partition size + */ + public static List<byte[]> partition(byte[] bytes, int size) { + assert size > 0; + List<byte[]> list = new ArrayList<byte[]>(); + int pos = 0; + while (pos < bytes.length) { + if (pos + size > bytes.length) { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + for (int i = pos; i < bytes.length; i++) { + stream.write(bytes[i]); + } + byte[] partition = stream.toByteArray(); + list.add(partition); + pos = pos + partition.length; + } else { + byte[] partition = new byte[size]; + for (int i = 0; i < size; i++) { + partition[i] = bytes[pos + i]; + } + list.add(partition); + pos = pos + size; + } + } + return list; + } + + /** + * Creates a serialized header entry that may be written to a log + * + * @param operation the operation type, i.e. {@link Header#INSERT}, {@link Header#UPDATE}, or {@link + * JournalStore#DELETE} + * @param numRecords the number of blocks that the record will be written two excluding the header block + * @param ownerId the id of the owner of the record + * @param id the id of the record unique to the owner + * @param expiration the record expirtation time in milliseconds + * @return a byte array containing the serialized header + * @throws IOException + */ + public static byte[] serializeHeader(short operation, int numRecords, String ownerId, String id, long expiration) + throws IOException { + ByteArrayOutputStream stream = null; + ObjectOutputStream ostream = null; + try { + stream = new ByteArrayOutputStream(); + ostream = new ObjectOutputStream(stream); + ostream.writeShort(operation); + ostream.writeInt(numRecords); + ostream.writeObject(ownerId); + ostream.writeObject(id); + ostream.writeLong(expiration); + ostream.flush(); + return stream.toByteArray(); + } finally { + if (ostream != null) { + try { + ostream.close(); + } catch (IOException e) { + // ignore + } + } + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + } + } + + /** + * Serializes a unique record id consisting of the owner id and the record's UUID + * + * @param ownerId the id of the owner, typically an SCAObject canonical name + * @param id the id associated with the record + * @return the serialized record byte array + * @throws IOException + */ + public static byte[] serializeRecordId(String ownerId, String id) + throws IOException { + ByteArrayOutputStream stream = null; + ObjectOutputStream ostream = null; + try { + stream = new ByteArrayOutputStream(); + ostream = new ObjectOutputStream(stream); + ostream.writeObject(ownerId); + ostream.writeObject(id); + ostream.flush(); + return stream.toByteArray(); + } finally { + if (ostream != null) { + try { + ostream.close(); + } catch (IOException e) { + // ignore + } + } + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + } + } + + /** + * Deserializes the given header. The first element from {@link Header#getFields()} is assumed to contain the header + * byte array to deserialize from + * + * @param header the header to deserialize + * @return the deserialized header + * @throws IOException + * @throws ClassNotFoundException + */ + public static Header deserializeHeader(Header header) throws IOException, ClassNotFoundException { + ByteArrayInputStream bas = null; + ObjectInputStream stream = null; + try { + bas = new ByteArrayInputStream(header.getFields()[0]); + stream = new TCCLObjectInputStream(bas); + header.setOperation(stream.readShort()); + header.setNumBlocks(stream.readInt()); + header.setOwnerId((String) stream.readObject()); + header.setId((String) stream.readObject()); + header.setExpiration(stream.readLong()); + return header; + } finally { + if (bas != null) { + try { + bas.close(); + } catch (IOException e) { + // ignore + } + } + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + } + + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/TCCLObjectInputStream.java b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/TCCLObjectInputStream.java new file mode 100644 index 0000000000..b341f9f9b9 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/main/java/org/apache/tuscany/persistence/store/journal/TCCLObjectInputStream.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; + +/** + * Deserializes an object based on the thread context classloader + * + * @version $Rev$ $Date$ + */ +public class TCCLObjectInputStream extends ObjectInputStream { + private final ClassLoader classLoader; + + public TCCLObjectInputStream(InputStream in) throws IOException, SecurityException { + super(in); + this.classLoader = Thread.currentThread().getContextClassLoader(); + } + + protected Class resolveClass(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException { + return classLoader.loadClass(streamClass.getName()); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreExpireTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreExpireTestCase.java new file mode 100644 index 0000000000..4e23b3ca72 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreExpireTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.net.URI; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.event.RuntimeEventListener; +import org.apache.tuscany.spi.services.store.StoreExpirationEvent; +import org.apache.tuscany.spi.services.store.StoreMonitor; + +import junit.framework.TestCase; +import org.easymock.IAnswer; +import org.easymock.classextension.EasyMock; +import org.objectweb.howl.log.LogEventListener; + +/** + * @version $Rev$ $Date$ + */ +public class JournalStoreExpireTestCase extends TestCase { + @SuppressWarnings({"FieldCanBeLocal"}) + private JournalStore store; + private SCAObject owner; + + public void testNotifyOnExpire() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + StoreMonitor monitor = EasyMock.createMock(StoreMonitor.class); + Journal journal = EasyMock.createNiceMock(Journal.class); + journal.setLogEventListener(EasyMock.isA(LogEventListener.class)); + EasyMock.replay(journal); + + RuntimeEventListener listener = org.easymock.EasyMock.createMock(RuntimeEventListener.class); + listener.onEvent(org.easymock.EasyMock.isA(StoreExpirationEvent.class)); + EasyMock.expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.countDown(); + return null; + } + }); + org.easymock.EasyMock.replay(listener); + + store = new JournalStore(monitor, journal) { + }; + store.addListener(listener); + store.init(); + final String id = UUID.randomUUID().toString(); + store.insertRecord(owner, id, "test", 1); + if (!latch.await(10000, TimeUnit.MILLISECONDS)) { + // failed to notify listener + fail(); + } + store.destroy(); + EasyMock.verify(listener); + } + + + protected void setUp() throws Exception { + super.setUp(); + TestUtils.cleanupLog(); + owner = EasyMock.createMock(SCAObject.class); + URI uri = URI.create("foo"); + EasyMock.expect(owner.getUri()).andReturn(uri).atLeastOnce(); + EasyMock.replay(owner); + } + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanupLog(); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreInsertTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreInsertTestCase.java new file mode 100644 index 0000000000..a2cab56134 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreInsertTestCase.java @@ -0,0 +1,134 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.util.UUID; +import java.net.URI; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.services.store.Store; +import org.apache.tuscany.spi.services.store.StoreMonitor; + +import junit.framework.TestCase; +import org.easymock.IAnswer; +import org.easymock.classextension.EasyMock; +import org.objectweb.howl.log.LogEventListener; + +/** + * @version $Rev$ $Date$ + */ +public class JournalStoreInsertTestCase extends TestCase { + @SuppressWarnings({"FieldCanBeLocal"}) + private JournalStore store; + private SCAObject owner; + + public void testOrderedShutdown() throws Exception { + StoreMonitor monitor = EasyMock.createMock(StoreMonitor.class); + Journal journal = EasyMock.createMock(Journal.class); + journal.setLogEventListener(EasyMock.isA(LogEventListener.class)); + journal.open(); + journal.close(); + EasyMock.replay(journal); + store = new JournalStore(monitor, journal) { + }; + store.init(); + store.destroy(); + EasyMock.verify(journal); + } + + public void testInsertRecord() throws Exception { + StoreMonitor monitor = EasyMock.createMock(StoreMonitor.class); + Journal journal = EasyMock.createMock(Journal.class); + journal.setLogEventListener(EasyMock.isA(LogEventListener.class)); + journal.open(); + final String id = UUID.randomUUID().toString(); + EasyMock.expect(journal.writeHeader(EasyMock.isA(byte[].class), EasyMock.eq(false))) + .andStubAnswer(new IAnswer<Long>() { + public Long answer() throws Throwable { + Header header = new Header(); + header.setFields(new byte[][]{(byte[]) EasyMock.getCurrentArguments()[0]}); + // deserialize the message to test the format is correct + SerializationHelper.deserializeHeader(header); + assertTrue("Operation not INSERT", Header.INSERT == header.getOperation()); + assertTrue("Expiration incorrect", Store.NEVER == header.getExpiration()); + assertTrue("Least significant id incorrect", + id.equals(header.getId())); + assertTrue("Most significant id incorrect", + id.equals(header.getId())); + assertTrue("Records incorrect", 1 == header.getNumBlocks()); + assertTrue("Owner id incorrect", "foo".equals(header.getOwnerId())); + return 1L; + } + }); + EasyMock.expect(journal.writeBlock(EasyMock.isA(byte[].class), EasyMock.isA(byte[].class), EasyMock.eq(true))) + .andStubAnswer(new IAnswer<Long>() { + public Long answer() throws Throwable { + byte[] payload = (byte[]) EasyMock.getCurrentArguments()[0]; + assertTrue("Block data incorrect", "test".equals(SerializationHelper.deserialize(payload, null))); + return 1L; + } + }); + journal.close(); + EasyMock.replay(journal); + store = new JournalStore(monitor, journal) { + }; + store.init(); + store.insertRecord(owner, id, "test", Store.NEVER); + store.destroy(); + EasyMock.verify(journal); + } + + /** + * Verifies that a written record will be cached. This is verified by the fact that long-term storage is never + * accessed. + */ + public void testInsertRecordCache() throws Exception { + StoreMonitor monitor = EasyMock.createMock(StoreMonitor.class); + Journal journal = EasyMock.createMock(Journal.class); + journal.setLogEventListener(EasyMock.isA(LogEventListener.class)); + journal.open(); + final String id = UUID.randomUUID().toString(); + EasyMock.expect(journal.writeHeader(EasyMock.isA(byte[].class), EasyMock.eq(false))).andReturn(1L); + EasyMock.expect(journal.writeBlock(EasyMock.isA(byte[].class), EasyMock.isA(byte[].class), EasyMock.eq(true))) + .andReturn(1L); + journal.close(); + EasyMock.replay(journal); + store = new JournalStore(monitor, journal) { + }; + store.init(); + store.insertRecord(owner, id, "test", Store.NEVER); + assertEquals("test", store.readRecord(owner, id)); + store.destroy(); + EasyMock.verify(journal); + } + + protected void setUp() throws Exception { + super.setUp(); + TestUtils.cleanupLog(); + owner = EasyMock.createMock(SCAObject.class); + URI uri = URI.create("foo"); + EasyMock.expect(owner.getUri()).andReturn(uri).atLeastOnce(); + EasyMock.replay(owner); + } + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanupLog(); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreOverflowTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreOverflowTestCase.java new file mode 100644 index 0000000000..61a77869c1 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalStoreOverflowTestCase.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.util.UUID; +import java.net.URI; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.services.store.StoreMonitor; + +import junit.framework.TestCase; +import org.easymock.classextension.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class JournalStoreOverflowTestCase extends TestCase { + @SuppressWarnings({"FieldCanBeLocal"}) + private JournalStore store; + private SCAObject owner; + + /** + * Validates records are moved forward during a log overflow + * + * @throws Exception + */ + public void testOverflow() throws Exception { + StoreMonitor monitor = EasyMock.createMock(StoreMonitor.class); + store = new JournalStore(monitor); + store.setMaxBlocksPerFile(3); + store.init(); + long expire = System.currentTimeMillis() + 200; + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); // + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire); + Thread.sleep(250); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire + 20000); + store.insertRecord(owner, UUID.randomUUID().toString(), "test", expire + 20000); + store.destroy(); + } + + + public void testOverflowAtInsertHeader() throws Exception { + + } + + public void testOverflowAtUpdateHeader() throws Exception { + + } + + public void testOverflowAtDeleteHeader() throws Exception { + + } + + public void testOverflowAtBlock() throws Exception { + + } + + protected void setUp() throws Exception { + super.setUp(); + TestUtils.cleanupLog(); + owner = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner.getUri()).andReturn(URI.create("foo")).atLeastOnce(); + EasyMock.replay(owner); + } + + protected void tearDown() throws Exception { + super.tearDown(); + TestUtils.cleanupLog(); + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalTestCase.java new file mode 100644 index 0000000000..2df83a0e74 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/JournalTestCase.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.ByteArrayOutputStream; +import java.util.UUID; + +import static org.apache.tuscany.spi.services.store.Store.NEVER; + +import junit.framework.TestCase; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeHeader; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeRecordId; +import org.objectweb.howl.log.Configuration; +import org.objectweb.howl.log.LogRecord; + +/** + * @version $Rev$ $Date$ + */ +public class JournalTestCase extends TestCase { + private Journal journal; + + public void testWriteHeader() throws Exception { + String id = UUID.randomUUID().toString(); + long key = journal.writeHeader(serializeHeader(Header.INSERT, 10, "foo/bar", id, NEVER), false); + LogRecord record = journal.get(null, key); + Header header = new Header(); + header.setFields(record.getFields()); + SerializationHelper.deserializeHeader(header); + assertTrue(record.type == Journal.HEADER); + assertEquals(Header.INSERT, header.getOperation()); + assertEquals(10, header.getNumBlocks()); + assertEquals("foo/bar", header.getOwnerId()); + assertEquals(id, header.getId()); + assertEquals(NEVER, header.getExpiration()); + } + + public void testWriteRecord() throws Exception { + byte[] recordId = serializeRecordId("foo", UUID.randomUUID().toString()); + long key = journal.writeBlock("this is a test".getBytes(), recordId, true); + LogRecord record = journal.get(null, key); + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + assertEquals(record.type, Journal.RECORD); + stream.write(record.getFields()[1]); + JournalRecord jrecord = new JournalRecord(stream.toByteArray()); + assertEquals("this is a test", new String(jrecord.getData())); + } + + protected void setUp() throws Exception { + super.setUp(); + TestUtils.cleanupLog(); + Configuration config = new Configuration(); + config.setLogFileDir("../stores"); + journal = new Journal(config); + journal.open(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + journal.close(); + TestUtils.cleanupLog(); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/MockSCAExternalizable.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/MockSCAExternalizable.java new file mode 100644 index 0000000000..62e8a50635 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/MockSCAExternalizable.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +import org.apache.tuscany.spi.component.ReactivationException; +import org.apache.tuscany.spi.component.SCAExternalizable; +import org.apache.tuscany.spi.component.WorkContext; + +/** + * @version $Rev$ $Date$ + */ +public class MockSCAExternalizable implements Externalizable, SCAExternalizable { + private WorkContext context; + private boolean reactivated; + + public void writeExternal(ObjectOutput out) throws IOException { + + } + + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + + } + + public boolean isReactivated() { + return reactivated; + } + + public void setWorkContext(WorkContext context) { + this.context = context; + } + + public void reactivate() throws ReactivationException { + assert context != null : "WorkContext not properly set"; + reactivated = true; + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/RecordKeyTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/RecordKeyTestCase.java new file mode 100644 index 0000000000..ddd69a1f54 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/RecordKeyTestCase.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.net.URI; + +import org.apache.tuscany.spi.component.SCAObject; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class RecordKeyTestCase extends TestCase { + + public void testEquals() throws Exception { + String id = "bar"; + URI uri = URI.create("foo"); + SCAObject owner1 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner1.getUri()).andReturn(uri); + EasyMock.replay(owner1); + SCAObject owner2 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner2.getUri()).andReturn(uri); + EasyMock.replay(owner2); + + RecordKey key1 = new RecordKey(id, owner1); + RecordKey key2 = new RecordKey(id, owner2); + assertEquals(key1, key2); + } + + public void testNotEqualsId() throws Exception { + String id = "bar"; + SCAObject owner1 = EasyMock.createMock(SCAObject.class); + URI uri = URI.create("foo"); + EasyMock.expect(owner1.getUri()).andReturn(uri); + EasyMock.replay(owner1); + SCAObject owner2 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner2.getUri()).andReturn(uri); + EasyMock.replay(owner2); + RecordKey key1 = new RecordKey(id, owner1); + RecordKey key2 = new RecordKey("baz", owner2); + assertFalse(key1.equals(key2)); + } + + public void testNotEqualsOwner() throws Exception { + String id = "bar"; + URI fooUri = URI.create("foo"); + SCAObject owner1 = EasyMock.createMock(SCAObject.class); + EasyMock.expect(owner1.getUri()).andReturn(fooUri); + EasyMock.replay(owner1); + SCAObject owner2 = EasyMock.createMock(SCAObject.class); + URI barUri = URI.create("bar"); + EasyMock.expect(owner2.getUri()).andReturn(barUri); + EasyMock.replay(owner2); + RecordKey key1 = new RecordKey(id, owner1); + RecordKey key2 = new RecordKey(id, owner2); + assertFalse(key1.equals(key2)); + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/SerializationHelperTestCase.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/SerializationHelperTestCase.java new file mode 100644 index 0000000000..160e4c7a23 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/SerializationHelperTestCase.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.util.List; +import java.util.UUID; + +import org.apache.tuscany.spi.component.WorkContext; +import static org.apache.tuscany.spi.services.store.Store.NEVER; + +import junit.framework.TestCase; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.deserialize; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class SerializationHelperTestCase extends TestCase { + + public void testTwoEvenChunks() throws Exception { + byte[] bytes = "this is a test".getBytes(); + List<byte[]> chunks = SerializationHelper.partition(bytes, 7); + assertEquals(2, chunks.size()); + assertEquals("this is", new String(chunks.get(0))); + assertEquals(" a test", new String(chunks.get(1))); + } + + public void testUnevenChunks() throws Exception { + byte[] bytes = "this is a test123".getBytes(); + List<byte[]> chunks = SerializationHelper.partition(bytes, 7); + assertEquals(3, chunks.size()); + assertEquals("this is", new String(chunks.get(0))); + assertEquals(" a test", new String(chunks.get(1))); + assertEquals("123", new String(chunks.get(2))); + } + + public void testChunkSizeGreater() throws Exception { + byte[] bytes = "this is a test".getBytes(); + List<byte[]> chunks = SerializationHelper.partition(bytes, 512); + assertEquals(1, chunks.size()); + byte[] chunk = chunks.get(0); + assertEquals(14, chunk.length); + assertEquals("this is a test", new String(chunk)); + } + + public void testSerializeDeserializeNonSCAExternalizable() throws Exception { + byte[] bytes = SerializationHelper.serialize("foo"); + assertEquals("foo", deserialize(bytes, null)); + } + + public void testSerializeDeserializeSCAExternalizable() throws Exception { + byte[] bytes = SerializationHelper.serialize(new MockSCAExternalizable()); + WorkContext context = EasyMock.createNiceMock(WorkContext.class); + MockSCAExternalizable externalized = (MockSCAExternalizable) deserialize(bytes, context); + assertTrue(externalized.isReactivated()); + } + + public void testDeserializeHeader() throws Exception { + String id = UUID.randomUUID().toString(); + byte[] bytes = SerializationHelper.serializeHeader(Header.INSERT, 2, "foo", id, NEVER); + Header header = SerializationHelper.deserializeHeader(new MockHeader(bytes)); + assertEquals(Header.INSERT, header.getOperation()); + assertEquals(2, header.getNumBlocks()); + assertEquals("foo", header.getOwnerId()); + assertEquals(id, header.getId()); + assertEquals(NEVER, header.getExpiration()); + } + + private class MockHeader extends Header { + public MockHeader(byte[] bytes) { + super(); + fields = new byte[][]{bytes}; + } + } + + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/TestUtils.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/TestUtils.java new file mode 100644 index 0000000000..5fb2ebeb82 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/TestUtils.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal; + +import java.io.File; + +/** + * JournalThroughputTest case utilities + * + * @version $Rev$ $Date$ + */ +public final class TestUtils { + + private TestUtils() { + + } + + /** + * Removes log files from disk + */ + public static void cleanupLog() { + File dir = new File("../stores"); + if (!dir.exists()) { + return; + } + for (File file : dir.listFiles()) { + file.delete(); + } + dir.delete(); + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/Foo.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/Foo.java new file mode 100644 index 0000000000..d9c7aee660 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/Foo.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal.performance; + +import java.io.Serializable; + +/** + * @version $Rev$ $Date$ + */ +@SuppressWarnings({"SerializableHasSerializationMethods"}) +public class Foo implements Serializable { + private static final long serialVersionUID = -1003664515513709814L; + protected String baz; + protected int bar; + + public Foo(String baz, int bar) { + this.baz = baz; + this.bar = bar; + } + + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + public int getBar() { + return bar; + } + + public void setBar(int bar) { + this.bar = bar; + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalStoreThroughputTest.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalStoreThroughputTest.java new file mode 100644 index 0000000000..eeb566f182 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalStoreThroughputTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal.performance; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; + +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.apache.tuscany.persistence.store.journal.JournalShutdownException; +import org.apache.tuscany.persistence.store.journal.JournalStore; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serialize; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeRecordId; +import org.apache.tuscany.persistence.store.journal.TestUtils; + +/** + * Runs a basic throughput tests on JournalStore operations + * <p/> + * TODO this should be integrated with a Maven itest-based performance harness + * + * @version $Rev$ $Date$ + */ +public class JournalStoreThroughputTest { + private static final int SIZE = 1000; + private CyclicBarrier barrier; + private JournalStore store; + private long now; + private SCAObject owner = new MockSCAObject(); + private String id = UUID.randomUUID().toString(); + private CountDownLatch latch = new CountDownLatch(1); + private long expire = System.currentTimeMillis() + 10000; + private Foo object = new Foo("this is a test", 1); + + public static void main(String[] args) throws Exception { + JournalStoreThroughputTest test = new JournalStoreThroughputTest(); + test.testAppend(); + test.latch.await(5000, TimeUnit.MILLISECONDS); + } + + public void testAppend() throws Exception { + TestUtils.cleanupLog(); + store = new JournalStore(new MockMonitor()); + store.init(); + final Thread[] threads = new Thread[SIZE]; + barrier = new CyclicBarrier(SIZE, new Runnable() { + public void run() { + try { + System.out.println("-----------------------------------------------------"); + System.out.println("JournalStore.append()"); + byte[] idBytes = serializeRecordId(owner.getUri().toString(), id); + byte[] bytes = serialize(object); + System.out.println("Approx record size :" + (bytes.length + idBytes.length)); + System.out.println("Total threads :" + barrier.getNumberWaiting()); + System.out.println("Forced writes :" + barrier.getNumberWaiting()); + System.out.println("Time:" + (System.currentTimeMillis() - now)); + store.destroy(); + latch.countDown(); + } catch (JournalShutdownException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + for (int i = 0; i < SIZE; i++) { + threads[i] = new Thread(new InsertWorker(true)); + } + now = System.currentTimeMillis(); + for (int i = 0; i < SIZE; i++) { + threads[i].start(); + } + } + + private class InsertWorker implements Runnable { + boolean forced; + + public InsertWorker(boolean forced) { + this.forced = forced; + } + + public void run() { + try { + store.insertRecord(owner, id, object, expire); + barrier.await(); + } catch (StoreWriteException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalThroughputTest.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalThroughputTest.java new file mode 100644 index 0000000000..7a3e8fa308 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/JournalThroughputTest.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal.performance; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; + +import org.apache.tuscany.spi.services.store.StoreWriteException; + +import org.apache.tuscany.persistence.store.journal.Journal; +import static org.apache.tuscany.persistence.store.journal.SerializationHelper.serializeRecordId; +import org.apache.tuscany.persistence.store.journal.TestUtils; + +/** + * Runs a basic throughput tests on Journal operations + * <p/> + * TODO this should be integrated with a Maven itest-based performance harness + * + * @version $Rev$ $Date$ + */ +public class JournalThroughputTest { + private static final int SIZE = 1000; + private CyclicBarrier barrier; + private Journal journal; + private byte[] bytes; + private byte[] recordId; + private long now; + private CountDownLatch latch = new CountDownLatch(1); + + public static void main(String[] args) throws Exception { + JournalThroughputTest test = new JournalThroughputTest(); + test.testForcedWrites(); + test.latch.await(5000, TimeUnit.MILLISECONDS); + test.testNonForcedWrites(); + } + + public void testForcedWrites() throws Exception { + TestUtils.cleanupLog(); + journal = new Journal(); + journal.open(); + recordId = serializeRecordId("foo", UUID.randomUUID().toString()); + bytes = "this is a test".getBytes(); + final Thread[] threads = new Thread[SIZE]; + barrier = new CyclicBarrier(SIZE, new Runnable() { + public void run() { + System.out.println("-----------------------------------------------------"); + System.out.println("Journal.writeBlock() using forced writes"); + System.out.println("Approx record size :" + (recordId.length + bytes.length)); + System.out.println("Total threads :" + barrier.getNumberWaiting()); + System.out.println("Forced writes :" + barrier.getNumberWaiting()); + System.out.println("Time:" + (System.currentTimeMillis() - now)); + try { + journal.close(); + latch.countDown(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }); + for (int i = 0; i < SIZE; i++) { + threads[i] = new Thread(new Worker(true)); + } + now = System.currentTimeMillis(); + for (int i = 0; i < SIZE; i++) { + threads[i].start(); + } + } + + public void testNonForcedWrites() throws Exception { + TestUtils.cleanupLog(); + journal = new Journal(); + journal.open(); + recordId = serializeRecordId("foo", UUID.randomUUID().toString()); + bytes = "this is a test".getBytes(); + final Thread[] threads = new Thread[SIZE]; + barrier = new CyclicBarrier(SIZE, new Runnable() { + public void run() { + System.out.println("-----------------------------------------------------"); + System.out.println("Journal.writeBlock() using non-forced writes"); + System.out.println("Approx record size :" + (recordId.length + bytes.length)); + System.out.println("Total threads :" + barrier.getNumberWaiting()); + System.out.println("Forced writes :" + barrier.getNumberWaiting()); + System.out.println("Time:" + (System.currentTimeMillis() - now)); + System.out.println("-----------------------------------------------------"); + try { + journal.close(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }); + for (int i = 0; i < SIZE; i++) { + threads[i] = new Thread(new Worker(false)); + } + now = System.currentTimeMillis(); + for (int i = 0; i < SIZE; i++) { + threads[i].start(); + } + } + + private class Worker implements Runnable { + boolean forced; + + public Worker(boolean forced) { + this.forced = forced; + } + + public void run() { + try { + journal.writeBlock(bytes, recordId, forced); + barrier.await(); + } catch (StoreWriteException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockMonitor.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockMonitor.java new file mode 100644 index 0000000000..a62630ebe0 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockMonitor.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal.performance; + +import org.apache.tuscany.spi.services.store.StoreMonitor; + +import org.apache.tuscany.api.annotation.LogLevel; + +/** + * @version $Rev$ $Date$ + */ +public class MockMonitor implements StoreMonitor { + @LogLevel("DEBUG") + public void start(String msg) { + + } + + @LogLevel("DEBUG") + public void stop(String msg) { + + } + + @LogLevel("DEBUG") + public void beginRecover() { + + } + + @LogLevel("DEBUG") + public void endRecover() { + + } + + @LogLevel("DEBUG") + public void recover(Object recordId) { + + } + + @LogLevel("ERROR") + public void error(Throwable e) { + + } +} diff --git a/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockSCAObject.java b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockSCAObject.java new file mode 100644 index 0000000000..e9ecdbab28 --- /dev/null +++ b/sandbox/old/contrib/persistence/store.journal/src/test/java/org/apache/tuscany/persistence/store/journal/performance/MockSCAObject.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.persistence.store.journal.performance; + +import java.net.URI; + +import org.apache.tuscany.spi.CoreRuntimeException; +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.event.Event; +import org.apache.tuscany.spi.event.EventFilter; +import org.apache.tuscany.spi.event.RuntimeEventListener; + +/** + * @version $Rev$ $Date$ + */ +public class MockSCAObject implements SCAObject { + + public URI getUri() { + return null; + } + + public void publish(Event object) { + + } + + public void addListener(RuntimeEventListener listener) { + + } + + public void addListener(EventFilter filter, RuntimeEventListener listener) { + + } + + public void removeListener(RuntimeEventListener listener) { + + } + + public int getLifecycleState() { + return 0; + } + + public void start() throws CoreRuntimeException { + + } + + public void stop() throws CoreRuntimeException { + + } + +} |