index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/BaseClass.java | package org.apache.aries.transaction.pojo;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
@Transactional(value=TxType.REQUIRED)
public class BaseClass {
@Transactional(value=TxType.NEVER)
public void defaultType(String test) {
}
public void supports(String test) {
}
}
| 7,700 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/ExtendedPojo.java | package org.apache.aries.transaction.pojo;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
public class ExtendedPojo extends BaseClass {
@Override
public void defaultType(String test) {
}
@Transactional(value=TxType.SUPPORTS)
@Override
public void supports(String test) {
}
}
| 7,701 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/pojo/BadlyAnnotatedPojo1.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction.pojo;
import javax.transaction.Transactional;
public class BadlyAnnotatedPojo1 {
@Transactional
private void doesNotWork() {
}
}
| 7,702 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/ComponentTxData.java | package org.apache.aries.transaction;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ComponentTxData {
private static final Logger LOG = LoggerFactory.getLogger(ComponentTxData.class);
private static final int BANNED_MODIFIERS = Modifier.PRIVATE | Modifier.STATIC;
private Map<Method, Optional<TransactionalAnnotationAttributes>> txMap = new ConcurrentHashMap<Method, Optional<TransactionalAnnotationAttributes>>();
private boolean isTransactional;
private Class<?> beanClass;
public ComponentTxData(Class<?> c) {
beanClass = c;
isTransactional = false;
// Check class hierarchy
Class<?> current = c;
while (current != Object.class) {
isTransactional |= parseTxData(current);
for (Class<?> iface : current.getInterfaces()) {
isTransactional |= parseTxData(iface);
}
current = current.getSuperclass();
}
}
Optional<TransactionalAnnotationAttributes> getEffectiveType(Method m) {
if (txMap.containsKey(m)) {
return getTxAttr(m);
}
try {
Method effectiveMethod = beanClass.getDeclaredMethod(m.getName(), m.getParameterTypes());
Optional<TransactionalAnnotationAttributes> txAttr = getTxAttr(effectiveMethod);
txMap.put(m, txAttr);
return txAttr;
} catch (NoSuchMethodException e) { // NOSONAR
return getFromMethod(m);
} catch (SecurityException e) {
throw new RuntimeException("Security exception when determining effective method", e); // NOSONAR
}
}
private Optional<TransactionalAnnotationAttributes> getFromMethod(Method m) {
try {
Method effectiveMethod = beanClass.getMethod(m.getName(), m.getParameterTypes());
Optional<TransactionalAnnotationAttributes> txAttr = getTxAttr(effectiveMethod);
txMap.put(m, txAttr);
return txAttr;
} catch (NoSuchMethodException e1) {
LOG.debug("No method found when scanning for transactions", e1);
return Optional.empty();
} catch (SecurityException e1) {
throw new RuntimeException("Security exception when determining effective method", e1); // NOSONAR
}
}
private Optional<TransactionalAnnotationAttributes> getTxAttr(Method method) {
Optional<TransactionalAnnotationAttributes> txAttr = txMap.get(method);
if (txAttr == null) {
return Optional.empty();
} else {
return txAttr;
}
}
private boolean parseTxData(Class<?> c) {
boolean shouldAssignInterceptor = false;
Transactional classAnnotation = c.getAnnotation(Transactional.class);
TxType defaultType = getType(classAnnotation);
if (defaultType != null) {
shouldAssignInterceptor = true;
}
for (Method m : c.getDeclaredMethods()) {
try {
Transactional methodAnnotation = m.getAnnotation(Transactional.class);
TxType t = getType(methodAnnotation);
if (t != null) {
TransactionalAnnotationAttributes txData = new TransactionalAnnotationAttributes(t,
methodAnnotation.dontRollbackOn(), methodAnnotation.rollbackOn());
assertAllowedModifier(m);
txMap.put(m, Optional.of(txData));
shouldAssignInterceptor = true;
} else if (defaultType != null){
txMap.put(m, Optional.of(new TransactionalAnnotationAttributes(defaultType, classAnnotation.dontRollbackOn(),
classAnnotation.rollbackOn())));
}
} catch(IllegalStateException e) {
LOG.warn("Invalid transaction annoation found", e);
}
}
return shouldAssignInterceptor;
}
private static TxType getType(Transactional jtaT) {
return (jtaT != null) ? jtaT.value() : null;
}
private static void assertAllowedModifier(Method m) {
if ((m.getModifiers() & BANNED_MODIFIERS) != 0) {
throw new IllegalArgumentException("Transaction annotation is not allowed on private or static method " + m);
}
}
public boolean isTransactional() {
return isTransactional;
}
public Class<?> getBeanClass() {
return beanClass;
}
}
| 7,703 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/TransactionAttribute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.InvalidTransactionException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.Transactional.TxType;
/**
* TODO This is copied from aries transaction. We could share this code
*/
public enum TransactionAttribute {
MANDATORY
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException
{
if (man.getStatus() == Status.STATUS_NO_TRANSACTION) {
throw new IllegalStateException("No transaction present when calling method that mandates a transaction.");
}
return new TransactionToken(man.getTransaction(), null, MANDATORY, false, false);
}
},
NEVER
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException
{
if (man.getStatus() == Status.STATUS_ACTIVE) {
throw new IllegalStateException("Transaction present when calling method that forbids a transaction.");
}
return new TransactionToken(null, null, NEVER, false, false);
}
},
NOT_SUPPORTED
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException
{
if (man.getStatus() == Status.STATUS_ACTIVE) {
return new TransactionToken(null, man.suspend(), NOT_SUPPORTED, false, true);
}
return new TransactionToken(null, null, NOT_SUPPORTED, false, false);
}
@Override
public void finish(TransactionManager man, TransactionToken tranToken) throws SystemException,
InvalidTransactionException
{
Transaction tran = tranToken.getSuspendedTransaction();
if (tran != null) {
man.resume(tran);
}
}
},
REQUIRED
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException, NotSupportedException
{
if (man.getStatus() == Status.STATUS_NO_TRANSACTION) {
man.begin();
return new TransactionToken(man.getTransaction(), null, REQUIRED, true, true);
}
return new TransactionToken(man.getTransaction(), null, REQUIRED, false, false);
}
@Override
public void finish(TransactionManager man, TransactionToken tranToken) throws SystemException,
InvalidTransactionException, RollbackException,
HeuristicMixedException, HeuristicRollbackException
{
if (tranToken.isCompletionAllowed()) {
if (man.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
man.rollback();
} else {
man.commit();
}
}
}
},
REQUIRES_NEW
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException, NotSupportedException,
InvalidTransactionException
{
Transaction suspendedTransaction = (man.getStatus() == Status.STATUS_ACTIVE) ? man.suspend() : null;
try {
man.begin();
} catch (SystemException e) {
man.resume(suspendedTransaction);
throw e;
} catch (NotSupportedException e) {
man.resume(suspendedTransaction);
throw e;
}
return new TransactionToken(man.getTransaction(), suspendedTransaction, REQUIRES_NEW, true, true);
}
@Override
public void finish(TransactionManager man, TransactionToken tranToken) throws SystemException,
InvalidTransactionException, RollbackException,
HeuristicMixedException, HeuristicRollbackException
{
if (tranToken.isCompletionAllowed()) {
if (man.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
man.rollback();
} else {
man.commit();
}
}
Transaction tran = tranToken.getSuspendedTransaction();
if (tran != null) {
man.resume(tran);
}
}
},
SUPPORTS
{
@Override
public TransactionToken begin(TransactionManager man) throws SystemException, NotSupportedException,
InvalidTransactionException
{
if (man.getStatus() == Status.STATUS_ACTIVE) {
return new TransactionToken(man.getTransaction(), null, SUPPORTS, false, false);
}
return new TransactionToken(null, null, SUPPORTS, false, false);
}
};
public static TransactionAttribute fromValue(TxType type)
{
return valueOf(type.name());
}
public TransactionToken begin(TransactionManager man) throws SystemException, NotSupportedException, InvalidTransactionException // NOSONAR
{
return null;
}
public void finish(TransactionManager man, TransactionToken tranToken) throws SystemException, // NOSONAR
InvalidTransactionException, RollbackException,
HeuristicMixedException, HeuristicRollbackException
{
// No operation by default
}
}
| 7,704 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/TxInterceptorImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction;
import java.lang.reflect.Method;
import java.util.Optional;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.apache.aries.blueprint.Interceptor;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.Coordinator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TxInterceptorImpl implements Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(TxInterceptorImpl.class);
private TransactionManager tm;
private Coordinator coordinator;
private ComponentTxData txData;
public TxInterceptorImpl(TransactionManager tm, Coordinator coordinator, ComponentTxData txData) {
this.tm = tm;
this.coordinator = coordinator;
this.txData = txData;
}
@Override
public int getRank() {
return 1; // Higher rank than jpa interceptor to make sure transaction is started first
}
@Override
public Object preCall(ComponentMetadata cm, Method m, Object... parameters) throws Throwable {
final Optional<TransactionalAnnotationAttributes> type = txData.getEffectiveType(m);
if (!type.isPresent()) {
// No transaction
return null;
}
TransactionAttribute txAttribute = TransactionAttribute.fromValue(type.get().getTxType());
LOGGER.debug("PreCall for bean {}, method {} with tx strategy {}.", getCmId(cm), m.getName(), txAttribute);
TransactionToken token = txAttribute.begin(tm);
boolean requiresNewCoordination = token.requiresNewCoordination();
if (!requiresNewCoordination && !transactionExists(coordinator)) {
// in case the txAttribute doesn't require new coordination AND there's active transaction, like in:
// - REQUIRED, when there was TX active before the method
// - SUPPORTS, when there was TX active before the method
// - MANDATORY, when there was TX active before the method
// we still have to create coordination
if (token.getActiveTransaction() != null && tm.getStatus() == Status.STATUS_ACTIVE) {
requiresNewCoordination = true;
}
}
if (requiresNewCoordination) {
String coordName = "txInterceptor." + m.getDeclaringClass().getName() + "." + m.getName();
Coordination coord = coordinator.begin(coordName , 0);
// @javax.transaction.Transactional is only part of 1.2 and even if it's about time that all previous
// JTA versions should be forgotten, we can't rely on it...
coord.getVariables().put(Transaction.class, txAttribute.name());
token.setCoordination(coord);
}
return token;
}
/**
* Checks whether there's already a {@link Coordination} with {@link Transaction} variable
* @param coordinator
* @return
*/
private boolean transactionExists(Coordinator coordinator) {
boolean exists = false;
Coordination coord = coordinator.peek();
while (coord != null) {
if (coord.getVariables().containsKey(Transaction.class)) {
return true;
}
coord = coord.getEnclosingCoordination();
}
return exists;
}
@Override
public void postCallWithException(ComponentMetadata cm, Method m, Throwable ex, Object preCallToken) {
if (!(preCallToken instanceof TransactionToken)) {
return;
}
LOGGER.debug("PostCallWithException for bean {}, method {}.", getCmId(cm), m.getName(), ex);
final TransactionToken token = (TransactionToken)preCallToken;
safeEndCoordination(token);
try {
Transaction tran = token.getActiveTransaction();
if (tran != null && isRollBackException(ex, m)) {
tran.setRollbackOnly();
LOGGER.debug("Setting transaction to rollback only because of exception ", ex);
}
token.getTransactionAttribute().finish(tm, token);
} catch (Exception e) {
// we do not throw the exception since there already is one, but we need to log it
LOGGER.warn("Exception during transaction cleanup", e);
}
}
@Override
public void postCallWithReturn(ComponentMetadata cm, Method m, Object returnType, Object preCallToken)
throws Exception {
LOGGER.debug("PostCallWithReturn for bean {}, method {}.", getCmId(cm), m);
// it is possible transaction is not involved at all
if (preCallToken == null) {
return;
}
if (!(preCallToken instanceof TransactionToken)) {
throw new IllegalStateException("Expected a TransactionToken from preCall but got " + preCallToken);
}
final TransactionToken token = (TransactionToken)preCallToken;
safeEndCoordination(token);
try {
token.getTransactionAttribute().finish(tm, token);
} catch (Exception e) {
// We are throwing an exception, so we don't error it out
LOGGER.debug("Exception while completing transaction.", e);
RollbackException rbe = new javax.transaction.RollbackException();
rbe.addSuppressed(e);
throw rbe;
}
}
private void safeEndCoordination(final TransactionToken token) {
try {
if (token != null && token.getCoordination() != null) {
token.getCoordination().end();
}
} catch (Exception e){
LOGGER.debug(e.getMessage(), e);
}
}
private static String getCmId(ComponentMetadata cm) {
return cm == null ? null : cm.getId();
}
private boolean isRollBackException(Throwable ex, Method m) {
if (m != null) {
Optional<TransactionalAnnotationAttributes> effectiveType = txData.getEffectiveType(m);
if (!effectiveType.isPresent()) {
return isUncheckedException(ex);
} else {
//check dontRollbackOn first, since according to spec it has precedence
for (Class dontRollbackClass : effectiveType.get().getDontRollbackOn()) {
if (dontRollbackClass.isInstance(ex)) {
LOGGER.debug("Current exception {} found in element dontRollbackOn.", ex.getClass());
return false;
}
}
//don't need to check further elements if ex is an unchecked exception
if (isUncheckedException(ex)) {
return true;
}
for (Class rollbackExceptionClass : effectiveType.get().getRollbackOn()) {
if (rollbackExceptionClass.isInstance(ex)) {
LOGGER.debug("Current exception {} found in element rollbackOn.", ex.getClass());
return true;
}
}
}
} else {
return isUncheckedException(ex);
}
return false;
}
private static boolean isUncheckedException(Throwable ex) {
return ex instanceof RuntimeException || ex instanceof Error;
}
}
| 7,705 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/TransactionToken.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction;
import javax.transaction.Transaction;
import org.osgi.service.coordinator.Coordination;
public class TransactionToken
{
private Transaction activeTransaction;
private Transaction suspendedTransaction;
private TransactionAttribute transactionAttribute;
private boolean isCompletionAllowed;
private boolean requiresNewCoordination;
private Coordination coordination;
public TransactionToken(Transaction activeTransaction, Transaction suspendedTransaction,
TransactionAttribute transactionAttribute)
{
this(activeTransaction, suspendedTransaction, transactionAttribute, false);
}
TransactionToken(Transaction activeTransaction, Transaction suspendedTransaction,
TransactionAttribute transactionAttribute, boolean isCompletionAllowed)
{
this(activeTransaction, suspendedTransaction, transactionAttribute, isCompletionAllowed, true);
}
TransactionToken(Transaction activeTransaction, Transaction suspendedTransaction,
TransactionAttribute transactionAttribute, boolean isCompletionAllowed,
boolean requiresNewCoordination)
{
this.activeTransaction = activeTransaction;
this.suspendedTransaction = suspendedTransaction;
this.transactionAttribute = transactionAttribute;
this.isCompletionAllowed = isCompletionAllowed;
this.requiresNewCoordination = requiresNewCoordination;
}
public Transaction getActiveTransaction() {
return activeTransaction;
}
public Transaction getSuspendedTransaction() {
return suspendedTransaction;
}
public void setSuspendedTransaction(Transaction suspendedTransaction) {
this.suspendedTransaction = suspendedTransaction;
}
public TransactionAttribute getTransactionAttribute() {
return transactionAttribute;
}
public void setTransactionStrategy(TransactionAttribute transactionAttribute) {
this.transactionAttribute = transactionAttribute;
}
public boolean isCompletionAllowed() {
return isCompletionAllowed;
}
public boolean requiresNewCoordination() {
return requiresNewCoordination;
}
public Coordination getCoordination() {
return coordination;
}
public void setCoordination(Coordination coordination) {
this.coordination = coordination;
}
} | 7,706 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/TransactionalAnnotationAttributes.java | package org.apache.aries.transaction;
import javax.transaction.Transactional.TxType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TransactionalAnnotationAttributes {
private TxType txType;
private List<Class> rollbackOn = new ArrayList<Class>();
private List<Class> dontRollbackOn = new ArrayList<Class>();
public TransactionalAnnotationAttributes(TxType defaultType) {
this.txType = defaultType;
}
public TransactionalAnnotationAttributes(TxType txType, Class[] dontRollbackOn, Class[] rollbackOn) {
this.txType = txType;
if (dontRollbackOn != null) {
this.dontRollbackOn = Arrays.asList(dontRollbackOn);
}
if (rollbackOn != null) {
this.rollbackOn = Arrays.asList(rollbackOn);
}
}
public TxType getTxType() {
return txType;
}
public void setTxType(TxType txType) {
this.txType = txType;
}
public List<Class> getRollbackOn() {
return rollbackOn;
}
public void setRollbackOn(List<Class> rollbackOn) {
this.rollbackOn = rollbackOn;
}
public List<Class> getDontRollbackOn() {
return dontRollbackOn;
}
public void setDontRollbackOn(List<Class> dontRollbackOn) {
this.dontRollbackOn = dontRollbackOn;
}
}
| 7,707 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/parsing/TxNamespaceHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction.parsing;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.transaction.TransactionManager;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutablePassThroughMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.coordinator.Coordinator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class TxNamespaceHandler implements NamespaceHandler {
public static final String TX_NAMESPACE_URI = "http://aries.apache.org/xmlns/transactions/v2.0.0";
public static final String ANNOTATION_PARSER_BEAN_NAME = ".org_apache_aries_transaction_annotations";
private static final Logger LOGGER = LoggerFactory.getLogger(TxNamespaceHandler.class);
private TransactionManager tm;
private Coordinator coordinator;
private final Map<String, String> schemaMap;
public TxNamespaceHandler() {
schemaMap = new HashMap<String, String>();
schemaMap.put(TX_NAMESPACE_URI, "transactionv20.xsd");
}
private void parseElement(Element elt, ParserContext pc)
{
LOGGER.debug("parser asked to parse element {} ", elt.getNodeName());
ComponentDefinitionRegistry cdr = pc.getComponentDefinitionRegistry();
if ("enable".equals(elt.getLocalName())) {
Node n = elt.getChildNodes().item(0);
if ((n == null || Boolean.parseBoolean(n.getNodeValue())) &&
!cdr.containsComponentDefinition(ANNOTATION_PARSER_BEAN_NAME)) {
LOGGER.debug("Enabling annotation based transactions");
MutableBeanMetadata meta = createAnnotationParserBean(pc, cdr);
cdr.registerComponentDefinition(meta);
}
}
}
private MutableBeanMetadata createAnnotationParserBean(ParserContext pc, ComponentDefinitionRegistry cdr) {
MutableBeanMetadata meta = pc.createMetadata(MutableBeanMetadata.class);
meta.setId(ANNOTATION_PARSER_BEAN_NAME);
meta.setRuntimeClass(AnnotationProcessor.class);
meta.setProcessor(true);
meta.addArgument(passThrough(pc, cdr), ComponentDefinitionRegistry.class.getName(), 0);
meta.addArgument(passThrough(pc, tm), TransactionManager.class.getName(), 1);
meta.addArgument(passThrough(pc, coordinator), Coordinator.class.getName(), 1);
return meta;
}
private MutablePassThroughMetadata passThrough(ParserContext pc, Object o) {
MutablePassThroughMetadata meta = pc.createMetadata(MutablePassThroughMetadata.class);
meta.setObject(o);
return meta;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata cm, ParserContext pc)
{
if (node instanceof Element) {
parseElement((Element) node, pc);
}
return cm;
}
@Override
public Metadata parse(Element elt, ParserContext pc)
{
parseElement(elt, pc);
return null;
}
@Override
public URL getSchemaLocation(String namespaceUri)
{
String xsdPath = schemaMap.get(namespaceUri);
return xsdPath != null ? this.getClass().getResource(xsdPath) : null;
}
public void setTm(TransactionManager tm) {
this.tm = tm;
}
public void setCoordinator(Coordinator coordinator) {
this.coordinator = coordinator;
}
@SuppressWarnings("rawtypes")
@Override
public Set<Class> getManagedClasses()
{
return Collections.emptySet();
}
}
| 7,708 |
0 | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-blueprint/src/main/java/org/apache/aries/transaction/parsing/AnnotationProcessor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction.parsing;
import javax.transaction.TransactionManager;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.transaction.ComponentTxData;
import org.apache.aries.transaction.TxInterceptorImpl;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.coordinator.Coordinator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Adds the transactional interceptor if Transaction annotation is present
* on bean class or superclasses.
*/
public class AnnotationProcessor implements BeanProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationProcessor.class);
private final ComponentDefinitionRegistry cdr;
private TransactionManager tm;
private Coordinator coordinator;
public AnnotationProcessor(ComponentDefinitionRegistry cdr, TransactionManager tm, Coordinator coordinator) {
this.cdr = cdr;
this.tm = tm;
this.coordinator = coordinator;
}
@Override
public void beforeDestroy(Object arg0, String arg1) {
// Nothing to be done
}
@Override
public void afterDestroy(Object arg0, String arg1) {
// Nothing to be done
}
@Override
public Object beforeInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData) {
ComponentTxData txData = new ComponentTxData(bean.getClass());
if (txData.isTransactional()) {
LOGGER.debug("Adding transaction interceptor to bean {} with class {}.", beanName, bean.getClass());
cdr.registerInterceptorWithComponent(beanData, new TxInterceptorImpl(tm, coordinator, txData));
}
return bean;
}
@Override
public Object afterInit(Object arg0, String arg1, BeanCreator arg2, BeanMetadata arg3) {
return arg0;
}
}
| 7,709 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/RequiresNewTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import static junit.framework.Assert.assertEquals;
import java.sql.SQLException;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class RequiresNewTest extends AbstractIntegrationTest {
@Inject
@Filter("(tranAttribute=RequiresNew)")
TestBean rnBean;
@Inject
@Filter("(tranAttribute=Required)")
TestBean rBean;
/**
* Test with client transaction - a container transaction is used to insert the row,
* user transaction roll back has no influence
* @throws Exception
*/
@Test
public void testClientTransactionRollback() throws Exception {
int initialRows = counter.countRows();
tran.begin();
rnBean.insertRow("testWithClientTran", 1, null);
tran.rollback();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
/**
* Test with client transaction and application exception - the container transaction is committed,
* the user transaction is not affected.
* @throws Exception
*/
@Test
public void testClientTransactionAndApplicationException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
rBean.insertRow("testWithClientTranAndWithAppException", 1, null);
try {
rnBean.insertRow("testWithClientTranAndWithAppException", 2, new SQLException("Dummy exception"));
} catch (SQLException e) {
// Ignore expected
}
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 2, finalRows - initialRows);
}
/**
* Test with client transaction and runtime exception - the container transaction is rolled back,
* the user transaction is not affected
* @throws Exception
*/
@Test
public void testClientTransactionAndRuntimeException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
rBean.insertRow("testWithClientTranAndWithRuntimeException", 1, null);
try {
rnBean.insertRow("testWithClientTranAndWithRuntimeException", 2, new RuntimeException("Dummy exception"));
} catch (RuntimeException e) {
// Ignore expected
}
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
/**
* Test without client transaction - a container transaction is used to insert the row
* @throws Exception
*/
//@Test
public void testNoClientTransaction() throws Exception {
clientTransaction = false;
assertInsertSuccesful();
testClientTransactionAndApplicationException();
testClientTransactionAndRuntimeException();
}
@Override
protected TestBean getBean() {
return rnBean;
}
}
| 7,710 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/RequiredTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class RequiredTest extends AbstractIntegrationTest {
@Inject
@Filter(timeout=120000, value="(tranAttribute=Required)")
TestBean bean;
@Test
public void testInsertSuccesful() throws Exception {
clientTransaction = false;
assertInsertSuccesful();
}
@Test
public void testInsertWithAppExceptionCommitted() throws Exception {
assertInsertWithAppExceptionCommitted();
}
@Test
public void testInsertWithRuntimeExceptionRolledBack() throws Exception {
assertInsertWithRuntimeExceptionRolledBack();
}
@Override
protected TestBean getBean() {
return bean;
}
}
| 7,711 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/NeverTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class NeverTest extends AbstractIntegrationTest {
@Inject
@Filter("(tranAttribute=Never)")
TestBean bean;
/**
* Test with client transaction - an exception is thrown because transactions are not allowed
* @throws Exception
*/
@Test
public void testInsertFails() throws Exception {
clientTransaction = true;
assertInsertFails();
}
@Test
public void testDelegateInsertFails() throws Exception {
clientTransaction = false;
assertDelegateInsertFails();
}
@Override
protected TestBean getBean() {
return bean;
}
}
| 7,712 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/AbstractIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.transaction.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.vmOption;
import static org.ops4j.pax.exam.CoreOptions.when;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.transaction.RollbackException;
import javax.transaction.UserTransaction;
import org.apache.aries.transaction.test.Counter;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.extra.CleanCachesOption;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public abstract class AbstractIntegrationTest {
@Inject
BundleContext bundleContext;
@Inject
UserTransaction tran;
@Inject
Counter counter;
protected boolean clientTransaction = true;
public Option baseOptions() {
String localRepo = System.getProperty("maven.repo.local");
if (localRepo == null) {
localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
}
return composite(
junitBundles(),
new CleanCachesOption(true), // change to 'false' if investigation is needed
// this is how you set the default log level when using pax
// logging (logProfile)
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
// this option helps with debugging
//vmOption("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5006"),
when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))
);
}
@Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
frameworkProperty("org.osgi.framework.system.packages")
.value("javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers"),
systemProperty("org.apache.aries.proxy.weaving.enabled").value("none"),
systemProperty("pax.exam.osgi.unresolved.fail").value("true"),
// Bundles
mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(),
mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject(),
mavenBundle("org.apache.felix", "org.apache.felix.coordinator").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-validation_1.0_spec").versionAsInProject(),
mavenBundle("org.apache.geronimo.components", "geronimo-connector").versionAsInProject(),
mavenBundle("org.apache.derby", "derby").versionAsInProject(),
mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.api").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.api").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.impl").versionAsInProject(),
jta12Bundles(),
mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.manager").versionAsInProject(),
mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.blueprint").versionAsInProject(),
mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.jdbc").versionAsInProject(),
mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.testbundle").versionAsInProject(),
mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.testds").versionAsInProject(),
//debug(),
//new TimeoutOption( 0 ),
};
}
protected Option debug() {
return vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005");
}
private Option jta12Bundles() {
return CoreOptions.composite(
mavenBundle("javax.interceptor", "javax.interceptor-api").versionAsInProject(),
mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.javax-inject").versionAsInProject(),
mavenBundle("javax.el", "javax.el-api").versionAsInProject(),
mavenBundle("javax.enterprise", "cdi-api").versionAsInProject(),
mavenBundle("javax.transaction", "javax.transaction-api").versionAsInProject()
);
}
/**
* Helps to diagnose bundles that are not resolved as it will throw a detailed exception
*
* @throws BundleException
*/
public void resolveBundles() throws BundleException {
System.out.println("Checking for bundles");
Bundle[] bundles = bundleContext.getBundles();
for (Bundle bundle : bundles) {
if (bundle.getState() == Bundle.INSTALLED) {
System.out.println("Found non resolved bundle " + bundle.getBundleId() + ":"
+ bundle.getSymbolicName() + ":" + bundle.getVersion());
bundle.start();
}
}
}
// Test with client transaction and runtime exception - the user transaction is rolled back
protected void assertInsertWithRuntimeExceptionRolledBack() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
if (clientTransaction) {
tran.begin();
}
bean.insertRow("testWithClientTranAndWithRuntimeException", 1, null);
try {
bean.insertRow("testWithClientTranAndWithRuntimeException", 2, new RuntimeException("Dummy exception"));
} catch (RuntimeException e) {
Assert.assertEquals("Dummy exception", e.getMessage());
}
if (clientTransaction) {
try {
tran.commit();
fail("RollbackException not thrown");
} catch (RollbackException e) {
// Ignore expected
}
}
int finalRows = counter.countRows();
// In case of client transaction both are rolled back
// In case of container transaction only second insert is rolled back
assertEquals("Added rows", clientTransaction ? 0 : 1, finalRows - initialRows);
}
protected void assertInsertWithAppExceptionCommitted() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
if (clientTransaction) {
tran.begin();
}
bean.insertRow("testWithClientTranAndWithAppException", 1, null);
try {
bean.insertRow("testWithClientTranAndWithAppException", 2, new SQLException("Dummy exception"));
} catch (SQLException e) {
Assert.assertEquals("Dummy exception", e.getMessage());
}
if (clientTransaction) {
tran.commit();
}
int finalRows = counter.countRows();
assertEquals("Added rows", 2, finalRows - initialRows);
}
protected void assertInsertSuccesful() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
if (clientTransaction ) {
tran.begin();
}
bean.insertRow("testWithClientTran", 1, null);
if (clientTransaction ) {
tran.commit();
}
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
protected void assertInsertFails() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
if (clientTransaction ) {
tran.begin();
}
try {
bean.insertRow("testWithClientTran", 1, null);
fail("IllegalStateException not thrown");
} catch (IllegalStateException e) {
// Ignore Expected
}
if (clientTransaction ) {
tran.commit();
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
// Test without client transaction - the insert fails because the bean delegates to another
// bean with a transaction strategy of Mandatory, and no transaction is available
protected void assertDelegateInsertFails() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
if (clientTransaction ) {
tran.begin();
}
try {
bean.delegateInsertRow("testWithoutClientTran", 1);
fail("IllegalStateException not thrown");
} catch (IllegalStateException e) {
// Ignore expected
}
if (clientTransaction ) {
tran.commit();
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
// Test without client transaction - an exception is thrown because a transaction is mandatory
protected void assertMandatoryTransaction() throws SQLException {
try {
getBean().insertRow("testWithoutClientTran", 1, null);
fail("IllegalStateException not thrown");
} catch (IllegalStateException e) {
// Ignore expected
}
}
protected abstract TestBean getBean();
protected void assertDelegateInsert() throws Exception {
TestBean bean = getBean();
int initialRows = counter.countRows();
tran.begin();
bean.delegateInsertRow("testWithClientTran", 1);
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
} | 7,713 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/NotSupportedTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import static junit.framework.Assert.assertEquals;
import java.sql.SQLException;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class NotSupportedTest extends AbstractIntegrationTest {
@Inject
@Filter("(tranAttribute=NotSupported)")
TestBean nsBean;
@Inject
@Filter("(tranAttribute=Required)")
TestBean rBean;
/**
* The client transaction is suspended. So the delegate bean that mandates a transaction
* fails.
* @throws Exception
*/
@Test
public void testNotSupported() throws Exception {
assertDelegateInsertFails();
clientTransaction = false;
assertDelegateInsertFails();
}
@Test
public void testExceptionsDoNotAffectTransaction() throws Exception {
int initialRows = counter.countRows();
tran.begin();
rBean.insertRow("testWithClientTranAndWithRuntimeException", 1, null);
try {
nsBean.throwApplicationException();
} catch (SQLException e) {
// Ignore expected
}
try {
nsBean.throwRuntimeException();
} catch (RuntimeException e) {
// Ignore expected
}
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
@Override
protected TestBean getBean() {
return nsBean;
}
}
| 7,714 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/MandatoryTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class MandatoryTest extends AbstractIntegrationTest {
@Inject
@Filter("(tranAttribute=Mandatory)")
TestBean bean;
@Test
public void testMandatory() throws Exception {
assertInsertSuccesful();
assertInsertWithAppExceptionCommitted();
assertMandatoryTransaction();
}
@Test
public void testInsertWithRuntimeExceptionRolledBack() throws Exception {
assertInsertWithRuntimeExceptionRolledBack();
}
@Override
protected TestBean getBean() {
return bean;
}
}
| 7,715 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/RollbackOnTest.java | package org.apache.aries.transaction.itests;
import org.apache.aries.transaction.test.RollbackOnBean;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
import javax.inject.Inject;
import javax.transaction.Status;
import java.sql.SQLException;
import static junit.framework.Assert.assertEquals;
public class RollbackOnTest extends AbstractIntegrationTest {
@Inject
@Filter(timeout = 120000, value = "(tranAttribute=Required)")
TestBean rBean;
@Inject
RollbackOnBean rollbackOnBean;
@Before
public void setUp() throws Exception {
rollbackOnBean.setrBean(rBean);
}
//default behavior, doesn't rollback on application exception
@Test
public void testNoRollbackOnDefaultAppException() throws Exception {
tran.begin();
try {
rBean.insertRow("test", 1, new SQLException());
} catch (SQLException e) {
// Ignore expected
}
int txStatus = tran.getStatus();
tran.rollback();
Assert.assertEquals("tx was rolled back", Status.STATUS_ACTIVE, txStatus);
}
//default behavior, doesn't rollback on exception
@Test
public void testNoRollbackOnDefaultException() throws Exception {
tran.begin();
try {
rollbackOnBean.throwException("test", 2);
} catch (Exception e) {
// Ignore expected
}
int txStatus = tran.getStatus();
tran.rollback();
Assert.assertEquals("tx was rolled back", Status.STATUS_ACTIVE, txStatus);
}
@Test
public void testExceptionRollbackOnException() throws Exception {
tran.begin();
try {
rollbackOnBean.throwExceptionRollbackOnException("noAnnotationDefaultException", -1);
} catch (Exception e) {
// Ignore expected
}
int txStatus = tran.getStatus();
tran.rollback();
Assert.assertEquals("tx was not rolled back", Status.STATUS_MARKED_ROLLBACK, txStatus);
}
@Test
public void testNoRollbackOnDefaultRuntimeException() throws Exception {
tran.begin();
try {
rBean.insertRow("test", 1, new RuntimeException());
} catch (Exception e) {
// Ignore expected
}
int txStatus = tran.getStatus();
tran.rollback();
Assert.assertEquals("tx was not rolled back", Status.STATUS_MARKED_ROLLBACK, txStatus);
}
//throw Runtime / handle Exception
@Test
public void testDontRollbackOnRuntimeException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwRuntimeExceptionDontRollbackOnException("testDontRollbackOnRuntimeException", 3);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
@Test
public void testRollbackOnRuntimeException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwRuntimeExceptionRollbackOnException("testRollbackOnRuntimeException", 4);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
//throw runtime / handle AppException
@Test
public void testThrowRuntimeDontRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwRuntimeExceptionDontRollbackOnAppException("testThrowRuntimeDontRollbackOnAppException", 5);
tran.commit();
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
@Test
public void testThrowRuntimeRollbackOnException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwRuntimeExceptionRollbackOnAppException("testThrowRuntimeRollbackOnException", 6);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
//throw AppException / handle Exception
@Test
public void testThrowAppExceptionRollbackOnException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwApplicationExceptionRollbackOnException("testThrowAppExceptionRollbackOnException", 7);
} catch (SQLException e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
@Test
public void testThrowAppExceptionDontRollbackOnException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwApplicationExceptionDontRollbackOnException("testThrowAppExceptionDontRollbackOnException", 8);
} catch (SQLException e) {
//ignore
}
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
//throw AppException / handle AppException
@Test
public void testThrowAppExceptionDontRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwApplicationExceptionDontRollbackOnAppException("testThrowAppExceptionDontRollbackOnAppException", 9);
} catch (SQLException e) {
//ignore
}
tran.commit();
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
@Test
public void testThrowAppExceptionRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean.throwApplicationExceptionRollbackOnAppException("testThrowAppExceptionRollbackOnAppException", 10);
} catch (SQLException e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
//throw Exception, handle Exception + DontRollBackOn
@Test
public void testThrowRuntimeExceptionRollbackExceptionDontRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean
.throwExceptionRollbackOnExceptionDontRollbackOnAppException("testThrowRuntimeExceptionRollbackExceptionDontRollbackOnAppException", 11);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
@Test
public void testThrowRuntimeExceptionDontRollbackExceptionRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean
.throwExceptionRollbackOnAppExceptionDontRollbackOnException("testThrowRuntimeExceptionDontRollbackExceptionRollbackOnAppException", 12);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
//expected
}
int finalRows = counter.countRows();
assertEquals("Added rows", 0, finalRows - initialRows);
}
@Test
public void testThrowAppExceptionDontRollbackExceptionRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean
.throwAppExceptionRollbackOnAppExceptionDontRollbackOnException("testThrowAppExceptionDontRollbackExceptionRollbackOnAppException", 13);
} catch (SQLException e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
//expected
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
}
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
@Test
public void testThrowAppExceptionRollbackExceptionDontRollbackOnAppException() throws Exception {
int initialRows = counter.countRows();
tran.begin();
try {
rollbackOnBean
.throwAppExceptionRollbackOnExceptionDontRollbackOnAppException("testThrowAppExceptionRollbackExceptionDontRollbackOnAppException", 14);
} catch (Exception e) {
//ignore
}
try {
tran.commit();
} catch (Exception e) {
//expected
if (Status.STATUS_ACTIVE == tran.getStatus()) {
tran.rollback();
}
}
int finalRows = counter.countRows();
assertEquals("Added rows", 1, finalRows - initialRows);
}
@Override
protected TestBean getBean() {
return rBean;
}
}
| 7,716 |
0 | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-itests/src/test/java/org/apache/aries/transaction/itests/SupportsTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.itests;
import javax.inject.Inject;
import org.apache.aries.transaction.test.TestBean;
import org.junit.Test;
import org.ops4j.pax.exam.util.Filter;
public class SupportsTest extends AbstractIntegrationTest {
@Inject
@Filter("(tranAttribute=Supports)")
TestBean bean;
/**
* Test with client transaction - the insert succeeds because the bean delegates to
* another bean with a transaction strategy of Mandatory, and the user transaction
* is delegated
* @throws Exception
*/
@Test
public void testDelegatedInsertWithClientTransaction() throws Exception {
assertDelegateInsert();
}
/**
* Test with client transaction and application exception - the user transaction is not rolled back
* @throws Exception
*/
@Test
public void testInsertWithAppExceptionCommitted() throws Exception {
assertInsertWithAppExceptionCommitted();
}
/**
* Test with client transaction and runtime exception - the user transaction is rolled back
* @throws Exception
*/
@Test
public void testInsertWithRuntimeExceptionRolledBack() throws Exception {
assertInsertWithRuntimeExceptionRolledBack();
}
/**
* Test without client transaction - the insert fails because the bean delegates to
* another bean with a transaction strategy of Mandatory, and no transaction is available
* @throws Exception
*/
@Test
public void testDelegatedWithoutClientTransactionFails() throws Exception {
clientTransaction = false;
assertDelegateInsertFails();
}
@Override
protected TestBean getBean() {
return bean;
}
}
| 7,717 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/PooledConnectionFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.XAConnection;
import javax.jms.XAConnectionFactory;
import org.apache.aries.transaction.jms.internal.ConnectionKey;
import org.apache.aries.transaction.jms.internal.ConnectionPool;
import org.apache.aries.transaction.jms.internal.PooledConnection;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A JMS provider which pools Connection, Session and MessageProducer instances
* so it can be used with tools like <a href="http://camel.apache.org/activemq.html">Camel</a> and Spring's
* <a href="http://activemq.apache.org/spring-support.html">JmsTemplate and MessagListenerContainer</a>.
* Connections, sessions and producers are returned to a pool after use so that they can be reused later
* without having to undergo the cost of creating them again.
*
* b>NOTE:</b> while this implementation does allow the creation of a collection of active consumers,
* it does not 'pool' consumers. Pooling makes sense for connections, sessions and producers, which
* are expensive to create and can remain idle a minimal cost. Consumers, on the other hand, are usually
* just created at startup and left active, handling incoming messages as they come. When a consumer is
* complete, it is best to close it rather than return it to a pool for later reuse: this is because,
* even if a consumer is idle, ActiveMQ will keep delivering messages to the consumer's prefetch buffer,
* where they'll get held until the consumer is active again.
*
* If you are creating a collection of consumers (for example, for multi-threaded message consumption), you
* might want to consider using a lower prefetch value for each consumer (e.g. 10 or 20), to ensure that
* all messages don't end up going to just one of the consumers. See this FAQ entry for more detail:
* http://activemq.apache.org/i-do-not-receive-messages-in-my-second-consumer.html
*
* Optionally, one may configure the pool to examine and possibly evict objects as they sit idle in the
* pool. This is performed by an "idle object eviction" thread, which runs asynchronously. Caution should
* be used when configuring this optional feature. Eviction runs contend with client threads for access
* to objects in the pool, so if they run too frequently performance issues may result. The idle object
* eviction thread may be configured using the {@link PooledConnectionFactory#setTimeBetweenExpirationCheckMillis} method. By
* default the value is -1 which means no eviction thread will be run. Set to a non-negative value to
* configure the idle eviction thread to run.
*
* @org.apache.xbean.XBean element="pooledConnectionFactory"
*/
public class PooledConnectionFactory implements ConnectionFactory {
private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnectionFactory.class);
protected final AtomicBoolean stopped = new AtomicBoolean(false);
private GenericKeyedObjectPool<ConnectionKey, ConnectionPool> connectionsPool;
private ConnectionFactory connectionFactory;
private int maximumActiveSessionPerConnection = 500;
private int idleTimeout = 30 * 1000;
private boolean blockIfSessionPoolIsFull = true;
private long blockIfSessionPoolIsFullTimeout = -1L;
private long expiryTimeout = 0l;
private boolean createConnectionOnStartup = true;
private boolean useAnonymousProducers = true;
public void initConnectionsPool() {
if (this.connectionsPool == null) {
this.connectionsPool = new GenericKeyedObjectPool<ConnectionKey, ConnectionPool>(
new KeyedPoolableObjectFactory<ConnectionKey, ConnectionPool>() {
@Override
public void activateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
}
@Override
public void destroyObject(ConnectionKey key, ConnectionPool connection) throws Exception {
try {
if (LOG.isTraceEnabled()) {
LOG.trace("Destroying connection: {}", connection);
}
connection.close();
} catch (Exception e) {
LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e);
}
}
@Override
public ConnectionPool makeObject(ConnectionKey key) throws Exception {
Connection delegate = createConnection(key);
ConnectionPool connection = createConnectionPool(delegate);
connection.setIdleTimeout(getIdleTimeout());
connection.setExpiryTimeout(getExpiryTimeout());
connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection());
connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) {
connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout());
}
connection.setUseAnonymousProducers(isUseAnonymousProducers());
if (LOG.isTraceEnabled()) {
LOG.trace("Created new connection: {}", connection);
}
return connection;
}
@Override
public void passivateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
}
@Override
public boolean validateObject(ConnectionKey key, ConnectionPool connection) {
if (connection != null && connection.expiredCheck()) {
if (LOG.isTraceEnabled()) {
LOG.trace("Connection has expired: {} and will be destroyed", connection);
}
return false;
}
return true;
}
});
// Set max idle (not max active) since our connections always idle in the pool.
this.connectionsPool.setMaxIdle(1);
// We always want our validate method to control when idle objects are evicted.
this.connectionsPool.setTestOnBorrow(true);
this.connectionsPool.setTestWhileIdle(true);
}
}
/**
* @return the currently configured ConnectionFactory used to create the pooled Connections.
*/
public ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
/**
* Sets the ConnectionFactory used to create new pooled Connections.
* <p/>
* Updates to this value do not affect Connections that were previously created and placed
* into the pool. In order to allocate new Connections based off this new ConnectionFactory
* it is first necessary to {@link #clear()} the pooled Connections.
*
* @param toUse
* The factory to use to create pooled Connections.
*/
public void setConnectionFactory(final ConnectionFactory toUse) {
if (toUse instanceof XAConnectionFactory) {
this.connectionFactory = new XAConnectionFactoryWrapper((XAConnectionFactory) toUse);
} else {
this.connectionFactory = toUse;
}
}
@Override
public Connection createConnection() throws JMSException {
return createConnection(null, null);
}
@Override
public synchronized Connection createConnection(String userName, String password) throws JMSException {
if (stopped.get()) {
LOG.debug("PooledConnectionFactory is stopped, skip create new connection.");
return null;
}
ConnectionPool connection = null;
ConnectionKey key = new ConnectionKey(userName, password);
// This will either return an existing non-expired ConnectionPool or it
// will create a new one to meet the demand.
if (getConnectionsPool().getNumIdle(key) < getMaxConnections()) {
try {
// we want borrowObject to return the one we added.
connectionsPool.setLifo(true);
connectionsPool.addObject(key);
} catch (Exception e) {
throw createJmsException("Error while attempting to add new Connection to the pool", e);
}
} else {
// now we want the oldest one in the pool.
connectionsPool.setLifo(false);
}
try {
// We can race against other threads returning the connection when there is an
// expiration or idle timeout. We keep pulling out ConnectionPool instances until
// we win and get a non-closed instance and then increment the reference count
// under lock to prevent another thread from triggering an expiration check and
// pulling the rug out from under us.
while (connection == null) {
connection = connectionsPool.borrowObject(key);
synchronized (connection) {
if (connection.getConnection() != null) {
connection.incrementReferenceCount();
break;
}
// Return the bad one to the pool and let if get destroyed as normal.
connectionsPool.returnObject(key, connection);
connection = null;
}
}
} catch (Exception e) {
throw createJmsException("Error while attempting to retrieve a connection from the pool", e);
}
try {
connectionsPool.returnObject(key, connection);
} catch (Exception e) {
throw createJmsException("Error when returning connection to the pool", e);
}
return newPooledConnection(connection);
}
protected Connection newPooledConnection(ConnectionPool connection) {
return new PooledConnection(connection);
}
private JMSException createJmsException(String msg, Exception cause) {
JMSException exception = new JMSException(msg);
exception.setLinkedException(cause);
exception.initCause(cause);
return exception;
}
protected Connection createConnection(ConnectionKey key) throws JMSException {
if (key.getUserName() == null && key.getPassword() == null) {
return connectionFactory.createConnection();
} else {
return connectionFactory.createConnection(key.getUserName(), key.getPassword());
}
}
public void start() {
LOG.debug("Staring the PooledConnectionFactory: create on start = {}", isCreateConnectionOnStartup());
stopped.set(false);
if (isCreateConnectionOnStartup()) {
try {
// warm the pool by creating a connection during startup
createConnection();
} catch (JMSException e) {
LOG.warn("Create pooled connection during start failed. This exception will be ignored.", e);
}
}
}
public void stop() {
if (stopped.compareAndSet(false, true)) {
LOG.debug("Stopping the PooledConnectionFactory, number of connections in cache: {}",
connectionsPool != null ? connectionsPool.getNumActive() : 0);
try {
if (connectionsPool != null) {
connectionsPool.close();
}
} catch (Exception e) {
}
}
}
/**
* Clears all connections from the pool. Each connection that is currently in the pool is
* closed and removed from the pool. A new connection will be created on the next call to
* {@link #createConnection()}. Care should be taken when using this method as Connections that
* are in use be client's will be closed.
*/
public void clear() {
if (stopped.get()) {
return;
}
getConnectionsPool().clear();
}
/**
* Returns the currently configured maximum number of sessions a pooled Connection will
* create before it either blocks or throws an exception when a new session is requested,
* depending on configuration.
*
* @return the number of session instances that can be taken from a pooled connection.
*/
public int getMaximumActiveSessionPerConnection() {
return maximumActiveSessionPerConnection;
}
/**
* Sets the maximum number of active sessions per connection
*
* @param maximumActiveSessionPerConnection
* The maximum number of active session per connection in the pool.
*/
public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection;
}
/**
* Controls the behavior of the internal session pool. By default the call to
* Connection.getSession() will block if the session pool is full. If the
* argument false is given, it will change the default behavior and instead the
* call to getSession() will throw a JMSException.
*
* The size of the session pool is controlled by the @see #maximumActive
* property.
*
* @param block - if true, the call to getSession() blocks if the pool is full
* until a session object is available. defaults to true.
*/
public void setBlockIfSessionPoolIsFull(boolean block) {
this.blockIfSessionPoolIsFull = block;
}
/**
* Returns whether a pooled Connection will enter a blocked state or will throw an Exception
* once the maximum number of sessions has been borrowed from the the Session Pool.
*
* @return true if the pooled Connection createSession method will block when the limit is hit.
* @see #setBlockIfSessionPoolIsFull(boolean)
*/
public boolean isBlockIfSessionPoolIsFull() {
return this.blockIfSessionPoolIsFull;
}
/**
* Returns the maximum number to pooled Connections that this factory will allow before it
* begins to return connections from the pool on calls to ({@link #createConnection()}.
*
* @return the maxConnections that will be created for this pool.
*/
public int getMaxConnections() {
return getConnectionsPool().getMaxIdle();
}
/**
* Sets the maximum number of pooled Connections (defaults to one). Each call to
* {@link #createConnection()} will result in a new Connection being create up to the max
* connections value.
*
* @param maxConnections the maxConnections to set
*/
public void setMaxConnections(int maxConnections) {
getConnectionsPool().setMaxIdle(maxConnections);
}
/**
* Gets the Idle timeout value applied to new Connection's that are created by this pool.
* <p/>
* The idle timeout is used determine if a Connection instance has sat to long in the pool unused
* and if so is closed and removed from the pool. The default value is 30 seconds.
*
* @return idle timeout value (milliseconds)
*/
public int getIdleTimeout() {
return idleTimeout;
}
/**
* Sets the idle timeout value for Connection's that are created by this pool in Milliseconds,
* defaults to 30 seconds.
* <p/>
* For a Connection that is in the pool but has no current users the idle timeout determines how
* long the Connection can live before it is eligible for removal from the pool. Normally the
* connections are tested when an attempt to check one out occurs so a Connection instance can sit
* in the pool much longer than its idle timeout if connections are used infrequently.
*
* @param idleTimeout
* The maximum time a pooled Connection can sit unused before it is eligible for removal.
*/
public void setIdleTimeout(int idleTimeout) {
this.idleTimeout = idleTimeout;
}
/**
* allow connections to expire, irrespective of load or idle time. This is useful with failover
* to force a reconnect from the pool, to reestablish load balancing or use of the master post recovery
*
* @param expiryTimeout non zero in milliseconds
*/
public void setExpiryTimeout(long expiryTimeout) {
this.expiryTimeout = expiryTimeout;
}
/**
* @return the configured expiration timeout for connections in the pool.
*/
public long getExpiryTimeout() {
return expiryTimeout;
}
/**
* @return true if a Connection is created immediately on a call to {@link #start()}.
*/
public boolean isCreateConnectionOnStartup() {
return createConnectionOnStartup;
}
/**
* Whether to create a connection on starting this {@link PooledConnectionFactory}.
* <p/>
* This can be used to warm-up the pool on startup. Notice that any kind of exception
* happens during startup is logged at WARN level and ignored.
*
* @param createConnectionOnStartup <tt>true</tt> to create a connection on startup
*/
public void setCreateConnectionOnStartup(boolean createConnectionOnStartup) {
this.createConnectionOnStartup = createConnectionOnStartup;
}
/**
* Should Sessions use one anonymous producer for all producer requests or should a new
* MessageProducer be created for each request to create a producer object, default is true.
*
* When enabled the session only needs to allocate one MessageProducer for all requests and
* the MessageProducer#send(destination, message) method can be used. Normally this is the
* right thing to do however it does result in the Broker not showing the producers per
* destination.
*
* @return true if a PooledSession will use only a single anonymous message producer instance.
*/
public boolean isUseAnonymousProducers() {
return this.useAnonymousProducers;
}
/**
* Sets whether a PooledSession uses only one anonymous MessageProducer instance or creates
* a new MessageProducer for each call the create a MessageProducer.
*
* @param value
* Boolean value that configures whether anonymous producers are used.
*/
public void setUseAnonymousProducers(boolean value) {
this.useAnonymousProducers = value;
}
/**
* Gets the Pool of ConnectionPool instances which are keyed by different ConnectionKeys.
*
* @return this factories pool of ConnectionPool instances.
*/
protected GenericKeyedObjectPool<ConnectionKey, ConnectionPool> getConnectionsPool() {
initConnectionsPool();
return this.connectionsPool;
}
/**
* Sets the number of milliseconds to sleep between runs of the idle Connection eviction thread.
* When non-positive, no idle object eviction thread will be run, and Connections will only be
* checked on borrow to determine if they have sat idle for too long or have failed for some
* other reason.
* <p/>
* By default this value is set to -1 and no expiration thread ever runs.
*
* @param timeBetweenExpirationCheckMillis
* The time to wait between runs of the idle Connection eviction thread.
*/
public void setTimeBetweenExpirationCheckMillis(long timeBetweenExpirationCheckMillis) {
getConnectionsPool().setTimeBetweenEvictionRunsMillis(timeBetweenExpirationCheckMillis);
}
/**
* @return the number of milliseconds to sleep between runs of the idle connection eviction thread.
*/
public long getTimeBetweenExpirationCheckMillis() {
return getConnectionsPool().getTimeBetweenEvictionRunsMillis();
}
/**
* @return the number of Connections currently in the Pool
*/
public int getNumConnections() {
return getConnectionsPool().getNumIdle();
}
/**
* Delegate that creates each instance of an ConnectionPool object. Subclasses can override
* this method to customize the type of connection pool returned.
*
* @param connection
*
* @return instance of a new ConnectionPool.
*/
protected ConnectionPool createConnectionPool(Connection connection) {
return new ConnectionPool(connection);
}
/**
* Returns the timeout to use for blocking creating new sessions
*
* @return true if the pooled Connection createSession method will block when the limit is hit.
* @see #setBlockIfSessionPoolIsFull(boolean)
*/
public long getBlockIfSessionPoolIsFullTimeout() {
return blockIfSessionPoolIsFullTimeout;
}
/**
* Controls the behavior of the internal session pool. By default the call to
* Connection.getSession() will block if the session pool is full. This setting
* will affect how long it blocks and throws an exception after the timeout.
*
* The size of the session pool is controlled by the @see #maximumActive
* property.
*
* Whether or not the call to create session blocks is controlled by the @see #blockIfSessionPoolIsFull
* property
*
* @param blockIfSessionPoolIsFullTimeout - if blockIfSessionPoolIsFullTimeout is true,
* then use this setting to configure how long to block before retry
*/
public void setBlockIfSessionPoolIsFullTimeout(long blockIfSessionPoolIsFullTimeout) {
this.blockIfSessionPoolIsFullTimeout = blockIfSessionPoolIsFullTimeout;
}
static class XAConnectionFactoryWrapper implements XAConnectionFactory, ConnectionFactory {
private final XAConnectionFactory delegate;
XAConnectionFactoryWrapper(XAConnectionFactory delegate) {
this.delegate = delegate;
}
@Override
public Connection createConnection() throws JMSException {
return createXAConnection();
}
@Override
public Connection createConnection(String userName, String password) throws JMSException {
return createXAConnection(userName, password);
}
@Override
public XAConnection createXAConnection() throws JMSException {
return delegate.createXAConnection();
}
@Override
public XAConnection createXAConnection(String userName, String password) throws JMSException {
return delegate.createXAConnection(userName, password);
}
}
}
| 7,718 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/RecoverablePooledConnectionFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms;
import javax.jms.Connection;
import org.apache.aries.transaction.jms.internal.ConnectionPool;
import org.apache.aries.transaction.jms.internal.GenericResourceManager;
import org.apache.aries.transaction.jms.internal.RecoverableConnectionPool;
import org.apache.aries.transaction.jms.internal.XaPooledConnectionFactory;
/**
* A pooled connection factory which is dedicated to work with the Geronimo/Aries
* transaction manager for proper recovery of in-flight transactions after a
* crash.
*
* @org.apache.xbean.XBean element="xaPooledConnectionFactory"
*/
@SuppressWarnings("serial")
public class RecoverablePooledConnectionFactory extends XaPooledConnectionFactory {
private String name;
public RecoverablePooledConnectionFactory() {
super();
}
public String getName() {
return name;
}
/**
* The unique name for this managed XAResource. This name will be used
* by the transaction manager to recover transactions.
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
protected ConnectionPool createConnectionPool(Connection connection) {
return new RecoverableConnectionPool(connection, getTransactionManager(), getName());
}
/**
* @org.apache.xbean.InitMethod
*/
@Override
public void start() {
if (getConnectionFactory() == null) {
throw new IllegalArgumentException("connectionFactory must be set");
}
if (getTransactionManager() == null) {
throw new IllegalArgumentException("transactionManager must be set");
}
super.start();
new GenericResourceManager(name, getTransactionManager(), getConnectionFactory()).recoverResource();
}
}
| 7,719 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/ConnectionKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
/**
* A cache key for the connection details
*
*
*/
public class ConnectionKey {
private String userName;
private String password;
private int hash;
public ConnectionKey(String userName, String password) {
this.password = password;
this.userName = userName;
hash = 31;
if (userName != null) {
hash += userName.hashCode();
}
hash *= 31;
if (password != null) {
hash += password.hashCode();
}
}
public int hashCode() {
return hash;
}
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that instanceof ConnectionKey) {
return equals((ConnectionKey)that);
}
return false;
}
public boolean equals(ConnectionKey that) {
return isEqual(this.userName, that.userName) && isEqual(this.password, that.password);
}
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public static boolean isEqual(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
return o1 != null && o2 != null && o1.equals(o2);
}
}
| 7,720 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledProducer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.Destination;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
/**
* A pooled {@link MessageProducer}
*/
public class PooledProducer implements MessageProducer {
private final MessageProducer messageProducer;
private final Destination destination;
private int deliveryMode;
private boolean disableMessageID;
private boolean disableMessageTimestamp;
private int priority;
private long timeToLive;
private boolean anonymous = true;
public PooledProducer(MessageProducer messageProducer, Destination destination) throws JMSException {
this.messageProducer = messageProducer;
this.destination = destination;
this.anonymous = messageProducer.getDestination() == null;
this.deliveryMode = messageProducer.getDeliveryMode();
this.disableMessageID = messageProducer.getDisableMessageID();
this.disableMessageTimestamp = messageProducer.getDisableMessageTimestamp();
this.priority = messageProducer.getPriority();
this.timeToLive = messageProducer.getTimeToLive();
}
@Override
public void close() throws JMSException {
if (!anonymous) {
this.messageProducer.close();
}
}
@Override
public void send(Destination destination, Message message) throws JMSException {
send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
}
@Override
public void send(Message message) throws JMSException {
send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
}
@Override
public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
send(destination, message, deliveryMode, priority, timeToLive);
}
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
if (destination == null) {
if (messageProducer.getDestination() == null) {
throw new UnsupportedOperationException("A destination must be specified.");
}
throw new InvalidDestinationException("Don't understand null destinations");
}
MessageProducer messageProducer = getMessageProducer();
// just in case let only one thread send at once
synchronized (messageProducer) {
if (anonymous && this.destination != null && !this.destination.equals(destination)) {
throw new UnsupportedOperationException("This producer can only send messages to: " + this.destination);
}
// Producer will do it's own Destination validation so always use the destination
// based send method otherwise we might violate a JMS rule.
messageProducer.send(destination, message, deliveryMode, priority, timeToLive);
}
}
@Override
public Destination getDestination() {
return destination;
}
@Override
public int getDeliveryMode() {
return deliveryMode;
}
@Override
public void setDeliveryMode(int deliveryMode) {
this.deliveryMode = deliveryMode;
}
@Override
public boolean getDisableMessageID() {
return disableMessageID;
}
@Override
public void setDisableMessageID(boolean disableMessageID) {
this.disableMessageID = disableMessageID;
}
@Override
public boolean getDisableMessageTimestamp() {
return disableMessageTimestamp;
}
@Override
public void setDisableMessageTimestamp(boolean disableMessageTimestamp) {
this.disableMessageTimestamp = disableMessageTimestamp;
}
@Override
public int getPriority() {
return priority;
}
@Override
public void setPriority(int priority) {
this.priority = priority;
}
@Override
public long getTimeToLive() {
return timeToLive;
}
@Override
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
// Implementation methods
// -------------------------------------------------------------------------
protected MessageProducer getMessageProducer() {
return messageProducer;
}
protected boolean isAnonymous() {
return anonymous;
}
@Override
public String toString() {
return "PooledProducer { " + messageProducer + " }";
}
}
| 7,721 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledQueueSender.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueSender;
/**
*
*/
public class PooledQueueSender extends PooledProducer implements QueueSender {
public PooledQueueSender(QueueSender messageProducer, Destination destination) throws JMSException {
super(messageProducer, destination);
}
public void send(Queue queue, Message message, int i, int i1, long l) throws JMSException {
getQueueSender().send(queue, message, i, i1, l);
}
public void send(Queue queue, Message message) throws JMSException {
getQueueSender().send(queue, message);
}
public Queue getQueue() throws JMSException {
return getQueueSender().getQueue();
}
protected QueueSender getQueueSender() {
return (QueueSender) getMessageProducer();
}
}
| 7,722 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/ConnectionPool.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.Connection;
import javax.jms.IllegalStateException;
import javax.jms.JMSException;
import javax.jms.Session;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* Holds a real JMS connection along with the session pools associated with it.
* <p/>
* Instances of this class are shared amongst one or more PooledConnection object and must
* track the session objects that are loaned out for cleanup on close as well as ensuring
* that the temporary destinations of the managed Connection are purged when all references
* to this ConnectionPool are released.
*/
public class ConnectionPool {
protected Connection connection;
private int referenceCount;
private long lastUsed = System.currentTimeMillis();
private final long firstUsed = lastUsed;
private boolean hasExpired;
private int idleTimeout = 30 * 1000;
private long expiryTimeout = 0l;
private boolean useAnonymousProducers = true;
private final AtomicBoolean started = new AtomicBoolean(false);
private final GenericKeyedObjectPool<SessionKey, PooledSession> sessionPool;
private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
public ConnectionPool(Connection connection) {
this.connection = wrap(connection);
// Create our internal Pool of session instances.
this.sessionPool = new GenericKeyedObjectPool<SessionKey, PooledSession>(
new KeyedPoolableObjectFactory<SessionKey, PooledSession>() {
@Override
public void activateObject(SessionKey key, PooledSession session) throws Exception {
ConnectionPool.this.loanedSessions.add(session);
}
@Override
public void destroyObject(SessionKey key, PooledSession session) throws Exception {
ConnectionPool.this.loanedSessions.remove(session);
session.getInternalSession().close();
}
@Override
public PooledSession makeObject(SessionKey key) throws Exception {
Session session = makeSession(key);
return new PooledSession(key, session, sessionPool, key.isTransacted(), useAnonymousProducers);
}
@Override
public void passivateObject(SessionKey key, PooledSession session) throws Exception {
ConnectionPool.this.loanedSessions.remove(session);
}
@Override
public boolean validateObject(SessionKey key, PooledSession session) {
return true;
}
}
);
}
// useful when external failure needs to force expiry
public void setHasExpired(boolean val) {
hasExpired = val;
}
protected Session makeSession(SessionKey key) throws JMSException {
return connection.createSession(key.isTransacted(), key.getAckMode());
}
protected Connection wrap(Connection connection) {
return connection;
}
protected void unWrap(Connection connection) {
}
public void start() throws JMSException {
if (started.compareAndSet(false, true)) {
try {
connection.start();
} catch (JMSException e) {
started.set(false);
throw(e);
}
}
}
public synchronized Connection getConnection() {
return connection;
}
public Session createSession(boolean transacted, int ackMode) throws JMSException {
SessionKey key = new SessionKey(transacted, ackMode);
PooledSession session;
try {
session = sessionPool.borrowObject(key);
} catch (Exception e) {
javax.jms.IllegalStateException illegalStateException = new IllegalStateException(e.toString());
illegalStateException.initCause(e);
throw illegalStateException;
}
return session;
}
public synchronized void close() {
if (connection != null) {
try {
sessionPool.close();
} catch (Exception e) {
} finally {
try {
connection.close();
} catch (Exception e) {
} finally {
connection = null;
}
}
}
}
public synchronized void incrementReferenceCount() {
referenceCount++;
lastUsed = System.currentTimeMillis();
}
public synchronized void decrementReferenceCount() {
referenceCount--;
lastUsed = System.currentTimeMillis();
if (referenceCount == 0) {
// Loaned sessions are those that are active in the sessionPool and
// have not been closed by the client before closing the connection.
// These need to be closed so that all session's reflect the fact
// that the parent Connection is closed.
for (PooledSession session : this.loanedSessions) {
try {
session.close();
} catch (Exception e) {
}
}
this.loanedSessions.clear();
unWrap(getConnection());
expiredCheck();
}
}
/**
* Determines if this Connection has expired.
* <p/>
* A ConnectionPool is considered expired when all references to it are released AND either
* the configured idleTimeout has elapsed OR the configured expiryTimeout has elapsed.
* Once a ConnectionPool is determined to have expired its underlying Connection is closed.
*
* @return true if this connection has expired.
*/
public synchronized boolean expiredCheck() {
boolean expired = false;
if (connection == null) {
return true;
}
if (hasExpired) {
if (referenceCount == 0) {
close();
expired = true;
}
}
if (expiryTimeout > 0 && System.currentTimeMillis() > firstUsed + expiryTimeout) {
hasExpired = true;
if (referenceCount == 0) {
close();
expired = true;
}
}
// Only set hasExpired here is no references, as a Connection with references is by
// definition not idle at this time.
if (referenceCount == 0 && idleTimeout > 0 && System.currentTimeMillis() > lastUsed + idleTimeout) {
hasExpired = true;
close();
expired = true;
}
return expired;
}
public int getIdleTimeout() {
return idleTimeout;
}
public void setIdleTimeout(int idleTimeout) {
this.idleTimeout = idleTimeout;
}
public void setExpiryTimeout(long expiryTimeout) {
this.expiryTimeout = expiryTimeout;
}
public long getExpiryTimeout() {
return expiryTimeout;
}
public int getMaximumActiveSessionPerConnection() {
return this.sessionPool.getMaxActive();
}
public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
this.sessionPool.setMaxActive(maximumActiveSessionPerConnection);
}
public boolean isUseAnonymousProducers() {
return this.useAnonymousProducers;
}
public void setUseAnonymousProducers(boolean value) {
this.useAnonymousProducers = value;
}
/**
* @return the total number of Pooled session including idle sessions that are not
* currently loaned out to any client.
*/
public int getNumSessions() {
return this.sessionPool.getNumIdle() + this.sessionPool.getNumActive();
}
/**
* @return the total number of Sessions that are in the Session pool but not loaned out.
*/
public int getNumIdleSessions() {
return this.sessionPool.getNumIdle();
}
/**
* @return the total number of Session's that have been loaned to PooledConnection instances.
*/
public int getNumActiveSessions() {
return this.sessionPool.getNumActive();
}
/**
* Configure whether the createSession method should block when there are no more idle sessions and the
* pool already contains the maximum number of active sessions. If false the create method will fail
* and throw an exception.
*
* @param block
* Indicates whether blocking should be used to wait for more space to create a session.
*/
public void setBlockIfSessionPoolIsFull(boolean block) {
this.sessionPool.setWhenExhaustedAction(
(block ? GenericObjectPool.WHEN_EXHAUSTED_BLOCK : GenericObjectPool.WHEN_EXHAUSTED_FAIL));
}
public boolean isBlockIfSessionPoolIsFull() {
return this.sessionPool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
}
/**
* Returns the timeout to use for blocking creating new sessions
*
* @return true if the pooled Connection createSession method will block when the limit is hit.
* @see #setBlockIfSessionPoolIsFull(boolean)
*/
public long getBlockIfSessionPoolIsFullTimeout() {
return this.sessionPool.getMaxWait();
}
/**
* Controls the behavior of the internal session pool. By default the call to
* Connection.getSession() will block if the session pool is full. This setting
* will affect how long it blocks and throws an exception after the timeout.
*
* The size of the session pool is controlled by the @see #maximumActive
* property.
*
* Whether or not the call to create session blocks is controlled by the @see #blockIfSessionPoolIsFull
* property
*
* @param blockIfSessionPoolIsFullTimeout - if blockIfSessionPoolIsFullTimeout is true,
* then use this setting to configure how long to block before retry
*/
public void setBlockIfSessionPoolIsFullTimeout(long blockIfSessionPoolIsFullTimeout) {
this.sessionPool.setMaxWait(blockIfSessionPoolIsFullTimeout);
}
@Override
public String toString() {
return "ConnectionPool[" + connection + "]";
}
}
| 7,723 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/XaPooledConnectionFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.io.Serializable;
import java.util.Hashtable;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingEnumeration;
import javax.naming.spi.ObjectFactory;
import javax.transaction.TransactionManager;
import org.apache.aries.transaction.jms.PooledConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A pooled connection factory that automatically enlists
* sessions in the current active XA transaction if any.
*/
public class XaPooledConnectionFactory extends PooledConnectionFactory implements ObjectFactory,
Serializable, QueueConnectionFactory, TopicConnectionFactory {
private static final long serialVersionUID = -6538152448204064932L;
private static final transient Logger LOG = LoggerFactory.getLogger(XaPooledConnectionFactory.class);
private TransactionManager transactionManager;
private boolean tmFromJndi = false;
private String tmJndiName = "java:/TransactionManager";
public TransactionManager getTransactionManager() {
if (transactionManager == null && tmFromJndi) {
try {
transactionManager = (TransactionManager) new InitialContext().lookup(getTmJndiName());
} catch (Throwable ignored) {
if (LOG.isTraceEnabled()) {
LOG.trace("exception on tmFromJndi: " + getTmJndiName(), ignored);
}
}
}
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
protected ConnectionPool createConnectionPool(Connection connection) {
return new XaConnectionPool(connection, getTransactionManager());
}
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
setTmFromJndi(true);
configFromJndiConf(obj);
if (environment != null) {
IntrospectionSupport.setProperties(this, environment);
}
return this;
}
private void configFromJndiConf(Object rootContextName) {
if (rootContextName instanceof String) {
String name = (String) rootContextName;
name = name.substring(0, name.lastIndexOf('/')) + "/conf" + name.substring(name.lastIndexOf('/'));
try {
InitialContext ctx = new InitialContext();
NamingEnumeration<Binding> bindings = ctx.listBindings(name);
while (bindings.hasMore()) {
Binding bd = bindings.next();
IntrospectionSupport.setProperty(this, bd.getName(), bd.getObject());
}
} catch (Exception ignored) {
if (LOG.isTraceEnabled()) {
LOG.trace("exception on config from jndi: " + name, ignored);
}
}
}
}
public String getTmJndiName() {
return tmJndiName;
}
public void setTmJndiName(String tmJndiName) {
this.tmJndiName = tmJndiName;
}
public boolean isTmFromJndi() {
return tmFromJndi;
}
/**
* Allow transaction manager resolution from JNDI (ee deployment)
* @param tmFromJndi
*/
public void setTmFromJndi(boolean tmFromJndi) {
this.tmFromJndi = tmFromJndi;
}
@Override
public QueueConnection createQueueConnection() throws JMSException {
return (QueueConnection) createConnection();
}
@Override
public QueueConnection createQueueConnection(String userName, String password) throws JMSException {
return (QueueConnection) createConnection(userName, password);
}
@Override
public TopicConnection createTopicConnection() throws JMSException {
return (TopicConnection) createConnection();
}
@Override
public TopicConnection createTopicConnection(String userName, String password) throws JMSException {
return (TopicConnection) createConnection(userName, password);
}
}
| 7,724 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/IntrospectionSupport.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class IntrospectionSupport {
private static final Logger LOG = LoggerFactory.getLogger(IntrospectionSupport.class);
private IntrospectionSupport() {
}
@SuppressWarnings("rawtypes")
public static boolean setProperties(Object target, Map props) {
boolean rc = false;
if (target == null) {
throw new IllegalArgumentException("target was null.");
}
if (props == null) {
throw new IllegalArgumentException("props was null.");
}
for (Iterator<?> iter = props.entrySet().iterator(); iter.hasNext();) {
Entry<?,?> entry = (Entry<?,?>)iter.next();
if (setProperty(target, (String)entry.getKey(), entry.getValue())) {
iter.remove();
rc = true;
}
}
return rc;
}
public static boolean setProperty(Object target, String name, Object value) {
try {
Class<?> clazz = target.getClass();
if (target instanceof SSLServerSocket) {
// overcome illegal access issues with internal implementation class
clazz = SSLServerSocket.class;
}
Method setter = findSetterMethod(clazz, name);
if (setter == null) {
return false;
}
// If the type is null or it matches the needed type, just use the
// value directly
if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
setter.invoke(target, value);
} else {
// We need to convert it
setter.invoke(target, convert(value, setter.getParameterTypes()[0]));
}
return true;
} catch (Exception e) {
LOG.error(String.format("Could not set property %s on %s", name, target), e);
return false;
}
}
@SuppressWarnings({
"rawtypes", "unchecked"
})
private static Object convert(Object value, Class to) {
if (value == null) {
// lets avoid NullPointerException when converting to boolean for null values
if (boolean.class.isAssignableFrom(to)) {
return Boolean.FALSE;
}
return null;
}
// eager same instance type test to avoid the overhead of invoking the type converter
// if already same type
if (to.isAssignableFrom(value.getClass())) {
return to.cast(value);
}
if (boolean.class.isAssignableFrom(to) && value instanceof String) {
return Boolean.valueOf((String) value);
}
throw new IllegalArgumentException("Cannot convert from " + value.getClass()
+ " to " + to + " with value " + value);
}
private static Method findSetterMethod(Class<?> clazz, String name) {
// Build the method name.
name = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
Class<?> params[] = method.getParameterTypes();
if (method.getName().equals(name) && params.length == 1 ) {
return method;
}
}
return null;
}
}
| 7,725 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledSession.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.io.Serializable;
import java.lang.IllegalStateException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.jms.*;
import javax.transaction.xa.XAResource;
import org.apache.commons.pool.KeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PooledSession implements Session, TopicSession, QueueSession, XASession {
private static final transient Logger LOG = LoggerFactory.getLogger(PooledSession.class);
private final SessionKey key;
private final KeyedObjectPool<SessionKey, PooledSession> sessionPool;
private final CopyOnWriteArrayList<MessageConsumer> consumers = new CopyOnWriteArrayList<MessageConsumer>();
private final CopyOnWriteArrayList<QueueBrowser> browsers = new CopyOnWriteArrayList<QueueBrowser>();
private final CopyOnWriteArrayList<PooledSessionEventListener> sessionEventListeners = new CopyOnWriteArrayList<PooledSessionEventListener>();
private MessageProducer producer;
private TopicPublisher publisher;
private QueueSender sender;
private Session session;
private boolean transactional = true;
private boolean ignoreClose;
private boolean isXa;
private boolean useAnonymousProducers = true;
public PooledSession(SessionKey key, Session session, KeyedObjectPool<SessionKey, PooledSession> sessionPool, boolean transactional, boolean anonymous) {
this.key = key;
this.session = session;
this.sessionPool = sessionPool;
this.transactional = transactional;
this.useAnonymousProducers = anonymous;
}
public void addSessionEventListener(PooledSessionEventListener listener) {
// only add if really needed
if (!sessionEventListeners.contains(listener)) {
this.sessionEventListeners.add(listener);
}
}
protected boolean isIgnoreClose() {
return ignoreClose;
}
protected void setIgnoreClose(boolean ignoreClose) {
this.ignoreClose = ignoreClose;
}
@Override
public void close() throws JMSException {
if (!ignoreClose) {
boolean invalidate = false;
try {
// lets reset the session
getInternalSession().setMessageListener(null);
// Close any consumers and browsers that may have been created.
for (Iterator<MessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
MessageConsumer consumer = iter.next();
consumer.close();
}
for (Iterator<QueueBrowser> iter = browsers.iterator(); iter.hasNext();) {
QueueBrowser browser = iter.next();
browser.close();
}
if (transactional && !isXa) {
try {
getInternalSession().rollback();
} catch (JMSException e) {
invalidate = true;
LOG.warn("Caught exception trying rollback() when putting session back into the pool, will invalidate. " + e, e);
}
}
} catch (JMSException ex) {
invalidate = true;
LOG.warn("Caught exception trying close() when putting session back into the pool, will invalidate. " + ex, ex);
} finally {
consumers.clear();
browsers.clear();
for (PooledSessionEventListener listener : this.sessionEventListeners) {
listener.onSessionClosed(this);
}
sessionEventListeners.clear();
}
if (invalidate) {
// lets close the session and not put the session back into the pool
// instead invalidate it so the pool can create a new one on demand.
if (session != null) {
try {
session.close();
} catch (JMSException e1) {
LOG.trace("Ignoring exception on close as discarding session: " + e1, e1);
}
session = null;
}
try {
sessionPool.invalidateObject(key, this);
} catch (Exception e) {
LOG.trace("Ignoring exception on invalidateObject as discarding session: " + e, e);
}
} else {
try {
sessionPool.returnObject(key, this);
} catch (Exception e) {
javax.jms.IllegalStateException illegalStateException = new javax.jms.IllegalStateException(e.toString());
illegalStateException.initCause(e);
throw illegalStateException;
}
}
}
}
@Override
public void commit() throws JMSException {
getInternalSession().commit();
}
@Override
public BytesMessage createBytesMessage() throws JMSException {
return getInternalSession().createBytesMessage();
}
@Override
public MapMessage createMapMessage() throws JMSException {
return getInternalSession().createMapMessage();
}
@Override
public Message createMessage() throws JMSException {
return getInternalSession().createMessage();
}
@Override
public ObjectMessage createObjectMessage() throws JMSException {
return getInternalSession().createObjectMessage();
}
@Override
public ObjectMessage createObjectMessage(Serializable serializable) throws JMSException {
return getInternalSession().createObjectMessage(serializable);
}
@Override
public Queue createQueue(String s) throws JMSException {
return getInternalSession().createQueue(s);
}
@Override
public StreamMessage createStreamMessage() throws JMSException {
return getInternalSession().createStreamMessage();
}
@Override
public TemporaryQueue createTemporaryQueue() throws JMSException {
TemporaryQueue result;
result = getInternalSession().createTemporaryQueue();
// Notify all of the listeners of the created temporary Queue.
for (PooledSessionEventListener listener : this.sessionEventListeners) {
listener.onTemporaryQueueCreate(result);
}
return result;
}
@Override
public TemporaryTopic createTemporaryTopic() throws JMSException {
TemporaryTopic result;
result = getInternalSession().createTemporaryTopic();
// Notify all of the listeners of the created temporary Topic.
for (PooledSessionEventListener listener : this.sessionEventListeners) {
listener.onTemporaryTopicCreate(result);
}
return result;
}
@Override
public void unsubscribe(String s) throws JMSException {
getInternalSession().unsubscribe(s);
}
@Override
public TextMessage createTextMessage() throws JMSException {
return getInternalSession().createTextMessage();
}
@Override
public TextMessage createTextMessage(String s) throws JMSException {
return getInternalSession().createTextMessage(s);
}
@Override
public Topic createTopic(String s) throws JMSException {
return getInternalSession().createTopic(s);
}
@Override
public int getAcknowledgeMode() throws JMSException {
return getInternalSession().getAcknowledgeMode();
}
@Override
public boolean getTransacted() throws JMSException {
return getInternalSession().getTransacted();
}
@Override
public void recover() throws JMSException {
getInternalSession().recover();
}
@Override
public void rollback() throws JMSException {
getInternalSession().rollback();
}
@Override
public XAResource getXAResource() {
if (session instanceof XASession) {
return ((XASession) session).getXAResource();
}
return null;
}
@Override
public Session getSession() {
return this;
}
@Override
public void run() {
if (session != null) {
session.run();
}
}
// Consumer related methods
// -------------------------------------------------------------------------
@Override
public QueueBrowser createBrowser(Queue queue) throws JMSException {
return addQueueBrowser(getInternalSession().createBrowser(queue));
}
@Override
public QueueBrowser createBrowser(Queue queue, String selector) throws JMSException {
return addQueueBrowser(getInternalSession().createBrowser(queue, selector));
}
@Override
public MessageConsumer createConsumer(Destination destination) throws JMSException {
return addConsumer(getInternalSession().createConsumer(destination));
}
@Override
public MessageConsumer createConsumer(Destination destination, String selector) throws JMSException {
return addConsumer(getInternalSession().createConsumer(destination, selector));
}
@Override
public MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal) throws JMSException {
return addConsumer(getInternalSession().createConsumer(destination, selector, noLocal));
}
@Override
public TopicSubscriber createDurableSubscriber(Topic topic, String selector) throws JMSException {
return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, selector));
}
@Override
public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal) throws JMSException {
return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, name, selector, noLocal));
}
@Override
public MessageListener getMessageListener() throws JMSException {
return getInternalSession().getMessageListener();
}
@Override
public void setMessageListener(MessageListener messageListener) throws JMSException {
getInternalSession().setMessageListener(messageListener);
}
@Override
public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
return addTopicSubscriber(((TopicSession) getInternalSession()).createSubscriber(topic));
}
@Override
public TopicSubscriber createSubscriber(Topic topic, String selector, boolean local) throws JMSException {
return addTopicSubscriber(((TopicSession) getInternalSession()).createSubscriber(topic, selector, local));
}
@Override
public QueueReceiver createReceiver(Queue queue) throws JMSException {
return addQueueReceiver(((QueueSession) getInternalSession()).createReceiver(queue));
}
@Override
public QueueReceiver createReceiver(Queue queue, String selector) throws JMSException {
return addQueueReceiver(((QueueSession) getInternalSession()).createReceiver(queue, selector));
}
// Producer related methods
// -------------------------------------------------------------------------
@Override
public MessageProducer createProducer(Destination destination) throws JMSException {
return new PooledProducer(getMessageProducer(destination), destination);
}
@Override
public QueueSender createSender(Queue queue) throws JMSException {
return new PooledQueueSender(getQueueSender(queue), queue);
}
@Override
public TopicPublisher createPublisher(Topic topic) throws JMSException {
return new PooledTopicPublisher(getTopicPublisher(topic), topic);
}
public Session getInternalSession() throws IllegalStateException {
if (session == null) {
throw new IllegalStateException("The session has already been closed");
}
return session;
}
public MessageProducer getMessageProducer() throws JMSException {
return getMessageProducer(null);
}
public MessageProducer getMessageProducer(Destination destination) throws JMSException {
MessageProducer result = null;
if (useAnonymousProducers) {
if (producer == null) {
// Don't allow for duplicate anonymous producers.
synchronized (this) {
if (producer == null) {
producer = getInternalSession().createProducer(null);
}
}
}
result = producer;
} else {
result = getInternalSession().createProducer(destination);
}
return result;
}
public QueueSender getQueueSender() throws JMSException {
return getQueueSender(null);
}
public QueueSender getQueueSender(Queue destination) throws JMSException {
QueueSender result = null;
if (useAnonymousProducers) {
if (sender == null) {
// Don't allow for duplicate anonymous producers.
synchronized (this) {
if (sender == null) {
sender = ((QueueSession) getInternalSession()).createSender(null);
}
}
}
result = sender;
} else {
result = ((QueueSession) getInternalSession()).createSender(destination);
}
return result;
}
public TopicPublisher getTopicPublisher() throws JMSException {
return getTopicPublisher(null);
}
public TopicPublisher getTopicPublisher(Topic destination) throws JMSException {
TopicPublisher result = null;
if (useAnonymousProducers) {
if (publisher == null) {
// Don't allow for duplicate anonymous producers.
synchronized (this) {
if (publisher == null) {
publisher = ((TopicSession) getInternalSession()).createPublisher(null);
}
}
}
result = publisher;
} else {
result = ((TopicSession) getInternalSession()).createPublisher(destination);
}
return result;
}
private QueueBrowser addQueueBrowser(QueueBrowser browser) {
browsers.add(browser);
return browser;
}
private MessageConsumer addConsumer(MessageConsumer consumer) {
consumers.add(consumer);
// must wrap in PooledMessageConsumer to ensure the onConsumerClose
// method is invoked when the returned consumer is closed, to avoid memory
// leak in this session class in case many consumers is created
return new PooledMessageConsumer(this, consumer);
}
private TopicSubscriber addTopicSubscriber(TopicSubscriber subscriber) {
consumers.add(subscriber);
return subscriber;
}
private QueueReceiver addQueueReceiver(QueueReceiver receiver) {
consumers.add(receiver);
return receiver;
}
public void setIsXa(boolean isXa) {
this.isXa = isXa;
}
@Override
public String toString() {
return "PooledSession { " + session + " }";
}
/**
* Callback invoked when the consumer is closed.
* <p/>
* This is used to keep track of an explicit closed consumer created by this
* session, by which we know do not need to keep track of the consumer, as
* its already closed.
*
* @param consumer
* the consumer which is being closed
*/
protected void onConsumerClose(MessageConsumer consumer) {
consumers.remove(consumer);
}
}
| 7,726 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledTopicPublisher.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Topic;
import javax.jms.TopicPublisher;
/**
*
*/
public class PooledTopicPublisher extends PooledProducer implements TopicPublisher {
public PooledTopicPublisher(TopicPublisher messageProducer, Destination destination) throws JMSException {
super(messageProducer, destination);
}
public Topic getTopic() throws JMSException {
return getTopicPublisher().getTopic();
}
public void publish(Message message) throws JMSException {
getTopicPublisher().publish((Topic) getDestination(), message);
}
public void publish(Message message, int i, int i1, long l) throws JMSException {
getTopicPublisher().publish((Topic) getDestination(), message, i, i1, l);
}
public void publish(Topic topic, Message message) throws JMSException {
getTopicPublisher().publish(topic, message);
}
public void publish(Topic topic, Message message, int i, int i1, long l) throws JMSException {
getTopicPublisher().publish(topic, message, i, i1, l);
}
protected TopicPublisher getTopicPublisher() {
return (TopicPublisher) getMessageProducer();
}
}
| 7,727 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledMessageConsumer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
/**
* A {@link MessageConsumer} which was created by {@link PooledSession}.
*/
public class PooledMessageConsumer implements MessageConsumer {
private final PooledSession session;
private final MessageConsumer delegate;
/**
* Wraps the message consumer.
*
* @param session the pooled session
* @param delegate the created consumer to wrap
*/
public PooledMessageConsumer(PooledSession session, MessageConsumer delegate) {
this.session = session;
this.delegate = delegate;
}
public void close() throws JMSException {
// ensure session removes consumer as its closed now
session.onConsumerClose(delegate);
delegate.close();
}
public MessageListener getMessageListener() throws JMSException {
return delegate.getMessageListener();
}
public String getMessageSelector() throws JMSException {
return delegate.getMessageSelector();
}
public Message receive() throws JMSException {
return delegate.receive();
}
public Message receive(long timeout) throws JMSException {
return delegate.receive(timeout);
}
public Message receiveNoWait() throws JMSException {
return delegate.receiveNoWait();
}
public void setMessageListener(MessageListener listener) throws JMSException {
delegate.setMessageListener(listener);
}
public String toString() {
return delegate.toString();
}
}
| 7,728 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/Activator.java | /*
* Copyright 2014 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.xbean.blueprint.context.impl.XBeanNamespaceHandler;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private static final String JMS_NS_URI = "http://aries.apache.org/xmlns/transaction-jms/2.0";
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
@Override
public void start(BundleContext context) throws Exception {
// Expose blueprint namespace handler if xbean is present
try {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("osgi.service.blueprint.namespace", JMS_NS_URI);
context.registerService(NamespaceHandler.class, jmsNamespaceHandler(context), props);
} catch (NoClassDefFoundError e) {
LOGGER.warn("Unable to register JMS blueprint namespace handler (xbean-blueprint not available).");
} catch (Exception e) {
LOGGER.error("Unable to register JMS blueprint namespace handler", e);
}
}
private NamespaceHandler jmsNamespaceHandler(BundleContext context) throws Exception {
return new XBeanNamespaceHandler(
JMS_NS_URI,
"org.apache.aries.transaction.jms.xsd",
context.getBundle(),
"META-INF/services/org/apache/xbean/spring/http/aries.apache.org/xmlns/transaction-jms/2.0"
);
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 7,729 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledSessionEventListener.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
interface PooledSessionEventListener {
/**
* Called on successful creation of a new TemporaryQueue.
*
* @param tempQueue
* The TemporaryQueue just created.
*/
void onTemporaryQueueCreate(TemporaryQueue tempQueue);
/**
* Called on successful creation of a new TemporaryTopic.
*
* @param tempTopic
* The TemporaryTopic just created.
*/
void onTemporaryTopicCreate(TemporaryTopic tempTopic);
/**
* Called when the PooledSession is closed.
*
* @param session
* The PooledSession that has been closed.
*/
void onSessionClosed(PooledSession session);
}
| 7,730 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/SessionKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
/**
* A cache key for the session details
*
*
*/
public class SessionKey {
private boolean transacted;
private int ackMode;
private int hash;
public SessionKey(boolean transacted, int ackMode) {
this.transacted = transacted;
this.ackMode = ackMode;
hash = ackMode;
if (transacted) {
hash = 31 * hash + 1;
}
}
public int hashCode() {
return hash;
}
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that instanceof SessionKey) {
return equals((SessionKey) that);
}
return false;
}
public boolean equals(SessionKey that) {
return this.transacted == that.transacted && this.ackMode == that.ackMode;
}
public boolean isTransacted() {
return transacted;
}
public int getAckMode() {
return ackMode;
}
}
| 7,731 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/RecoverableConnectionPool.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.XASession;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
public class RecoverableConnectionPool extends XaConnectionPool {
private String name;
public RecoverableConnectionPool(Connection connection, TransactionManager transactionManager, String name) {
super(connection, transactionManager);
this.name = name;
}
protected XAResource createXaResource(PooledSession session) throws JMSException {
XAResource xares = ((XASession) session.getInternalSession()).getXAResource();
if (name != null) {
xares = new WrapperNamedXAResource(xares, name);
}
return xares;
}
}
| 7,732 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/PooledConnection.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.jms.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a proxy {@link Connection} which is-a {@link TopicConnection} and
* {@link QueueConnection} which is pooled and on {@link #close()} will return
* itself to the sessionPool.
*
* <b>NOTE</b> this implementation is only intended for use when sending
* messages. It does not deal with pooling of consumers; for that look at a
* library like <a href="http://jencks.org/">Jencks</a> such as in <a
* href="http://jencks.org/Message+Driven+POJOs">this example</a>
*
*/
public class PooledConnection implements TopicConnection, QueueConnection, PooledSessionEventListener {
private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnection.class);
protected ConnectionPool pool;
private volatile boolean stopped;
private final List<TemporaryQueue> connTempQueues = new CopyOnWriteArrayList<TemporaryQueue>();
private final List<TemporaryTopic> connTempTopics = new CopyOnWriteArrayList<TemporaryTopic>();
private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
/**
* Creates a new PooledConnection instance that uses the given ConnectionPool to create
* and manage its resources. The ConnectionPool instance can be shared amongst many
* PooledConnection instances.
*
* @param pool
* The connection and pool manager backing this proxy connection object.
*/
public PooledConnection(ConnectionPool pool) {
this.pool = pool;
}
/**
* Factory method to create a new instance.
*/
public PooledConnection newInstance() {
return new PooledConnection(pool);
}
@Override
public void close() throws JMSException {
this.cleanupConnectionTemporaryDestinations();
this.cleanupAllLoanedSessions();
if (this.pool != null) {
this.pool.decrementReferenceCount();
this.pool = null;
}
}
@Override
public void start() throws JMSException {
assertNotClosed();
pool.start();
}
@Override
public void stop() throws JMSException {
stopped = true;
}
@Override
public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
return getConnection().createConnectionConsumer(destination, selector, serverSessionPool, maxMessages);
}
@Override
public ConnectionConsumer createConnectionConsumer(Topic topic, String s, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
return getConnection().createConnectionConsumer(topic, s, serverSessionPool, maxMessages);
}
@Override
public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, ServerSessionPool serverSessionPool, int i) throws JMSException {
return getConnection().createDurableConnectionConsumer(topic, selector, s1, serverSessionPool, i);
}
@Override
public String getClientID() throws JMSException {
return getConnection().getClientID();
}
@Override
public ExceptionListener getExceptionListener() throws JMSException {
return getConnection().getExceptionListener();
}
@Override
public ConnectionMetaData getMetaData() throws JMSException {
return getConnection().getMetaData();
}
@Override
public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
getConnection().setExceptionListener(exceptionListener);
}
@Override
public void setClientID(String clientID) throws JMSException {
// ignore repeated calls to setClientID() with the same client id
// this could happen when a JMS component such as Spring that uses a
// PooledConnectionFactory shuts down and reinitializes.
if (this.getConnection().getClientID() == null || !this.getClientID().equals(clientID)) {
getConnection().setClientID(clientID);
}
}
@Override
public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
return getConnection().createConnectionConsumer(queue, selector, serverSessionPool, maxMessages);
}
// Session factory methods
// -------------------------------------------------------------------------
@Override
public QueueSession createQueueSession(boolean transacted, int ackMode) throws JMSException {
return (QueueSession) createSession(transacted, ackMode);
}
@Override
public TopicSession createTopicSession(boolean transacted, int ackMode) throws JMSException {
return (TopicSession) createSession(transacted, ackMode);
}
@Override
public Session createSession(boolean transacted, int ackMode) throws JMSException {
PooledSession result;
result = (PooledSession) pool.createSession(transacted, ackMode);
// Store the session so we can close the sessions that this PooledConnection
// created in order to ensure that consumers etc are closed per the JMS contract.
loanedSessions.add(result);
// Add a event listener to the session that notifies us when the session
// creates / destroys temporary destinations and closes etc.
result.addSessionEventListener(this);
return result;
}
// Implementation methods
// -------------------------------------------------------------------------
@Override
public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
connTempQueues.add(tempQueue);
}
@Override
public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
connTempTopics.add(tempTopic);
}
@Override
public void onSessionClosed(PooledSession session) {
if (session != null) {
this.loanedSessions.remove(session);
}
}
public Connection getConnection() throws JMSException {
assertNotClosed();
return pool.getConnection();
}
protected void assertNotClosed() throws javax.jms.IllegalStateException {
if (stopped || pool == null) {
throw new javax.jms.IllegalStateException("Connection closed");
}
}
protected Session createSession(SessionKey key) throws JMSException {
return getConnection().createSession(key.isTransacted(), key.getAckMode());
}
@Override
public String toString() {
return "PooledConnection { " + pool + " }";
}
/**
* Remove all of the temporary destinations created for this connection.
* This is important since the underlying connection may be reused over a
* long period of time, accumulating all of the temporary destinations from
* each use. However, from the perspective of the lifecycle from the
* client's view, close() closes the connection and, therefore, deletes all
* of the temporary destinations created.
*/
protected void cleanupConnectionTemporaryDestinations() {
for (TemporaryQueue tempQueue : connTempQueues) {
try {
tempQueue.delete();
} catch (JMSException ex) {
LOG.info("failed to delete Temporary Queue \"" + tempQueue.toString() + "\" on closing pooled connection: " + ex.getMessage());
}
}
connTempQueues.clear();
for (TemporaryTopic tempTopic : connTempTopics) {
try {
tempTopic.delete();
} catch (JMSException ex) {
LOG.info("failed to delete Temporary Topic \"" + tempTopic.toString() + "\" on closing pooled connection: " + ex.getMessage());
}
}
connTempTopics.clear();
}
/**
* The PooledSession tracks all Sessions that it created and now we close them. Closing the
* PooledSession will return the internal Session to the Pool of Session after cleaning up
* all the resources that the Session had allocated for this PooledConnection.
*/
protected void cleanupAllLoanedSessions() {
for (PooledSession session : loanedSessions) {
try {
session.close();
} catch (JMSException ex) {
LOG.info("failed to close laoned Session \"" + session + "\" on closing pooled connection: " + ex.getMessage());
}
}
loanedSessions.clear();
}
/**
* @return the total number of Pooled session including idle sessions that are not
* currently loaned out to any client.
*/
public int getNumSessions() {
return this.pool.getNumSessions();
}
/**
* @return the number of Sessions that are currently checked out of this Connection's session pool.
*/
public int getNumActiveSessions() {
return this.pool.getNumActiveSessions();
}
/**
* @return the number of Sessions that are idle in this Connection's sessions pool.
*/
public int getNumtIdleSessions() {
return this.pool.getNumIdleSessions();
}
}
| 7,733 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/XaConnectionPool.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import javax.jms.XAConnection;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
/**
* An XA-aware connection pool. When a session is created and an xa transaction is active,
* the session will automatically be enlisted in the current transaction.
*
* @author gnodet
*/
public class XaConnectionPool extends ConnectionPool {
private final TransactionManager transactionManager;
public XaConnectionPool(Connection connection, TransactionManager transactionManager) {
super(connection);
this.transactionManager = transactionManager;
}
@Override
protected Session makeSession(SessionKey key) throws JMSException {
return ((XAConnection) connection).createXASession();
}
@Override
public Session createSession(boolean transacted, int ackMode) throws JMSException {
try {
boolean isXa = (transactionManager != null && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION);
if (isXa) {
// if the xa tx aborts inflight we don't want to auto create a
// local transaction or auto ack
transacted = false;
ackMode = Session.CLIENT_ACKNOWLEDGE;
} else if (transactionManager != null) {
// cmt or transactionManager managed
transacted = false;
if (ackMode == Session.SESSION_TRANSACTED) {
ackMode = Session.AUTO_ACKNOWLEDGE;
}
}
PooledSession session = (PooledSession) super.createSession(transacted, ackMode);
if (isXa) {
session.addSessionEventListener(new PooledSessionEventListener() {
@Override
public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
}
@Override
public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
}
@Override
public void onSessionClosed(PooledSession session) {
session.setIgnoreClose(true);
session.setIsXa(false);
}
});
session.setIgnoreClose(true);
session.setIsXa(true);
transactionManager.getTransaction().registerSynchronization(new Synchronization(session));
incrementReferenceCount();
transactionManager.getTransaction().enlistResource(createXaResource(session));
} else {
session.setIgnoreClose(false);
}
return session;
} catch (RollbackException e) {
final JMSException jmsException = new JMSException("Rollback Exception");
jmsException.initCause(e);
throw jmsException;
} catch (SystemException e) {
final JMSException jmsException = new JMSException("System Exception");
jmsException.initCause(e);
throw jmsException;
}
}
protected XAResource createXaResource(PooledSession session) throws JMSException {
return session.getXAResource();
}
protected class Synchronization implements javax.transaction.Synchronization {
private final PooledSession session;
private Synchronization(PooledSession session) {
this.session = session;
}
@Override
public void beforeCompletion() {
}
@Override
public void afterCompletion(int status) {
try {
// This will return session to the pool.
session.setIgnoreClose(false);
session.close();
decrementReferenceCount();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
}
| 7,734 |
0 | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms | Create_ds/aries/transaction/transaction-jms/src/main/java/org/apache/aries/transaction/jms/internal/GenericResourceManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.jms.internal;
import java.io.IOException;
import javax.jms.ConnectionFactory;
import javax.jms.XAConnection;
import javax.jms.XAConnectionFactory;
import javax.jms.XASession;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenericResourceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(GenericResourceManager.class);
private String resourceName;
private String userName;
private String password;
private TransactionManager transactionManager;
private ConnectionFactory connectionFactory;
public GenericResourceManager() {
}
public GenericResourceManager(String resourceName, TransactionManager transactionManager, ConnectionFactory connectionFactory) {
this.resourceName = resourceName;
this.transactionManager = transactionManager;
this.connectionFactory = connectionFactory;
}
public void recoverResource() {
try {
if (!Recovery.recover(this)) {
LOGGER.info("Resource manager is unrecoverable");
}
} catch (NoClassDefFoundError e) {
LOGGER.info("Resource manager is unrecoverable due to missing classes: " + e);
} catch (Throwable e) {
LOGGER.warn("Error while recovering resource manager", e);
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
/**
* This class will ensure the broker is properly recovered when wired with
* the Geronimo transaction manager.
*/
public static class Recovery {
public static boolean isRecoverable(GenericResourceManager rm) {
return rm.getConnectionFactory() instanceof XAConnectionFactory &&
rm.getTransactionManager() instanceof RecoverableTransactionManager &&
rm.getResourceName() != null && !"".equals(rm.getResourceName());
}
public static boolean recover(final GenericResourceManager rm) throws IOException {
if (isRecoverable(rm)) {
final XAConnectionFactory connFactory = (XAConnectionFactory) rm.getConnectionFactory();
RecoverableTransactionManager rtxManager = (RecoverableTransactionManager) rm.getTransactionManager();
rtxManager.registerNamedXAResourceFactory(new NamedXAResourceFactory() {
public String getName() {
return rm.getResourceName();
}
public NamedXAResource getNamedXAResource() throws SystemException {
try {
final XAConnection xaConnection;
if (rm.getUserName() != null && rm.getPassword() != null) {
xaConnection = connFactory.createXAConnection(rm.getUserName(), rm.getPassword());
} else {
xaConnection = connFactory.createXAConnection();
}
final XASession session = xaConnection.createXASession();
xaConnection.start();
LOGGER.debug("new namedXAResource's connection: " + xaConnection);
return new ConnectionAndWrapperNamedXAResource(session.getXAResource(), getName(), xaConnection);
} catch (Exception e) {
SystemException se = new SystemException("Failed to create ConnectionAndWrapperNamedXAResource, " + e.getLocalizedMessage());
se.initCause(e);
LOGGER.error(se.getLocalizedMessage(), se);
throw se;
}
}
public void returnNamedXAResource(NamedXAResource namedXaResource) {
if (namedXaResource instanceof ConnectionAndWrapperNamedXAResource) {
try {
LOGGER.debug("closing returned namedXAResource's connection: " + ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection);
((ConnectionAndWrapperNamedXAResource)namedXaResource).connection.close();
} catch (Exception ignored) {
LOGGER.debug("failed to close returned namedXAResource: " + namedXaResource, ignored);
}
}
}
});
return true;
} else {
return false;
}
}
}
public static class ConnectionAndWrapperNamedXAResource extends WrapperNamedXAResource {
final XAConnection connection;
public ConnectionAndWrapperNamedXAResource(XAResource xaResource, String name, XAConnection connection) {
super(xaResource, name);
this.connection = connection;
}
}
}
| 7,735 |
0 | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction/internal/LogConversionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import javax.transaction.xa.Xid;
import org.apache.commons.io.FileUtils;
import org.apache.geronimo.transaction.log.HOWLLog;
import org.apache.geronimo.transaction.manager.TransactionBranchInfo;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.apache.geronimo.transaction.manager.XidImpl;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class LogConversionTest {
public static Logger LOG = LoggerFactory.getLogger(LogConversionTest.class);
private static XidFactory xidFactory = new TestXidFactoryImpl("org.apache.aries.transaction.test".getBytes());
private static File BASE = new File(System.getProperty("user.dir"), "txlogs");
private static long start = 42L;
private static long count = start;
@Test
public void initialConfiguration() throws Exception {
File logDir = new File(BASE, "initialConfiguration");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Dictionary<String, Object> properties = new Hashtable<String, Object>();
createLog("initialConfiguration", "transaction", 2, -1, 1, properties);
assertFalse(TransactionLogUtils.copyActiveTransactions(null, properties));
}
@Test
public void initialConfigurationEmptyTransactionLog() throws Exception {
File logDir = new File(BASE, "initialConfigurationEmptyTransactionLog");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Dictionary<String, Object> properties = new Hashtable<String, Object>();
createLog("initialConfigurationEmptyTransactionLog", "transaction", 2, -1, 1, properties);
new RandomAccessFile(new File(logDir, "transaction_1.log"), "rw").close();
new RandomAccessFile(new File(logDir, "transaction_2.log"), "rw").close();
assertFalse(TransactionLogUtils.copyActiveTransactions(null, properties));
}
@Test
public void initialConfigurationExistingTransactionLogNoChanges() throws Exception {
File logDir = new File(BASE, "initialConfigurationExistingTransactionLogNoChanges");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Dictionary<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("initialConfigurationExistingTransactionLogNoChanges", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
assertFalse(TransactionLogUtils.copyActiveTransactions(null, properties));
assertThat("Transaction log should not be touched", new File(logDir, "transaction_1.log").lastModified(), equalTo(lm));
}
@Test
@SuppressWarnings("unchecked")
public void existingTransactionLogChangedLogDir() throws Exception {
File logDir = new File(BASE, "existingTransactionLogChangedLogDir");
File newLogDir = new File(BASE, "existingTransactionLogChangedLogDir-new");
FileUtils.deleteDirectory(logDir);
FileUtils.deleteDirectory(newLogDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("existingTransactionLogChangedLogDir", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.logFileDir", newLogDir.getAbsolutePath());
assertFalse(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertThat("Transaction log should not be touched", new File(newLogDir, "transaction_1.log").lastModified(), equalTo(lm));
assertFalse("Old transaction log should be moved", logDir.exists());
assertTrue("New transaction log should be created", newLogDir.exists());
}
@Test
@SuppressWarnings("unchecked")
public void unknownExistingTransactionLogChangedLogDir() throws Exception {
File logDir = new File(BASE, "unknownExistingTransactionLogChangedLogDir");
File newLogDir = new File(BASE, "unknownExistingTransactionLogChangedLogDir-new");
FileUtils.deleteDirectory(logDir);
FileUtils.deleteDirectory(newLogDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("unknownExistingTransactionLogChangedLogDir", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.logFileDir", newLogDir.getAbsolutePath());
assertFalse(TransactionLogUtils.copyActiveTransactions(null, newConfig));
assertFalse("Transaction log should not exist", new File(newLogDir, "transaction_1.log").exists());
assertTrue("Old transaction log should not be removed", logDir.exists());
assertFalse("New transaction log should not be created (will be created on TX Manager startup)", newLogDir.exists());
}
@Test
@SuppressWarnings("unchecked")
public void changedNumberOfFiles() throws Exception {
File logDir = new File(BASE, "changedNumberOfFiles");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("changedNumberOfFiles", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.maxLogFiles", "20");
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertTrue("Transaction log should exist", new File(logDir, "transaction_1.log").exists());
assertTrue("There should be 20 transaction log files", new File(logDir, "transaction_20.log").exists());
assertThat("Transaction log should be processed", new File(logDir, "transaction_1.log").lastModified(), not(equalTo(lm)));
}
private long earlierLastModified(File file) {
file.setLastModified(file.lastModified() - 10000L);
return file.lastModified();
}
@Test
@SuppressWarnings("unchecked")
public void changedMaxBlocksPerFile() throws Exception {
File logDir = new File(BASE, "changedMaxBlocksPerFile");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("changedMaxBlocksPerFile", "transaction", 3, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.maxBlocksPerFile", "20");
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertTrue("Transaction log should exist", new File(logDir, "transaction_1.log").exists());
assertFalse("There should be 3 transaction log files", new File(logDir, "transaction_4.log").exists());
assertThat("Transaction log should be processed", new File(logDir, "transaction_1.log").lastModified(), not(equalTo(lm)));
}
@Test
@SuppressWarnings("unchecked")
public void changedBlockSize() throws Exception {
File logDir = new File(BASE, "changedBlockSize");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("changedBlockSize", "transaction", 3, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.bufferSize", "32");
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertTrue("Transaction log should exist", new File(logDir, "transaction_1.log").exists());
assertThat("Transaction log should be processed", new File(logDir, "transaction_1.log").lastModified(), not(equalTo(lm)));
}
@Test
@SuppressWarnings("unchecked")
public void changed3ParametersAndLogDir() throws Exception {
File logDir = new File(BASE, "changed3ParametersAndLogDir");
File newLogDir = new File(BASE, "changed3ParametersAndLogDir-new");
FileUtils.deleteDirectory(logDir);
FileUtils.deleteDirectory(newLogDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("changed3ParametersAndLogDir", "transaction", 3, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.maxLogFiles", "4");
newConfig.put("aries.transaction.howl.maxBlocksPerFile", "4");
newConfig.put("aries.transaction.howl.bufferSize", "4");
newConfig.put("aries.transaction.howl.logFileDir", newLogDir.getAbsolutePath());
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertTrue("Old transaction log should exist", new File(logDir, "transaction_1.log").exists());
assertTrue("New transaction log should exist", new File(newLogDir, "transaction_1.log").exists());
assertThat("Old transaction log should be touched (HOWL Log opened)", new File(logDir, "transaction_1.log").lastModified(), not(equalTo(lm)));
}
@Test
@SuppressWarnings("unchecked")
public void existingTransactionLogChangedLogFileName() throws Exception {
File logDir = new File(BASE, "existingTransactionLogChangedLogFileName");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("existingTransactionLogChangedLogFileName", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
earlierLastModified(new File(logDir, "transaction_1.log"));
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.logFileName", "megatransaction");
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertFalse("Old transaction log should not exist", new File(logDir, "transaction_1.log").exists());
assertTrue("New transaction log should exist", new File(logDir, "megatransaction_1.log").exists());
}
@Test
@SuppressWarnings("unchecked")
public void existingTransactionLogChangedLogFileNameAndLogDir() throws Exception {
File logDir = new File(BASE, "existingTransactionLogChangedLogFileNameAndLogDir");
File newLogDir = new File(BASE, "existingTransactionLogChangedLogFileNameAndLogDir-new");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("existingTransactionLogChangedLogFileNameAndLogDir", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
earlierLastModified(new File(logDir, "transaction_1.log"));
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.logFileName", "megatransaction");
newConfig.put("aries.transaction.howl.logFileDir", newLogDir.getAbsolutePath());
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertFalse("Old transaction log should not exist", new File(logDir, "transaction_1.log").exists());
assertTrue("New transaction log should exist", new File(newLogDir, "megatransaction_1.log").exists());
}
@Test
@SuppressWarnings("unchecked")
public void existingTransactionLogChangedLogFileNameAndBlockSize() throws Exception {
File logDir = new File(BASE, "existingTransactionLogChangedLogFileNameAndBlockSize");
FileUtils.deleteDirectory(logDir);
logDir.mkdirs();
Hashtable<String, Object> properties = new Hashtable<String, Object>();
HOWLLog txLog = createLog("existingTransactionLogChangedLogFileNameAndBlockSize", "transaction", 2, -1, 1, properties);
txLog.doStart();
transaction(txLog, 1, false);
txLog.doStop();
long lm = earlierLastModified(new File(logDir, "transaction_1.log"));
Hashtable<String, Object> newConfig = (Hashtable<String, Object>) properties.clone();
newConfig.put("aries.transaction.howl.logFileName", "megatransaction");
newConfig.put("aries.transaction.howl.bufferSize", "4");
assertTrue(TransactionLogUtils.copyActiveTransactions(properties, newConfig));
assertThat("Old transaction log should be touched (HOWL Log opened)", new File(logDir, "transaction_1.log").lastModified(), not(equalTo(lm)));
assertTrue("New transaction log should exist", new File(logDir, "megatransaction_1.log").exists());
}
private HOWLLog createLog(String logFileDir, String logFileName,
int maxLogFiles, int maxBlocksPerFile, int bufferSizeInKB,
Dictionary<String, Object> properties) throws Exception {
properties.put("aries.transaction.recoverable", "true");
properties.put("aries.transaction.howl.bufferClassName", "org.objectweb.howl.log.BlockLogBuffer");
properties.put("aries.transaction.howl.checksumEnabled", "true");
properties.put("aries.transaction.howl.adler32Checksum", "true");
properties.put("aries.transaction.howl.flushSleepTime", "50");
properties.put("aries.transaction.howl.logFileExt", "log");
properties.put("aries.transaction.howl.logFileName", logFileName);
properties.put("aries.transaction.howl.minBuffers", "1");
properties.put("aries.transaction.howl.maxBuffers", "0");
properties.put("aries.transaction.howl.threadsWaitingForceThreshold", "-1");
properties.put("aries.transaction.flushPartialBuffers", "true");
String absoluteLogFileDir = new File(BASE, logFileDir).getAbsolutePath() + "/";
properties.put("aries.transaction.howl.logFileDir", absoluteLogFileDir);
properties.put("aries.transaction.howl.bufferSize", Integer.toString(bufferSizeInKB));
properties.put("aries.transaction.howl.maxBlocksPerFile", Integer.toString(maxBlocksPerFile));
properties.put("aries.transaction.howl.maxLogFiles", Integer.toString(maxLogFiles));
return new HOWLLog("org.objectweb.howl.log.BlockLogBuffer", bufferSizeInKB,
true, true, 50,
absoluteLogFileDir, "log", logFileName,
maxBlocksPerFile, 0, maxLogFiles, 1, -1, true, xidFactory, null);
}
private void transaction(HOWLLog log, int transactionBranchCount, boolean commit) throws Exception {
Xid xid = xidFactory.createXid();
List<TransactionBranchInfo> txBranches = new LinkedList<TransactionBranchInfo>();
for (int b = 1; b <= transactionBranchCount; b++) {
// TransactionImpl.enlistResource()
Xid branchXid = xidFactory.createBranch(xid, b);
txBranches.add(new TestTransactionBranchInfo(branchXid, String.format("res-%02d", b)));
}
// org.apache.geronimo.transaction.manager.TransactionImpl.internalPrepare()
Object logMark = log.prepare(xid, txBranches);
if (commit) {
// org.apache.geronimo.transaction.manager.CommitTask.run()
log.commit(xid, logMark);
}
}
private static class TestTransactionBranchInfo implements TransactionBranchInfo {
private final Xid xid;
private final String name;
public TestTransactionBranchInfo(Xid xid, String name) {
this.xid = xid;
this.name = name;
}
@Override
public String getResourceName() {
return name;
}
@Override
public Xid getBranchXid() {
return xid;
}
}
private static class TestXidFactoryImpl extends XidFactoryImpl {
private final byte[] baseId = new byte[Xid.MAXGTRIDSIZE];
public TestXidFactoryImpl(byte[] tmId) {
super(tmId);
System.arraycopy(tmId, 0, baseId, 8, tmId.length);
}
@Override
public Xid createXid() {
byte[] globalId = baseId.clone();
long id;
synchronized (this) {
id = count++;
}
insertLong(id, globalId, 0);
return new XidImpl(globalId);
}
@Override
public Xid createBranch(Xid globalId, int branch) {
byte[] branchId = baseId.clone();
branchId[0] = (byte) branch;
branchId[1] = (byte) (branch >>> 8);
branchId[2] = (byte) (branch >>> 16);
branchId[3] = (byte) (branch >>> 24);
insertLong(start, branchId, 4);
return new XidImpl(globalId, branchId);
}
}
}
| 7,736 |
0 | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction/internal/LogTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.io.File;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.log.HOWLLog;
import org.apache.geronimo.transaction.manager.GeronimoTransactionManager;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class LogTest {
int minThreads = 100;
int maxThreads = 100;
int minTxPerThread = 1000;
int maxTxPerThread = 1000;
@Before
public void setUp() {
System.setProperty("org.slf4j.simplelogger.defaultlog", "error");
}
@Test
@Ignore
public void testGeronimo() throws Exception {
System.err.println("Geronimo");
XidFactory xidFactory = new XidFactoryImpl("hi".getBytes());
HOWLLog txLog = new HOWLLog("org.objectweb.howl.log.BlockLogBuffer",
4,
true,
true,
50,
new File(".").getAbsolutePath(),
"log",
"geronimo",
512,
0,
2,
4,
-1,
true,
xidFactory,
null);
txLog.doStart();
GeronimoTransactionManager tm = new GeronimoTransactionManager(600, xidFactory, txLog);
XAResource xar1 = new TestXAResource("res1");
XAResource xar2 = new TestXAResource("res2");
tm.registerNamedXAResourceFactory(new TestXAResourceFactory("res1"));
tm.registerNamedXAResourceFactory(new TestXAResourceFactory("res2"));
for (int i = minThreads; i <= maxThreads; i *= 10) {
for (int j = minTxPerThread; j <= maxTxPerThread; j *= 10) {
long ms = testThroughput(tm, xar1, xar2, i, j);
System.err.println("TPS (" + i + " threads, " + j + " tx) = " + ((i * j) / (ms / 1000.0)));
}
}
txLog.doStop();
System.err.println();
System.err.flush();
}
public long testThroughput(final TransactionManager tm, final XAResource xar1, final XAResource xar2, final int nbThreads, final int nbTxPerThread) throws Exception {
Thread[] threads = new Thread[nbThreads];
for (int thIdx = 0; thIdx < nbThreads; thIdx++) {
threads[thIdx] = new Thread() {
@Override
public void run() {
try {
for (int txIdx = 0; txIdx < nbTxPerThread; txIdx++) {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(xar1);
tx.enlistResource(xar2);
tx.commit();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
};
}
long t0 = System.currentTimeMillis();
for (int thIdx = 0; thIdx < nbThreads; thIdx++) {
threads[thIdx].start();
}
for (int thIdx = 0; thIdx < nbThreads; thIdx++) {
threads[thIdx].join();
}
long t1 = System.currentTimeMillis();
return t1 - t0;
}
public static class TestXAResourceFactory implements NamedXAResourceFactory {
private final String name;
public TestXAResourceFactory(String name) {
this.name = name;
}
public String getName() {
return name;
}
public NamedXAResource getNamedXAResource() throws SystemException {
return new TestXAResource(name);
}
public void returnNamedXAResource(NamedXAResource namedXAResource) {
}
}
public static class TestXAResource implements XAResource, NamedXAResource {
private final String name;
public TestXAResource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void commit(Xid xid, boolean b) throws XAException {
}
public void end(Xid xid, int i) throws XAException {
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return xaResource instanceof TestXAResource && ((TestXAResource) xaResource).name.equals(name);
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int i) throws XAException {
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
}
public boolean setTransactionTimeout(int i) throws XAException {
return false;
}
public void start(Xid xid, int i) throws XAException {
}
}
}
| 7,737 |
0 | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/test/java/org/apache/aries/transaction/internal/XidFactoryImplTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.util.concurrent.TimeUnit;
import javax.transaction.xa.Xid;
import org.apache.aries.transaction.internal.XidFactoryImpl;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class XidFactoryImplTest {
@Test
public void testLong() {
byte[] buffer = new byte[64];
long l1 = 1343120074022l;
XidFactoryImpl.insertLong(l1, buffer, 4);
long l2 = XidFactoryImpl.extractLong(buffer, 4);
assertEquals(l1, l2);
l1 = 1343120074022l - TimeUnit.DAYS.toMillis(15);
XidFactoryImpl.insertLong(l1, buffer, 4);
l2 = XidFactoryImpl.extractLong(buffer, 4);
assertEquals(l1, l2);
}
@Test
public void testAriesFactory() throws Exception {
XidFactory factory = new XidFactoryImpl("hi".getBytes());
Xid id1 = factory.createXid();
Xid id2 = factory.createXid();
assertFalse("Should not match new: " + id1, factory.matchesGlobalId(id1.getGlobalTransactionId()));
assertFalse("Should not match new: " + id2, factory.matchesGlobalId(id2.getGlobalTransactionId()));
Xid b_id1 = factory.createBranch(id1, 1);
Xid b_id2 = factory.createBranch(id2, 1);
assertFalse("Should not match new branch: " + b_id1, factory.matchesBranchId(b_id1.getBranchQualifier()));
assertFalse("Should not match new branch: " + b_id2, factory.matchesBranchId(b_id2.getBranchQualifier()));
Thread.sleep(5);
XidFactory factory2 = new XidFactoryImpl("hi".getBytes());
assertTrue("Should match old: " + id1, factory2.matchesGlobalId(id1.getGlobalTransactionId()));
assertTrue("Should match old: " + id2, factory2.matchesGlobalId(id2.getGlobalTransactionId()));
assertTrue("Should match old branch: " + b_id1, factory2.matchesBranchId(b_id1.getBranchQualifier()));
assertTrue("Should match old branch: " + b_id2, factory2.matchesBranchId(b_id2.getBranchQualifier()));
}
}
| 7,738 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/objectweb/howl | Create_ds/aries/transaction/transaction-manager/src/main/java/org/objectweb/howl/log/Logger.java | /*
* JOnAS: Java(TM) Open Application Server
* Copyright (C) 2004 Bull S.A.
* All rights reserved.
*
* Contact: howl@objectweb.org
*
* This software is licensed under the BSD license.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ------------------------------------------------------------------------------
* $Id: Logger.java,v 1.14 2006/04/21 15:03:36 girouxm Exp $
* ------------------------------------------------------------------------------
*/
package org.objectweb.howl.log;
import java.io.IOException;
/**
* Manage a configured set of two or more physical log files.
*
* <p>Log files have a configured maximum size. When a file has
* reached the configured capacity, Logger switches to
* the next available alternate file. Normally, log files are created
* in advance to guarantee that space is available during execution.
*
* <p>Each log file has a file header containing information
* allowing Logger to reposition and replay the logs
* during a recovery scenario.
*
* <p>LogFile <i> marking </i>
* <p>The LogFile's mark is the the position within the file
* of the oldest active entry.
* Initially the mark is set at the beginning of the file.
* At some configured interval, the caller invokes <i> mark() </i>
* with the key of the oldest active entry in the log.
*
* <p>For XA the key would be for the oldest transaction still
* in committing state. In theory, XA could call <i> mark() </i> every
* time a DONE record is logged. In practice, it should only be
* necessary to call <i> mark() </i> every minute or so depending on the
* capacity of the log files.
*
* <p>The Logger maintains an active mark within the set
* of log files. A file may be reused only if the mark does not
* reside within the file. The Logger will throw
* LogFileOverflowException if an attempt is made to switch to a
* file that contains a mark.
*
* @author Michael Giroux
*
*/
public class Logger extends LogObject
{
/**
* indicates whether the LogFile is open.
* <p>Logger methods return LogClosedException when log is closed.
*/
protected volatile boolean isClosed = true;
/**
* Manages a pool of buffers used for log file IO.
*/
LogBufferManager bmgr = null;
/**
* Manages a pool of files used for log file IO.
*/
LogFileManager lfmgr = null;
/**
* @return activeMark member of the associated LogFileManager.
*/
public long getActiveMark()
{
return lfmgr.activeMark;
}
/**
* Construct a Logger using default Configuration object.
* @throws IOException
*/
public Logger()
throws IOException
{
this(new Configuration());
}
/**
* Construct a Logger using a Configuration supplied
* by the caller.
* @param config Configuration object
* @throws IOException
*/
public Logger(Configuration config)
throws IOException
{
super(config);
lfmgr = new LogFileManager(config);
bmgr = new LogBufferManager(config);
}
/**
* add a USER record consisting of byte[][] to log.
*
* <p>if <i> sync </i> parameter is true, then the method will
* block (in bmgr.put()) until the <i> data </i> buffer is forced to disk.
* Otherwise, the method returns immediately.
*
* @param data record data
* @param sync true if call should block until force
*
* @return a key that can be used to locate the record.
* Some implementations may use the key as a correlation ID
* to associate related records.
*
* When automark is disabled (false) the caller must
* invoke mark() using this key to indicate the location
* of the oldest active entry in the log.
*
* @throws LogClosedException
* @throws LogRecordSizeException
* @throws LogFileOverflowException
* @throws InterruptedException
* @throws IOException
*
* @see #mark(long)
* @see #setAutoMark(boolean)
*/
public long put(byte[][] data, boolean sync)
throws LogClosedException, LogRecordSizeException, LogFileOverflowException,
InterruptedException, IOException
{
return put(LogRecordType.USER, data, sync);
}
/**
* add a USER record consisting of byte[] to the log.
*
* <p>wrap byte[] <i> data </i> in a new byte[][]
* and delegates call to put(byte[][], boolean)
*
* @param data byte[] to be written to log
* @param sync true if caller wishes to block waiting for the
* record to force to disk.
* @return log key for the record
* @throws LogClosedException
* @throws LogRecordSizeException
* @throws LogFileOverflowException
* @throws InterruptedException
* @throws IOException
*/
public long put(byte[] data, boolean sync)
throws LogClosedException, LogRecordSizeException, LogFileOverflowException,
InterruptedException, IOException
{
return put(LogRecordType.USER, new byte[][]{data}, sync);
}
/**
* Sub-classes call this method to write log records with
* a specific record type.
*
* @param type a record type defined in LogRecordType.
* @param data record data to be logged.
* @param sync boolean indicating whether call should
* wait for data to be written to physical disk.
*
* @return a log key that can be used to reference
* the record.
*/
protected long put(short type, byte[][] data, boolean sync)
throws LogClosedException, LogRecordSizeException, LogFileOverflowException,
InterruptedException, IOException
{
synchronized(this)
{
if (isClosed) throw new LogClosedException();
}
// QUESTION: should we deal with exceptions here?
long key = bmgr.put(type, data, sync);
lfmgr.setCurrentKey(key);
return key;
}
/**
* sets the LogFile's mark.
*
* <p><i> mark() </i> provides a generalized method for callers
* to inform the Logger that log space can be released
* for reuse.
*
* <p>calls LogFileManager to process the request.
*
* @param key is a log key returned by a previous call to put().
* @param force a boolean that indicates whether the mark data
* should be forced to disk. When set to <b> true </b> the caller
* is blocked until the mark record is forced to disk.
*
* @throws InvalidLogKeyException
* if <i> key </i> parameter is out of range.
* <i> key </i> must be greater than current activeMark and less than the most recent
* key returned by put().
* @throws LogClosedException
* if this logger instance has been closed.
*/
public void mark(long key, boolean force)
throws InvalidLogKeyException, LogClosedException, IOException, InterruptedException
{
synchronized(this)
{
if (isClosed)
throw new LogClosedException("log is closed");
}
lfmgr.mark(key, force);
}
/**
* calls Logger.mark(key, force) with <i> force </i> set to <b> true </b>.
* <p>Caller is blocked until mark record is forced to disk.
* @param key a log key returned by a previous call to put().
* @throws InvalidLogKeyException
* @throws LogClosedException
* @throws IOException
* @throws InterruptedException
* @see #mark(long, boolean)
*/
public void mark(long key)
throws InvalidLogKeyException, LogClosedException, IOException, InterruptedException
{
mark(key, true);
}
/**
* Sets the LogFile marking mode.
*
* <p>passes call to LogFileManager
*
* @param autoMark true to indicate automatic marking.
*/
public void setAutoMark(boolean autoMark)
throws InvalidLogKeyException, LogClosedException, LogFileOverflowException, IOException, InterruptedException
{
synchronized(this)
{
if (this.isClosed) throw new LogClosedException();
}
lfmgr.setAutoMark(autoMark);
}
/**
* close the Log files and perform necessary cleanup tasks.
*/
public void close() throws IOException, InterruptedException
{
// prevent new threads from adding to the log
synchronized(this) { isClosed = true; }
lfmgr.close();
bmgr.close();
}
/**
* open Log files and perform necessart initialization.
*
* TODO: consider open(String name) to allow named configurations.
* this would allow utility to open two loggers and copy
* old records to new files.
*
*/
public void open()
throws InvalidFileSetException,
IOException, LogConfigurationException, InvalidLogBufferException, InterruptedException
{
lfmgr.open();
try {
bmgr.open();
} catch (ClassNotFoundException e) {
String cnf = "LogBuffer Class not found: " + config.getBufferClassName();
LogConfigurationException lce = new LogConfigurationException(cnf, e);
throw lce;
}
// read header information from each file
lfmgr.init(bmgr);
// indicate that Log is ready for use.
synchronized(this) { isClosed = false; }
}
/**
* Registers a LogEventListener for log event notifications.
*
* @param eventListener object to be notified of logger events.
*/
public void setLogEventListener(LogEventListener eventListener)
{
lfmgr.setLogEventListener(eventListener);
}
/**
* Replays log from a specified mark forward to the current mark.
*
* <p>Beginning with the record located at <i> mark </i>
* the Logger reads log records forward to the end of the log.
* USER records are passed to the <i> listener </i> onRecord()
* method. When the end of log has been reached, replay returns
* one final record with a type of END_OF_LOG to inform <i> listener </i>
* that no further records will be returned.
*
* <p>If an error is encountered while reading the log, the
* <i> listener </i> onError method is called. Replay terminates
* when any error occurs and when END_OF_LOG is encountered.
*
* @param listener an object that implements ReplayListener interface.
* @param mark a log key to begin replay from.
* <p>The <i> mark </i> should be a valid log key returned by the put()
* method. To replay the entire log beginning with the oldest available
* record, <i> mark </i> should be set to zero (0L).
* @throws LogConfigurationException
* most likely because the configured LogBuffer class cannot be found.
* @throws InvalidLogKeyException
* if <i> mark </i> is not a valid log key.
*/
public void replay(ReplayListener listener, long mark)
throws InvalidLogKeyException, LogConfigurationException
{
// replay only the user records.
bmgr.replay(listener, mark, false);
}
/**
* Replays log from the active mark forward to the current position.
*
* @param listener an object that implements ReplayListener interface.
* @throws LogConfigurationException
* most likely because the configured LogBuffer class cannot be found.
* @see #replay(ReplayListener, long)
*/
public void replay(ReplayListener listener) throws LogConfigurationException
{
try {
bmgr.replay(listener, lfmgr.activeMark, false);
} catch (InvalidLogKeyException e) {
// should not happen -- use assert to catch during development
assert false : "Unhandled InvalidLogKeyException" + e.toString();
}
}
/**
* Allows sub-classes of Logger to replay control records.
*
* @param listener ReplayListener to receive the records
* @param mark starting mark (log key) for the replay.
* @param replayCtrlRecords boolean indicating whether to
* return CTRL records.
* @throws InvalidLogKeyException
* If the <i> mark </i> parameter specifies an invalid log key
* (one that does not exist in the current set of log files.)
* @throws LogConfigurationException
*
* @see org.objectweb.howl.log.LogBufferManager#replay(ReplayListener, long, boolean)
*/
protected void replay(ReplayListener listener, long mark, boolean replayCtrlRecords)
throws InvalidLogKeyException, LogConfigurationException
{
bmgr.replay(listener, mark, replayCtrlRecords);
}
/**
* Read a specific record from the log.
* <p>Control records are not filtered by this method.
* If the requested mark is valid and identifies a control record,
* the record will be returned.
* @param lr LogRecord to be updated or null if caller wishes a new
* LogRecord to be allocated.
* @param mark a log key identifying the location of the record
* within the journal
* @return LogRecord containing requested record
* @throws InvalidLogKeyException
* if logkey parameter is < 0L or if the requested key is not within the current range
* of keys in the log.
* @throws LogConfigurationException
* @throws LogException
*/ // FEATURE: 300792
public LogRecord get(LogRecord lr, long mark) throws InvalidLogKeyException,
LogConfigurationException,
LogException, InvalidLogBufferException
{
/* this code is similar to LogBufferManager.replay() -- potential for refactor */
int bsn = bmgr.bsnFromMark(mark);
if (mark < 0 || (bsn == 0 && mark != 0))
throw new InvalidLogKeyException(Long.toHexString(mark));
if (lr == null)
lr = new LogRecord((config.getBufferSize() * 1024)/4); // default to 1/4 buffer size
// allocate a LogBuffer that we can use to read the journal
try {
if (lr.buffer == null)
lr.buffer = bmgr.getLogBuffer(-1);
} catch (ClassNotFoundException e) {
throw new LogConfigurationException(e);
}
LogBuffer buffer = lr.buffer;
// read block containing requested mark
try {
bmgr.forceCurrentBuffer();
lfmgr.read(buffer, bsn);
} catch (IOException e) {
LogFile lf = buffer.lf;
String msg = "Error reading " + lf.file + " @ position [" + lf.position + "]";
throw new LogException(msg, e);
}
if (buffer.bsn == -1)
{
lr.type = LogRecordType.END_OF_LOG;
return lr;
}
// verify we have the desired block
// if requested mark == 0 then we start with the oldest block available
int markBSN = (mark == 0) ? buffer.bsn : bmgr.bsnFromMark(mark);
if (markBSN != buffer.bsn) {
InvalidLogBufferException lbe = new InvalidLogBufferException(
"block read [" + buffer.bsn + "] not block requested: " + markBSN);
throw lbe;
}
/*
* position buffer to requested mark.
*
* Although the mark contains a buffer offset, we search forward
* through the buffer to guarantee that we have the start
* of a record. This protects against using marks that were
* not generated by the current Logger.
*/
lr.get(buffer); // get first record in buffer
if (mark > 0 && mark > bmgr.markFromBsn(markBSN,0)) {
while(lr.key < mark) {
lr.get(buffer);
}
if (lr.key != mark) {
String msg = "The requested mark [" + Long.toHexString(mark) +
"] was not found in the log.";
// BUG 300733 following line changed to throw an exception
throw new InvalidLogKeyException(msg);
}
}
return lr;
}
/**
* Read the journal record that follows the record identified by lr.
* @param lr LogRecord to be updated with the next journal record.
* <p>The LogRecord <code> lr </code> must have been returned
* by a previous call to Logger.get(LogRecord, long).
* <p>Effectively, the record identified by lr is located, and the record
* immediately following it is returned.
* @return LogRecord containing the requested record.
* @throws IllegalArgumentException
* if lr parameter is null or if the lr.buffer member is null.
*/ // FEATURE: 300792
public LogRecord getNext(LogRecord lr)
throws InvalidLogBufferException, LogException
{
if (lr == null || lr.buffer == null) throw new IllegalArgumentException();
LogBuffer buffer = lr.buffer;
// get next record
lr.get(buffer);
if (lr.isEOB())
{
long bsn = buffer.bsn; // so we can test for wraparound
try {
lfmgr.read(buffer, buffer.bsn+1);
} catch (IOException e) {
LogFile lf = lr.buffer.lf;
String msg = "Error reading " + lf.file + " @ position [" + lf.position + "]";
throw new LogException(msg, e);
}
if (buffer.bsn == -1 || buffer.bsn < bsn) // BUG 304982
{
lr.type = LogRecordType.END_OF_LOG;
return lr;
}
lr.get(buffer);
}
return lr;
}
/**
* return an XML node containing statistics for the Logger,
* the LogFile pool and the LogBuffer pool.
*
* <p>The getStats method for the LogBufferManager and LogFileManager
* are called to include statistics for these contained objects.
*
* @return String contiining XML node.
*/
public String getStats()
{
String name = this.getClass().getName();
StringBuffer stats = new StringBuffer(
"<Logger class='" + name + "'>"
);
// TODO: append Logger specific stats
stats.append(bmgr.getStats());
stats.append(lfmgr.getStats());
stats.append("\n</Logger>" +
"\n");
return stats.toString();
}
}
| 7,739 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/AriesTransactionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction;
import org.apache.geronimo.transaction.manager.MonitorableTransactionManager;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.XAWork;
import org.apache.geronimo.transaction.manager.XidImporter;
import javax.resource.spi.XATerminator;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
public interface AriesTransactionManager extends
TransactionManager, UserTransaction,
TransactionSynchronizationRegistry, XidImporter,
MonitorableTransactionManager, RecoverableTransactionManager,
XATerminator, XAWork {
}
| 7,740 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/XidFactoryImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.apache.geronimo.transaction.manager.XidImpl;
/**
* Factory for transaction ids that are ever increasing
* allowing determination of new transactions
* The Xid is constructed of two parts:
* <ol><li>8 byte id (LSB first)</li>
* <li>base id</li>
* <ol>
* can't easily extend geronimo XidFactoryImpl b/c count is private
*/
public class XidFactoryImpl implements XidFactory {
private final byte[] baseId = new byte[Xid.MAXGTRIDSIZE];
private final long start = System.currentTimeMillis();
private long count = start;
public XidFactoryImpl(byte[] tmId) {
System.arraycopy(tmId, 0, baseId, 8, tmId.length);
}
public Xid createXid() {
byte[] globalId = (byte[]) baseId.clone();
long id;
synchronized (this) {
id = count++;
}
insertLong(id, globalId, 0);
return new XidImpl(globalId);
}
public Xid createBranch(Xid globalId, int branch) {
byte[] branchId = (byte[]) baseId.clone();
branchId[0] = (byte) branch;
branchId[1] = (byte) (branch >>> 8);
branchId[2] = (byte) (branch >>> 16);
branchId[3] = (byte) (branch >>> 24);
insertLong(start, branchId, 4);
return new XidImpl(globalId, branchId);
}
public boolean matchesGlobalId(byte[] globalTransactionId) {
if (globalTransactionId.length != Xid.MAXGTRIDSIZE) {
return false;
}
for (int i = 8; i < globalTransactionId.length; i++) {
if (globalTransactionId[i] != baseId[i]) {
return false;
}
}
// for recovery, only match old transactions
long id = extractLong(globalTransactionId, 0);
return (id < start);
}
public boolean matchesBranchId(byte[] branchQualifier) {
if (branchQualifier.length != Xid.MAXBQUALSIZE) {
return false;
}
long id = extractLong(branchQualifier, 4);
if (id >= start) {
// newly created branch, not recoverable
return false;
}
for (int i = 12; i < branchQualifier.length; i++) {
if (branchQualifier[i] != baseId[i]) {
return false;
}
}
return true;
}
public Xid recover(int formatId, byte[] globalTransactionid, byte[] branchQualifier) {
return new XidImpl(formatId, globalTransactionid, branchQualifier);
}
static void insertLong(long value, byte[] bytes, int offset) {
bytes[offset + 0] = (byte) value;
bytes[offset + 1] = (byte) (value >>> 8);
bytes[offset + 2] = (byte) (value >>> 16);
bytes[offset + 3] = (byte) (value >>> 24);
bytes[offset + 4] = (byte) (value >>> 32);
bytes[offset + 5] = (byte) (value >>> 40);
bytes[offset + 6] = (byte) (value >>> 48);
bytes[offset + 7] = (byte) (value >>> 56);
}
static long extractLong(byte[] bytes, int offset) {
return (bytes[offset + 0] & 0xff)
+ (((bytes[offset + 1] & 0xff)) << 8)
+ (((bytes[offset + 2] & 0xff)) << 16)
+ (((bytes[offset + 3] & 0xffL)) << 24)
+ (((bytes[offset + 4] & 0xffL)) << 32)
+ (((bytes[offset + 5] & 0xffL)) << 40)
+ (((bytes[offset + 6] & 0xffL)) << 48)
+ (((long) bytes[offset + 7]) << 56);
}
}
| 7,741 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/AriesPlatformTransactionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.transaction.Transaction;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.xa.XAException;
import org.apache.geronimo.transaction.manager.TransactionLog;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.apache.geronimo.transaction.manager.TransactionManagerMonitor;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.jta.JtaTransactionManager;
/**
*/
public class AriesPlatformTransactionManager extends AriesTransactionManagerImpl implements PlatformTransactionManager {
private final PlatformTransactionManager platformTransactionManager;
private final Map<Transaction, SuspendedResourcesHolder> suspendedResources = new ConcurrentHashMap<Transaction, SuspendedResourcesHolder>();
public AriesPlatformTransactionManager() throws XAException {
platformTransactionManager = new JtaTransactionManager(this, this);
registerTransactionAssociationListener();
}
public AriesPlatformTransactionManager(int defaultTransactionTimeoutSeconds) throws XAException {
super(defaultTransactionTimeoutSeconds);
platformTransactionManager = new JtaTransactionManager(this, this);
registerTransactionAssociationListener();
}
public AriesPlatformTransactionManager(int defaultTransactionTimeoutSeconds, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, transactionLog);
platformTransactionManager = new JtaTransactionManager(this, this);
registerTransactionAssociationListener();
}
public AriesPlatformTransactionManager(int defaultTransactionTimeoutSeconds, XidFactory xidFactory, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, xidFactory, transactionLog);
platformTransactionManager = new JtaTransactionManager(this, this);
registerTransactionAssociationListener();
}
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
return platformTransactionManager.getTransaction(definition);
}
public void commit(TransactionStatus status) throws TransactionException {
platformTransactionManager.commit(status);
}
public void rollback(TransactionStatus status) throws TransactionException {
platformTransactionManager.rollback(status);
}
protected void registerTransactionAssociationListener() {
addTransactionAssociationListener(new TransactionManagerMonitor() {
public void threadAssociated(Transaction transaction) {
try {
if (transaction.getStatus() == Status.STATUS_ACTIVE) {
SuspendedResourcesHolder holder = suspendedResources.remove(transaction);
if (holder != null && holder.getSuspendedSynchronizations() != null) {
TransactionSynchronizationManager.setActualTransactionActive(true);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(holder.isReadOnly());
TransactionSynchronizationManager.setCurrentTransactionName(holder.getName());
TransactionSynchronizationManager.initSynchronization();
for (Iterator<?> it = holder.getSuspendedSynchronizations().iterator(); it.hasNext();) {
TransactionSynchronization synchronization = (TransactionSynchronization) it.next();
synchronization.resume();
TransactionSynchronizationManager.registerSynchronization(synchronization);
}
}
}
} catch (SystemException e) {
return;
}
}
public void threadUnassociated(Transaction transaction) {
try {
if (transaction.getStatus() == Status.STATUS_ACTIVE) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
List<?> suspendedSynchronizations = TransactionSynchronizationManager.getSynchronizations();
for (Iterator<?> it = suspendedSynchronizations.iterator(); it.hasNext();) {
((TransactionSynchronization) it.next()).suspend();
}
TransactionSynchronizationManager.clearSynchronization();
String name = TransactionSynchronizationManager.getCurrentTransactionName();
TransactionSynchronizationManager.setCurrentTransactionName(null);
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
TransactionSynchronizationManager.setActualTransactionActive(false);
SuspendedResourcesHolder holder = new SuspendedResourcesHolder(null, suspendedSynchronizations, name, readOnly);
suspendedResources.put(transaction, holder);
}
}
} catch (SystemException e) {
return;
}
}
});
}
/**
* Holder for suspended resources.
* Used internally by <code>suspend</code> and <code>resume</code>.
*/
private static class SuspendedResourcesHolder {
private final Object suspendedResources;
private final List<?> suspendedSynchronizations;
private final String name;
private final boolean readOnly;
public SuspendedResourcesHolder(
Object suspendedResources, List<?> suspendedSynchronizations, String name, boolean readOnly) {
this.suspendedResources = suspendedResources;
this.suspendedSynchronizations = suspendedSynchronizations;
this.name = name;
this.readOnly = readOnly;
}
@SuppressWarnings("unused")
public Object getSuspendedResources() {
return suspendedResources;
}
public List<?> getSuspendedSynchronizations() {
return suspendedSynchronizations;
}
public String getName() {
return name;
}
public boolean isReadOnly() {
return readOnly;
}
}
}
| 7,742 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/TransactionLogUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.geronimo.transaction.log.HOWLLog;
import org.apache.geronimo.transaction.manager.Recovery;
import org.apache.geronimo.transaction.manager.TransactionBranchInfo;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.objectweb.howl.log.LogRecordType;
import org.osgi.service.cm.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.aries.transaction.internal.TransactionManagerService.*;
public class TransactionLogUtils {
public static Logger log = LoggerFactory.getLogger(TransactionLogUtils.class);
private static Pattern TX_FILE_NAME = Pattern.compile("(.*)_([0-9]+)\\.([^.]+)");
/**
* <p>When <code>org.apache.aries.transaction</code> PID changes, there may be a need to copy
* entries from transaction log when some important configuration changed (like block size)</p>
* @param oldConfiguration previous configuration when configuration changed, may be <code>null</code> when starting bundle
* @param newConfiguration configuration to create new transaction manager
* @return <code>true</code> if there was conversion performed
*/
public static boolean copyActiveTransactions(Dictionary<String, Object> oldConfiguration, Dictionary<String, ?> newConfiguration)
throws ConfigurationException, IOException {
if (oldConfiguration == null) {
oldConfiguration = new Hashtable<String, Object>();
}
if (oldConfiguration.get(HOWL_LOG_FILE_DIR) == null) {
// we will be adjusting oldConfiguration to be able to create "old HOWLLog"
oldConfiguration.put(HOWL_LOG_FILE_DIR, newConfiguration.get(HOWL_LOG_FILE_DIR));
}
String oldLogDirectory = (String) oldConfiguration.get(HOWL_LOG_FILE_DIR);
String newLogDirectory = (String) newConfiguration.get(HOWL_LOG_FILE_DIR);
if (newLogDirectory == null || oldLogDirectory == null) {
// handle with exceptions at TM creation time
return false;
}
File oldDir = new File(oldLogDirectory);
oldLogDirectory = oldDir.getAbsolutePath();
File newDir = new File(newLogDirectory);
newLogDirectory = newDir.getAbsolutePath();
// a file which may tell us what's the previous configuation
File transaction_1 = null;
if (!oldDir.equals(newDir)) {
// recent logs are in oldDir, so even if newDir contains some logs, we will remove them
deleteDirectory(newDir);
transaction_1 = new File(oldDir, configuredTransactionLogName(oldConfiguration, 1));
} else {
// we may need to move oldDir to some temporary location, if the configuration is changed
// we'll then have to copy old tx log to new one
transaction_1 = new File(oldDir, configuredTransactionLogName(oldConfiguration, 1));
if (!transaction_1.exists() || transaction_1.length() == 0L) {
oldConfiguration.put(HOWL_LOG_FILE_NAME, getString(newConfiguration, HOWL_LOG_FILE_NAME, "transaction"));
oldConfiguration.put(HOWL_LOG_FILE_EXT, getString(newConfiguration, HOWL_LOG_FILE_EXT, "log"));
transaction_1 = new File(oldDir, configuredTransactionLogName(newConfiguration, 1));
}
}
if (!transaction_1.exists() || transaction_1.length() == 0L) {
// no need to copy anything
return false;
}
BaseTxLogConfig oldTxConfig = transactionLogFileConfig(transaction_1);
BaseTxLogConfig newTxConfig = transactionLogFileConfig(newConfiguration);
if (oldTxConfig == null || oldTxConfig.equals(newTxConfig)) {
// old log files compatible, but maybe we have to copy them
if (!oldDir.equals(newDir)) {
if (!oldDir.renameTo(newDir)) {
log.warn("Can't backup old transaction logs directory: {}", oldDir.getAbsolutePath());
return false;
}
}
// files are compatible - we'll check one more thing - name_N.extension
String oldName = configuredTransactionLogName(oldConfiguration, 1);
String newName = configuredTransactionLogName(newConfiguration, 1);
if (!oldName.equals(newName)) {
final Dictionary<String, Object> finalOldConfiguration = oldConfiguration;
final Dictionary<String, ?> finalNewConfiguration = newConfiguration;
final Map<String, String> changes = new HashMap<String, String>();
newDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
Matcher matcher = TX_FILE_NAME.matcher(name);
if (matcher.matches()) {
if (matcher.group(1).equals(getString(finalOldConfiguration, HOWL_LOG_FILE_NAME, "transaction"))
&& matcher.group(3).equals(getString(finalOldConfiguration, HOWL_LOG_FILE_EXT, "log"))) {
changes.put(name, String.format("%s_%d.%s",
getString(finalNewConfiguration, HOWL_LOG_FILE_NAME, "transaction"),
Integer.parseInt(matcher.group(2)),
getString(finalNewConfiguration, HOWL_LOG_FILE_EXT, "log")));
}
}
return false;
}
});
for (String old : changes.keySet()) {
new File(newDir, old).renameTo(new File(newDir, changes.get(old)));
}
return true;
}
return false;
}
File backupDir = null;
if (oldDir.equals(newDir)) {
// move old dir to backup dir
backupDir = new File(newLogDirectory + String.format("-%016x", System.currentTimeMillis()));
if (!oldDir.renameTo(backupDir)) {
log.warn("Can't backup old transaction logs directory: {}", oldDir.getAbsolutePath());
return false;
}
oldConfiguration = copy(oldConfiguration);
oldConfiguration.put(HOWL_LOG_FILE_DIR, backupDir.getAbsolutePath());
}
log.info("Copying transaction log from {} to {}", oldDir.getAbsolutePath(), newDir.getAbsolutePath());
oldConfiguration.put(RECOVERABLE, newConfiguration.get(RECOVERABLE));
oldConfiguration.put(HOWL_MAX_LOG_FILES, Integer.toString(oldTxConfig.maxLogFiles));
oldConfiguration.put(HOWL_MAX_BLOCKS_PER_FILE, Integer.toString(oldTxConfig.maxBlocksPerFile));
oldConfiguration.put(HOWL_BUFFER_SIZE, Integer.toString(oldTxConfig.bufferSizeKBytes));
String tmid1 = TransactionManagerService.getString(oldConfiguration, TMID, Activator.PID);
XidFactory xidFactory1 = new XidFactoryImpl(tmid1.substring(0, Math.min(tmid1.length(), 64)).getBytes());
String tmid2 = TransactionManagerService.getString(newConfiguration, TMID, Activator.PID);
XidFactory xidFactory2 = new XidFactoryImpl(tmid2.substring(0, Math.min(tmid2.length(), 64)).getBytes());
org.apache.geronimo.transaction.manager.TransactionLog oldLog = null;
org.apache.geronimo.transaction.manager.TransactionLog newLog = null;
try {
oldLog = TransactionManagerService.createTransactionLog(oldConfiguration, xidFactory1);
newLog = TransactionManagerService.createTransactionLog(newConfiguration, xidFactory2);
if (!(oldLog instanceof HOWLLog)) {
log.info("TransactionLog {} is not recoverable", oldLogDirectory);
return false;
}
if (!(newLog instanceof HOWLLog)) {
log.info("TransactionLog {} is not recoverable", newLogDirectory);
return false;
}
HOWLLog from = (HOWLLog) oldLog;
HOWLLog to = (HOWLLog) newLog;
Collection<Recovery.XidBranchesPair> pairs = from.recover(xidFactory1);
for (Recovery.XidBranchesPair xidBranchesPair : pairs) {
log.info("Copying active transaction with XID {}", xidBranchesPair.getXid());
for (TransactionBranchInfo branchInfo : xidBranchesPair.getBranches()) {
log.info("- Copying branch {} for resource {}", branchInfo.getBranchXid(), branchInfo.getResourceName());
}
to.prepare(xidBranchesPair.getXid(), new ArrayList<TransactionBranchInfo>(xidBranchesPair.getBranches()));
}
log.info("Migration of active transactions finished");
deleteDirectory(backupDir);
return !pairs.isEmpty();
} catch (Exception e) {
log.error("An exception occurred while trying to migrate transaction log after changing configuration.", e);
if (backupDir != null) {
deleteDirectory(newDir);
backupDir.renameTo(oldDir);
}
return false;
} finally {
try {
if (oldLog instanceof HOWLLog) {
((HOWLLog)oldLog).doStop();
}
if (newLog instanceof HOWLLog) {
((HOWLLog)newLog).doStop();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
/**
* Retrieves 3 important configuration parameters from single HOWL transaction log file
* @param txFile existing HOWL file
* @return
*/
private static BaseTxLogConfig transactionLogFileConfig(File txFile) throws IOException {
RandomAccessFile raf = new RandomAccessFile(txFile, "r");
FileChannel channel = raf.getChannel();
try {
ByteBuffer bb = ByteBuffer.wrap(new byte[1024]);
int read = channel.read(bb);
if (read < 0x47) { // enough data to have HOWL block header and FILE_HEADER record
return null;
}
bb.rewind();
if (bb.getInt() != 0x484f574c) { // HOWL
return null;
}
bb.getInt(); // BSN
int bufferSizeKBytes = bb.getInt() / 1024;
bb.getInt(); // size
bb.getInt(); // checksum
bb.getLong(); // timestamp
bb.getShort(); // 0x0d0a
if (bb.getShort() != LogRecordType.FILE_HEADER) {
return null;
}
bb.getShort(); // size
bb.getShort(); // size
bb.get(); // automark
bb.getLong(); // active mark
bb.getLong(); // log key
bb.getLong(); // timestamp
int maxLogFiles = bb.getInt();
int maxBlocksPerFile = bb.getInt();
if (maxBlocksPerFile == Integer.MAX_VALUE) {
maxBlocksPerFile = -1;
}
bb.getShort(); // 0x0d0a
return new BaseTxLogConfig(maxLogFiles, maxBlocksPerFile, bufferSizeKBytes);
} finally {
channel.close();
raf.close();
}
}
/**
* Retrieves 3 important configuration parameters from configuration
* @param configuration
* @return
*/
private static BaseTxLogConfig transactionLogFileConfig(Dictionary<String, ?> configuration) throws ConfigurationException {
BaseTxLogConfig result = new BaseTxLogConfig();
result.maxLogFiles = getInt(configuration, HOWL_MAX_LOG_FILES, 2);
result.maxBlocksPerFile = getInt(configuration, HOWL_MAX_BLOCKS_PER_FILE, -1);
result.bufferSizeKBytes = getInt(configuration, HOWL_BUFFER_SIZE, 4);
return result;
}
private static String configuredTransactionLogName(Dictionary<String, ?> configuration, int number) throws ConfigurationException {
String logFileName = getString(configuration, HOWL_LOG_FILE_NAME, "transaction");
String logFileExt = getString(configuration, HOWL_LOG_FILE_EXT, "log");
return String.format("%s_%d.%s", logFileName, number, logFileExt);
}
private static Dictionary<String, Object> copy(Dictionary<String, Object> configuration) {
Dictionary<String, Object> result = new Hashtable<String, Object>();
for (Enumeration<String> keys = configuration.keys(); keys.hasMoreElements(); ) {
String k = keys.nextElement();
result.put(k, configuration.get(k));
}
return result;
}
/**
* Recursively delete directory with content
* @param file
*/
private static boolean deleteDirectory(File file) {
if (file == null) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
deleteDirectory(f);
}
}
return file.delete();
} else {
if (!file.delete()) {
return false;
}
return true;
}
}
private static class BaseTxLogConfig {
public int maxLogFiles;
public int maxBlocksPerFile;
public int bufferSizeKBytes;
public BaseTxLogConfig() {
}
public BaseTxLogConfig(int maxLogFiles, int maxBlocksPerFile, int bufferSizeKBytes) {
this.maxLogFiles = maxLogFiles;
this.maxBlocksPerFile = maxBlocksPerFile;
this.bufferSizeKBytes = bufferSizeKBytes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseTxLogConfig that = (BaseTxLogConfig) o;
if (maxLogFiles != that.maxLogFiles) return false;
if (maxBlocksPerFile != that.maxBlocksPerFile) return false;
if (bufferSizeKBytes != that.bufferSizeKBytes) return false;
return true;
}
@Override
public int hashCode() {
int result = maxLogFiles;
result = 31 * result + maxBlocksPerFile;
result = 31 * result + bufferSizeKBytes;
return result;
}
}
}
| 7,743 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.aries.transaction.internal.TransactionManagerService.DEFAULT_RECOVERABLE;
import static org.apache.aries.transaction.internal.TransactionManagerService.RECOVERABLE;
/**
*/
public class Activator implements BundleActivator, ManagedService {
public static final String PID = "org.apache.aries.transaction";
private static final Logger log = LoggerFactory.getLogger(PID);
private BundleContext bundleContext;
private TransactionManagerService manager;
private Dictionary<String, ?> properties;
public void start(BundleContext bundleContext) throws Exception {
this.bundleContext = bundleContext;
// Make sure TransactionManager comes up even if no config admin is installed
Dictionary<String, Object> properties = getInitialConfig();
updated(properties);
bundleContext.registerService(ManagedService.class.getName(), this, getProps());
}
private Dictionary<String, Object> getInitialConfig() {
try {
ServiceReference<ConfigurationAdmin> ref = bundleContext.getServiceReference(ConfigurationAdmin.class);
if (ref != null) {
ConfigurationAdmin configurationAdmin = bundleContext.getService(ref);
if (configurationAdmin != null) {
try {
Configuration config = configurationAdmin.getConfiguration(PID);
return config.getProperties();
} finally {
bundleContext.ungetService(ref);
}
}
}
} catch (Exception e) {
// Ignore
}
return null;
}
private Dictionary<String, Object> getProps() {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, PID);
return props;
}
public void stop(BundleContext context) throws Exception {
deleted();
}
@SuppressWarnings("unchecked")
public synchronized void updated(Dictionary<String, ?> properties) throws ConfigurationException {
if (properties == null) {
properties = getProps();
}
if (!equals(this.properties, properties)) {
deleted();
// ARIES-1719 - copy tx log with different configuration
// we can move active transactions (LogRecordType.XACOMMIT without XADONE)
// to different tx log
try {
if (TransactionManagerService.getBool(properties, RECOVERABLE, DEFAULT_RECOVERABLE)) {
TransactionLogUtils.copyActiveTransactions((Dictionary<String, Object>) this.properties, properties);
}
} catch (IOException e) {
log.error("An exception occurred starting the transaction manager.", e);
}
this.properties = properties;
manager = new TransactionManagerService(PID, properties, bundleContext);
try {
manager.start();
} catch (Exception e) {
log.error("An exception occurred starting the transaction manager.", e);
}
}
}
private boolean equals(Dictionary<String, ?> d1, Dictionary<String, ?> d2) {
if (d1 == d2) {
return true;
} else if (d1 == null ^ d2 == null) {
return false;
} else if (d1.size() != d2.size()) {
return false;
} else {
for (Enumeration<String> e1 = d1.keys(); e1.hasMoreElements();) {
String key = e1.nextElement();
Object v1 = d1.get(key);
Object v2 = d2.get(key);
if (v1 != v2 && (v2 == null || !v2.equals(v1))) {
return false;
}
}
return true;
}
}
public synchronized void deleted() {
if (manager != null) {
try {
manager.close();
} catch (Exception e) {
log.error("An exception occurred stopping the transaction manager.", e);
} finally {
manager = null;
}
}
}
} | 7,744 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/AriesTransactionManagerImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.geronimo.transaction.manager.GeronimoTransactionManager;
import org.apache.geronimo.transaction.manager.TransactionLog;
import org.apache.geronimo.transaction.manager.XidFactory;
import javax.transaction.xa.XAException;
public class AriesTransactionManagerImpl extends GeronimoTransactionManager implements AriesTransactionManager {
public AriesTransactionManagerImpl() throws XAException {
}
public AriesTransactionManagerImpl(int defaultTransactionTimeoutSeconds) throws XAException {
super(defaultTransactionTimeoutSeconds);
}
public AriesTransactionManagerImpl(int defaultTransactionTimeoutSeconds, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, transactionLog);
}
public AriesTransactionManagerImpl(int defaultTransactionTimeoutSeconds, XidFactory xidFactory, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, xidFactory, transactionLog);
}
}
| 7,745 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction | Create_ds/aries/transaction/transaction-manager/src/main/java/org/apache/aries/transaction/internal/TransactionManagerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.transaction.internal;
import java.io.File;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import javax.transaction.xa.XAException;
import org.apache.aries.transaction.AriesTransactionManager;
import org.apache.geronimo.transaction.log.HOWLLog;
import org.apache.geronimo.transaction.log.UnrecoverableLog;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.TransactionLog;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
/**
*/
@SuppressWarnings("rawtypes")
public class TransactionManagerService {
public static final String TRANSACTION_TIMEOUT = "aries.transaction.timeout";
public static final String RECOVERABLE = "aries.transaction.recoverable";
public static final String TMID = "aries.transaction.tmid";
public static final String HOWL_BUFFER_CLASS_NAME = "aries.transaction.howl.bufferClassName";
public static final String HOWL_BUFFER_SIZE = "aries.transaction.howl.bufferSize";
public static final String HOWL_CHECKSUM_ENABLED = "aries.transaction.howl.checksumEnabled";
public static final String HOWL_ADLER32_CHECKSUM = "aries.transaction.howl.adler32Checksum";
public static final String HOWL_FLUSH_SLEEP_TIME = "aries.transaction.howl.flushSleepTime";
public static final String HOWL_LOG_FILE_EXT = "aries.transaction.howl.logFileExt";
public static final String HOWL_LOG_FILE_NAME = "aries.transaction.howl.logFileName";
public static final String HOWL_MAX_BLOCKS_PER_FILE = "aries.transaction.howl.maxBlocksPerFile";
public static final String HOWL_MAX_LOG_FILES = "aries.transaction.howl.maxLogFiles";
public static final String HOWL_MAX_BUFFERS = "aries.transaction.howl.maxBuffers";
public static final String HOWL_MIN_BUFFERS = "aries.transaction.howl.minBuffers";
public static final String HOWL_THREADS_WAITING_FORCE_THRESHOLD = "aries.transaction.howl.threadsWaitingForceThreshold";
public static final String HOWL_LOG_FILE_DIR = "aries.transaction.howl.logFileDir";
public static final String HOWL_FLUSH_PARTIAL_BUFFERS = "aries.transaction.flushPartialBuffers";
public static final int DEFAULT_TRANSACTION_TIMEOUT = 600; // 600 seconds -> 10 minutes
public static final boolean DEFAULT_RECOVERABLE = false; // not recoverable by default
private static final String PLATFORM_TRANSACTION_MANAGER_CLASS = "org.springframework.transaction.PlatformTransactionManager";
@SuppressWarnings("unused")
private final String pid;
private final Dictionary properties;
private final BundleContext bundleContext;
private boolean useSpring;
private AriesTransactionManagerImpl transactionManager;
private TransactionLog transactionLog;
private ServiceRegistration<?> serviceRegistration;
public TransactionManagerService(String pid, Dictionary properties, BundleContext bundleContext) throws ConfigurationException {
this.pid = pid;
this.properties = properties;
this.bundleContext = bundleContext;
// Transaction timeout
int transactionTimeout = getInt(this.properties, TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT);
if (transactionTimeout <= 0) {
throw new ConfigurationException(TRANSACTION_TIMEOUT, "The transaction timeout property must be greater than zero.");
}
final String tmid = getString(this.properties, TMID, pid);
// the max length of the factory should be 64
XidFactory xidFactory = new XidFactoryImpl(tmid.substring(0, Math.min(tmid.length(), 64)).getBytes());
// Transaction log
transactionLog = createTransactionLog(this.properties, xidFactory);
// Create transaction manager
try {
try {
transactionManager = new SpringTransactionManagerCreator().create(transactionTimeout, xidFactory, transactionLog);
useSpring = true;
} catch (NoClassDefFoundError e) {
transactionManager = new AriesTransactionManagerImpl(transactionTimeout, xidFactory, transactionLog);
}
} catch (XAException e) {
throw new RuntimeException("An exception occurred during transaction recovery.", e);
}
}
public void start() throws Exception {
List<String> clazzes = new ArrayList<String>();
clazzes.add(AriesTransactionManager.class.getName());
clazzes.add(TransactionManager.class.getName());
clazzes.add(TransactionSynchronizationRegistry.class.getName());
clazzes.add(UserTransaction.class.getName());
clazzes.add(RecoverableTransactionManager.class.getName());
if (useSpring) {
clazzes.add(PLATFORM_TRANSACTION_MANAGER_CLASS);
}
String[] ifar = clazzes.toArray(new String[clazzes.size()]);
serviceRegistration = bundleContext.registerService(ifar, transactionManager, null);
}
public void close() throws Exception {
if(serviceRegistration != null) {
try {
serviceRegistration.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
if (transactionLog instanceof HOWLLog) {
((HOWLLog) transactionLog).doStop();
}
}
static String getString(Dictionary properties, String property, String dflt) {
String value = (String) properties.get(property);
if (value != null) {
return value;
}
return dflt;
}
static int getInt(Dictionary properties, String property, int dflt) throws ConfigurationException {
String value = (String) properties.get(property);
if (value != null) {
try {
return Integer.parseInt(value);
} catch (Exception e) {
throw new ConfigurationException(property, "The property " + property + " should have an integer value, but the value " + value + " is not an integer.", e);
}
}
return dflt;
}
static boolean getBool(Dictionary properties, String property, boolean dflt) throws ConfigurationException {
String value = (String) properties.get(property);
if (value != null) {
try {
return Boolean.parseBoolean(value);
} catch (Exception e) {
throw new ConfigurationException(property, "The property " + property + " should have a boolean value, but the value " + value + " is not a boolean.", e);
}
}
return dflt;
}
static TransactionLog createTransactionLog(Dictionary properties, XidFactory xidFactory) throws ConfigurationException {
TransactionLog result = null;
if (getBool(properties, RECOVERABLE, DEFAULT_RECOVERABLE)) {
String bufferClassName = getString(properties, HOWL_BUFFER_CLASS_NAME, "org.objectweb.howl.log.BlockLogBuffer");
int bufferSizeKBytes = getInt(properties, HOWL_BUFFER_SIZE, 4);
if (bufferSizeKBytes < 1 || bufferSizeKBytes > 32) {
throw new ConfigurationException(HOWL_BUFFER_SIZE, "The buffer size must be between one and thirty-two.");
}
boolean checksumEnabled = getBool(properties, HOWL_CHECKSUM_ENABLED, true);
boolean adler32Checksum = getBool(properties, HOWL_ADLER32_CHECKSUM, true);
int flushSleepTimeMilliseconds = getInt(properties, HOWL_FLUSH_SLEEP_TIME, 50);
String logFileExt = getString(properties, HOWL_LOG_FILE_EXT, "log");
String logFileName = getString(properties, HOWL_LOG_FILE_NAME, "transaction");
int maxBlocksPerFile = getInt(properties, HOWL_MAX_BLOCKS_PER_FILE, -1);
int maxLogFiles = getInt(properties, HOWL_MAX_LOG_FILES, 2);
int minBuffers = getInt(properties, HOWL_MIN_BUFFERS, 4);
if (minBuffers < 0) {
throw new ConfigurationException(HOWL_MIN_BUFFERS, "The minimum number of buffers must be greater than zero.");
}
int maxBuffers = getInt(properties, HOWL_MAX_BUFFERS, 0);
if (maxBuffers > 0 && minBuffers < maxBuffers) {
throw new ConfigurationException(HOWL_MAX_BUFFERS, "The maximum number of buffers must be greater than the minimum number of buffers.");
}
int threadsWaitingForceThreshold = getInt(properties, HOWL_THREADS_WAITING_FORCE_THRESHOLD, -1);
boolean flushPartialBuffers = getBool(properties, HOWL_FLUSH_PARTIAL_BUFFERS, true);
String logFileDir = getString(properties, HOWL_LOG_FILE_DIR, null);
if (logFileDir == null || logFileDir.length() == 0 || !new File(logFileDir).isAbsolute()) {
throw new ConfigurationException(HOWL_LOG_FILE_DIR, "The log file directory must be set to an absolute directory.");
}
try {
result = new HOWLLog(bufferClassName,
bufferSizeKBytes,
checksumEnabled,
adler32Checksum,
flushSleepTimeMilliseconds,
logFileDir,
logFileExt,
logFileName,
maxBlocksPerFile,
maxBuffers,
maxLogFiles,
minBuffers,
threadsWaitingForceThreshold,
flushPartialBuffers,
xidFactory,
null);
((HOWLLog) result).doStart();
} catch (Exception e) {
// This should not really happen as we've checked properties earlier
throw new ConfigurationException(null, e.getMessage(), e);
}
} else {
result = new UnrecoverableLog();
}
return result;
}
/**
* We use an inner static class to decouple this class from the spring-tx classes
* in order to not have NoClassDefFoundError if those are not present.
*/
public static class SpringTransactionManagerCreator {
public AriesTransactionManagerImpl create(int defaultTransactionTimeoutSeconds, XidFactory xidFactory, TransactionLog transactionLog) throws XAException {
return new AriesPlatformTransactionManager(defaultTransactionTimeoutSeconds, xidFactory, transactionLog);
}
}
}
| 7,746 |
0 | Create_ds/aries/transaction/transaction-manager/src/main/java/javax/resource | Create_ds/aries/transaction/transaction-manager/src/main/java/javax/resource/spi/XATerminator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//
package javax.resource.spi;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
/**
* @version $Rev$ $Date$
*/
public interface XATerminator {
public void commit(Xid xid, boolean onePhase) throws XAException;
public void forget(Xid xid) throws XAException;
public int prepare(Xid xid) throws XAException;
public Xid[] recover(int flag) throws XAException;
public void rollback(Xid xid) throws XAException;
} | 7,747 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/mocks/BundleContextMock.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.mocks;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import junit.framework.AssertionFailedError;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.apache.aries.unittest.mocks.Skeleton;
/**
*
*/
/**
* This class is a partial implementation of BundleContext. Its main function
* is to provide a service registry implementation
*/
public class BundleContextMock
{
/** The service registry */
private static Map<String, List<ServiceData>> registry = new HashMap<String, List<ServiceData>>();
/** A list of bundles installed into the runtime */
private static List<Bundle> bundles = new ArrayList<Bundle>();
/** A list of service listeners */
private static List<ServiceListener> listeners = new ArrayList<ServiceListener>();
/** The next service id to be assigned */
private static long nextId = 0;
private static class MockServiceFactory implements ServiceFactory
{
private final Object service;
public MockServiceFactory(Object obj)
{
service = obj;
}
public Object getService(Bundle arg0, ServiceRegistration arg1)
{
return service;
}
public void ungetService(Bundle arg0, ServiceRegistration arg1, Object arg2)
{
}
}
private static class FilteredServiceListener implements ServiceListener
{
private Filter filter;
private final ServiceListener listener;
public FilteredServiceListener(String f, ServiceListener l)
{
listener = l;
if (f != null) {
try {
filter = FrameworkUtil.createFilter(f);
} catch (InvalidSyntaxException e) {
AssertionFailedError err = new AssertionFailedError("The filter " + f + " is invalid");
err.initCause(e);
throw err;
}
}
}
public void serviceChanged(ServiceEvent arg0)
{
if (matches(arg0)) listener.serviceChanged(arg0);
}
private boolean matches(ServiceEvent arg0)
{
if (filter == null) return true;
ServiceReference ref = arg0.getServiceReference();
if (Skeleton.isSkeleton(ref)) {
Object template = Skeleton.getSkeleton(ref).getTemplateObject();
if (template instanceof ServiceData) {
return filter.match(((ServiceData)template).getProperties());
}
}
return filter.match(ref);
}
@Override
public boolean equals(Object obj)
{
if (obj == null) return false;
else if (obj instanceof FilteredServiceListener) {
return listener.equals(((FilteredServiceListener)obj).listener);
}
return false;
}
@Override
public int hashCode()
{
return listener.hashCode();
}
}
/**
* This class represents the information registered about a service. It also
* implements part of the ServiceRegistration and ServiceReference interfaces.
*/
private class ServiceData implements Comparable<ServiceReference>
{
/** The service that was registered */
private ServiceFactory serviceImpl;
/** the service properties */
@SuppressWarnings("unused")
private final Hashtable<String, Object> serviceProps = new Hashtable<String, Object>();
/** The interfaces the service publishes with */
private String[] interfaceNames;
/** The bundle that defines this service */
private Bundle registeringBundle;
/**
* This method unregisters the service from the registry.
*/
public void unregister()
{
for (String interfaceName : interfaceNames) {
List<ServiceData> list = registry.get(interfaceName);
if (list != null) {
list.remove(this);
if (list.isEmpty()) {
registry.remove(interfaceName);
}
}
}
notifyAllListeners(ServiceEvent.UNREGISTERING);
registeringBundle = null;
}
/**
* This method is used to register the service data in the registry
*/
public void register()
{
for (String interfaceName : interfaceNames) {
List<ServiceData> list = registry.get(interfaceName);
if (list == null) {
list = new ArrayList<ServiceData>();
registry.put(interfaceName, list);
}
list.add(this);
}
notifyAllListeners(ServiceEvent.REGISTERED);
}
private void notifyAllListeners(int eventType) {
List<ServiceListener> copy = new ArrayList<ServiceListener>(listeners.size());
copy.addAll(listeners);
for(ServiceListener listener : copy) {
listener.serviceChanged(new ServiceEvent(eventType, Skeleton.newMock(this, ServiceReference.class)));
}
}
/**
* Change the service properties
* @param newProps
*/
public void setProperties(Dictionary<String,Object> newProps)
{
// make sure we don't overwrite framework properties
newProps.put(Constants.OBJECTCLASS, serviceProps.get(Constants.OBJECTCLASS));
newProps.put(Constants.SERVICE_ID, serviceProps.get(Constants.SERVICE_ID));
Enumeration<String> keys = newProps.keys();
serviceProps.clear();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
serviceProps.put(key, newProps.get(key));
}
notifyAllListeners(ServiceEvent.MODIFIED);
}
/**
* This implements the isAssignableTo method from ServiceReference.
*
* @param b
* @param className
* @return true if the referenced service can be assigned to the requested
* class name.
*/
public boolean isAssignableTo(Bundle b, String className)
{
boolean result = false;
for (String iName : interfaceNames)
{
result = iName.equals(className);
if (result) break;
}
return result;
}
/**
* Returns the requested service property.
* @param key the property to return.
* @return the property value.
*/
public Object getProperty(String key)
{
return serviceProps.get(key);
}
@Override
public boolean equals(Object o) {
if(o == null) return false;
if(o == this) return true;
if (o instanceof ServiceData) {
ServiceData other = (ServiceData) o;
return serviceImpl == other.serviceImpl;
}
return false;
}
@Override
public int hashCode()
{
return serviceImpl.hashCode();
}
/**
* @return the keys of all the service properties.
*/
public String[] getPropertyKeys()
{
Enumeration<String> e = serviceProps.keys();
String[] toReturn = new String[serviceProps.size()];
for(int i = 0 ; i < serviceProps.size(); i++)
toReturn[i] = e.nextElement();
return toReturn;
}
/**
* @return the bundle this service reference was registered against.
*/
public Bundle getBundle()
{
return registeringBundle;
}
/**
* @return a service reference for this service registration.
*/
public ServiceReference getReference()
{
return Skeleton.newMock(this, ServiceReference.class);
}
public Hashtable<String, Object> getProperties()
{
return new Hashtable<String, Object>(serviceProps);
}
/**
* Implement the standard behaviour of the registry
*/
public int compareTo(ServiceReference o) {
Integer rank = (Integer) serviceProps.get(Constants.SERVICE_RANKING);
if(rank == null)
rank = 0;
Integer otherRank = (Integer) o.getProperty(Constants.SERVICE_RANKING);
if(otherRank == null)
otherRank = 0;
//Higher rank = higher order
int result = rank.compareTo(otherRank);
if(result == 0) {
Long id = (Long) serviceProps.get(Constants.SERVICE_ID);
Long otherId = (Long) o.getProperty(Constants.SERVICE_ID);
//higher id = lower order
return otherId.compareTo(id);
}
return result;
}
}
/** The bundle associated with this bundle context */
private Bundle bundle;
/**
* Default constructor, widely used in the tests.
*/
public BundleContextMock()
{
bundle = Skeleton.newMock(new BundleMock("test." + new Random(System.currentTimeMillis()).nextInt(),
new Hashtable<Object, Object>()), Bundle.class);
}
/**
* Constructor used by BundleMock, it ensures the bundle and its context are wired together correctly.
*
* TODO We have to many Bundle mocks objects for a single OSGi bundle, we need to update this.
*
* @param b
*/
public BundleContextMock(Bundle b)
{
bundle = b;
}
/**
* This checks that we have at least one service with this interface name.
*
* @param interfaceName the name of the interface.
*/
public static void assertServiceExists(String interfaceName)
{
assertTrue("No service registered with interface " + interfaceName + ". Services found: " + registry.keySet(), registry.containsKey(interfaceName));
}
/**
* This checks that we have at no services with this interface name.
*
* @param interfaceName the name of the interface.
*/
public static void assertNoServiceExists(String interfaceName)
{
assertFalse("Services registered with interface " + interfaceName + ". Services found: " + registry.keySet(), registry.containsKey(interfaceName));
}
/**
* This implements the registerService method from BundleContext.
*
* @param interFace
* @param service
* @param properties
* @return the ServiceRegistration object for this service.
*/
public ServiceRegistration registerService(String interFace, final Object service, Dictionary<String, Object> properties)
{
// validate that the service implements interFace
try {
Class<?> clazz = Class.forName(interFace, false, service.getClass().getClassLoader());
if (!!!clazz.isInstance(service) && !!!(service instanceof ServiceFactory)) {
throw new AssertionFailedError("The service " + service + " does not implement " + interFace);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return registerService(new String[] {interFace}, service, properties);
}
/**
* This implements the registerService method from BundleContext.
*
* @param interfaces
* @param service
* @param properties
* @return the ServiceRegistration object for this service.
*/
public ServiceRegistration registerService(String[] interfaces, Object service, Dictionary<String, Object> properties)
{
if (properties == null) properties = new Hashtable<String, Object>();
ServiceData data = new ServiceData();
// cast the service to a service factory because in our framework we only ever register
// a service factory. If we every put a non-service factory object in that is a failure.
properties.put(Constants.OBJECTCLASS, interfaces);
properties.put(Constants.SERVICE_ID, nextId++);
if (service instanceof ServiceFactory) {
data.serviceImpl = (ServiceFactory)service;
} else {
data.serviceImpl = new MockServiceFactory(service);
}
data.interfaceNames = interfaces;
data.registeringBundle = bundle;
Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
data.serviceProps.put(key, properties.get(key));
}
data.register();
return Skeleton.newMock(data, ServiceRegistration.class);
}
/**
* This helper method is used to get the service from the registry with the
* given interface name.
*
* <p>This should really return multiple services.
* </p>
*
* @param interfaceName the interface name.
* @param bundle the bundle name.
* @return the registered service.
*/
public static Object getService(String interfaceName, Bundle bundle)
{
List<ServiceData> datum = registry.get(interfaceName);
if (datum == null) return null;
else if (datum.isEmpty()) return null;
// this is safe for now, but may not be when we do other scoped components.
else {
ServiceRegistration reg = Skeleton.newMock(ServiceRegistration.class);
return datum.iterator().next().serviceImpl.getService(bundle, reg);
}
}
/**
* A mock implementation of the getServiceReferences method. It does not currently
* process the filter, this is probably a bit hard, so we might cheat when we do.
*
* <p>Note this does not check that the service classes are visible to the
* caller as OSGi does. It is equivalent to getAllServiceReferences.
* </p>
*
* @param className the name of the class the lookup is for.
* @param filter
* @return an array of matching service references.
* @throws InvalidSyntaxException
*/
public ServiceReference[] getServiceReferences(String className, String filter) throws InvalidSyntaxException
{
List<ServiceData> data = new ArrayList<ServiceData>();
if (className != null) {
List<ServiceData> tmpData = registry.get(className);
if (tmpData != null) data.addAll(tmpData);
} else {
data = new ArrayList<ServiceData>();
for (List<ServiceData> value : registry.values())
data.addAll(value);
}
ServiceReference[] refs;
if (data == null) {
refs = null;
} else {
if (filter != null) {
Filter f = FrameworkUtil.createFilter(filter);
Iterator<ServiceData> it = data.iterator();
while (it.hasNext()) {
ServiceData sd = it.next();
if (!!!f.match(sd.getProperties())) it.remove();
}
}
if (data.isEmpty()) return null;
refs = new ServiceReference[data.size()];
for (int i = 0; i < refs.length; i++) {
refs[i] = Skeleton.newMock(data.get(i), ServiceReference.class);
}
}
return refs;
}
/**
* Gets the first matching service reference.
*
* @param className the class name wanted.
* @return the matchine service, or null if one cannot be found.
*/
public ServiceReference getServiceReference(String className)
{
ServiceReference[] refs;
try {
refs = getServiceReferences(className, null);
if (refs != null) return refs[0];
return null;
} catch (InvalidSyntaxException e) {
// should never happen.
e.printStackTrace();
}
return null;
}
/**
* This method finds all the service references in the registry with the
* matching class name and filter.
*
* @param className
* @param filter
* @return the matching service references.
* @throws InvalidSyntaxException
*/
public ServiceReference[] getAllServiceReferences(String className, String filter) throws InvalidSyntaxException
{
return getServiceReferences(className, filter);
}
/**
* Retrieve a service from the registry.
* @param ref the service reference.
* @return the returned service.
*/
public Object getService(ServiceReference ref)
{
ServiceData data = (ServiceData)Skeleton.getSkeleton(ref).getTemplateObject();
return data.serviceImpl.getService(getBundle(), Skeleton.newMock(data, ServiceRegistration.class));
}
/**
* This method implements the installBundle method from BundleContext. It
* makes use of the java.util.jar package to parse the manifest from the input
* stream.
*
* @param location the location of the bundle.
* @param is the input stream to read from.
* @return the created bundle.
* @throws BundleException
*/
public Bundle installBundle(String location, InputStream is) throws BundleException
{
Bundle b;
JarInputStream jis;
try {
jis = new JarInputStream(is);
Manifest man = jis.getManifest();
b = createBundle(man, null);
} catch (IOException e) {
throw new BundleException(e.getMessage(), e);
}
return b;
}
/**
* Create a mock bundle correctly configured using the supplied manifest and
* location.
*
* @param man the manifest to load.
* @param location the location on disk.
* @return the created bundle
* @throws MalformedURLException
*/
private Bundle createBundle(Manifest man, String location) throws MalformedURLException
{
Attributes attribs = man.getMainAttributes();
String symbolicName = attribs.getValue(Constants.BUNDLE_SYMBOLICNAME);
Hashtable<Object, Object> attribMap = new Hashtable<Object, Object>();
for (Map.Entry<Object, Object> entry : attribs.entrySet()) {
Attributes.Name name = (Attributes.Name)entry.getKey();
attribMap.put(name.toString(), entry.getValue());
}
BundleMock mock = new BundleMock(symbolicName, attribMap, location);
mock.addToClassPath(new File("build/unittest/classes").toURL());
Bundle b = Skeleton.newMock(mock, Bundle.class);
bundles.add(b);
return b;
}
/**
* Asks to install an OSGi bundle from the given location.
*
* @param location the location of the bundle on the file system.
* @return the installed bundle.
* @throws BundleException
*/
public Bundle installBundle(String location) throws BundleException
{
try {
URI uri = new URI(location.replaceAll(" ", "%20"));
File baseDir = new File(uri);
Manifest man = null;
//check if it is a directory
if (baseDir.isDirectory()){
man = new Manifest(new FileInputStream(new File(baseDir, "META-INF/MANIFEST.MF")));
}
//if it isn't assume it is a jar file
else{
InputStream is = new FileInputStream(baseDir);
JarInputStream jis = new JarInputStream(is);
man = jis.getManifest();
jis.close();
if (man == null){
throw new BundleException("Null manifest");
}
}
return createBundle(man, location);
} catch (IOException e) {
throw new BundleException(e.getMessage(), e);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
throw new BundleException(e.getMessage(), e);
}
}
/**
* @return all the bundles in the system
*/
public Bundle[] getBundles()
{
return bundles.toArray(new Bundle[bundles.size()]);
}
/**
* Add a service listener.
*
* @param listener
* @param filter
*/
public void addServiceListener(ServiceListener listener, String filter)
{
listeners.add(new FilteredServiceListener(filter, listener));
}
/**
* Add a service listener.
*
* @param listener
*/
public void addServiceListener(ServiceListener listener)
{
listeners.add(listener);
}
/**
* Remove a service listener
* @param listener
*/
public void removeServiceListener(ServiceListener listener)
{
listeners.remove(new FilteredServiceListener(null, listener));
}
public String getProperty(String name)
{
if (Constants.FRAMEWORK_VERSION.equals(name)) {
return "4.1";
}
/*added System.getProperty so that tests can set a system property
* but it is retrieved via the BundleContext.
* This allows tests to emulate different properties being set on the
* context, helpful for the feature pack launcher/kernel relationship
*/
return System.getProperty(name);
}
/**
* @return the bundle associated with this bundle context (if we created one).
*/
public Bundle getBundle()
{
return bundle;
}
/**
* This method clears the service registry.
*/
public static void clear()
{
registry.clear();
bundles.clear();
listeners.clear();
nextId = 0;
}
public static List<ServiceListener> getServiceListeners()
{
return listeners;
}
public void addBundle(Bundle b)
{
bundles.add(b);
}
} | 7,748 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/mocks/BundleMock.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.mocks;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.MethodCallHandler;
import org.apache.aries.unittest.mocks.Skeleton;
import org.apache.aries.unittest.mocks.annotations.Singleton;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
@Singleton
public class BundleMock
{
private final String symbolicName;
private final Dictionary<?, ?> headers;
private final BundleContext bc;
private String location;
private BundleClassLoader cl;
private class BundleClassLoader extends URLClassLoader implements BundleReference
{
List<Bundle> otherBundlesToCheck = new ArrayList<Bundle>();
public BundleClassLoader(URL[] urls)
{
super(urls);
}
public BundleClassLoader(URL[] urls, ClassLoader parent)
{
super(urls, parent);
}
public void addBundle(Bundle ... otherBundles)
{
otherBundlesToCheck.addAll(Arrays.asList(otherBundles));
}
public Bundle[] getBundles()
{
return otherBundlesToCheck.toArray(new Bundle[otherBundlesToCheck.size()]);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
Class<?> result = null;
for (Bundle b : otherBundlesToCheck) {
try {
result = b.loadClass(name);
} catch (ClassNotFoundException e) {
// do nothing here.
}
if (result != null) return result;
}
return super.findClass(name);
}
public Bundle getBundle()
{
return Skeleton.newMock(BundleMock.this, Bundle.class);
}
}
public BundleMock(String name, Dictionary<?, ?> bundleHeaders)
{
symbolicName = name;
headers = bundleHeaders;
bc = Skeleton.newMock(new BundleContextMock(Skeleton.newMock(this, Bundle.class)), BundleContext.class);
cl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() {
public BundleClassLoader run()
{
return new BundleClassLoader(new URL[0], this.getClass().getClassLoader());
}
});
}
public BundleMock(String name, Dictionary<?,?> bundleHeaders, boolean dummy)
{
this(name, bundleHeaders);
cl = null;
}
public BundleMock(String name, Dictionary<?, ?> bundleHeaders, String location)
{
this(name, bundleHeaders);
this.location = location;
if (location != null) {
String cp = (String)bundleHeaders.get(Constants.BUNDLE_CLASSPATH);
if (cp == null) cp = ".";
String[] cpEntries = cp.split(",");
final List<URL> urls = new ArrayList<URL>();
try {
for (String cpEntry : cpEntries) {
if (".".equals(cpEntry.trim())) {
urls.add(new URL(location));
} else {
urls.add(new URL(location + "/" + cpEntry));
}
}
cl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() {
public BundleClassLoader run()
{
return new BundleClassLoader(urls.toArray(new URL[urls.size()]));
}
});
} catch (MalformedURLException e) {
Error err = new AssertionFailedError("The location was not a valid url");
err.initCause(e);
throw err;
}
}
}
private static class PrivateDataFileHandler implements MethodCallHandler
{
private final File location;
public PrivateDataFileHandler(File f)
{
this.location = f;
}
public Object handle(MethodCall call, Skeleton parent)
{
File privateStorage = new File(location.getAbsolutePath(), "_private");
if (!!!privateStorage.exists())
privateStorage.mkdirs();
return new File(privateStorage, (String) call.getArguments()[0]);
}
}
public BundleMock(String name, Dictionary<?, ?> properties, File location) throws Exception
{
this(name,properties,location.toURL().toExternalForm());
Skeleton bcSkel = Skeleton.getSkeleton(bc);
bcSkel.registerMethodCallHandler(
new MethodCall(BundleContext.class,"getDataFile", new Object[] { String.class }),
new PrivateDataFileHandler(location)
);
}
public String getSymbolicName()
{
return symbolicName;
}
public Dictionary<?, ?> getHeaders()
{
return headers;
}
public Enumeration<URL> findEntries(String baseDir, String matchRule, boolean recurse)
{
System.err.println("findEntries: " + baseDir + ", " + matchRule + ", " + recurse);
File base;
try {
base = new File(new File(new URL(location.replaceAll(" ", "%20")).toURI()), baseDir);
System.err.println("Base dir: " + base);
} catch (Exception e) {
Error err = new AssertionFailedError("Unable to findEntries from " + location);
err.initCause(e);
throw err;
}
if (matchRule.equals("*.xml")) matchRule = ".*\\.xml";
else matchRule = matchRule.replaceAll("\\*", ".*");
System.err.println("matchrule: " + matchRule);
final Pattern p = Pattern.compile(matchRule);
File[] files = base.listFiles(new FileFilter(){
public boolean accept(File pathname)
{
return pathname.isFile() &&
p.matcher(pathname.getName()).matches();
}
});
Vector<URL> v = new Vector<URL>();
if (files != null) {
for (File f : files) {
try {
v.add(f.toURL());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
System.err.println("no matching files");
}
if (v.isEmpty()) {
return null;
} else {
System.err.println(v);
return v.elements();
}
}
public URL getResource(String name)
{
if (cl != null) return cl.getResource(name);
try {
File f = new File(name);
if(f.exists() || "Entities.jar".equals(name)) return f.toURL();
else return null;
} catch (MalformedURLException e) {
Error err = new AssertionFailedError("The resource " + name + " could not be found.");
err.initCause(e);
throw err;
}
}
public Enumeration<URL> getResources(String name)
{
if (cl != null)
{
try {
return cl.getResources(name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
final URL resource = getResource(name);
if(resource != null) {
return new Enumeration<URL>() {
boolean hasMore = true;
public boolean hasMoreElements()
{
return hasMore;
}
public URL nextElement()
{
hasMore = false;
return resource;
}
};
}
}
return new Enumeration<URL>(){
public URL nextElement()
{
return null;
}
public boolean hasMoreElements()
{
return false;
}
};
}
public Class<?> loadClass(String name) throws ClassNotFoundException
{
if (cl != null) return Class.forName(name, false, cl);
throw new ClassNotFoundException("Argh, things went horribly wrong trying to load " + name);
}
public String getLocation()
{
try {
return (location == null) ? new File(symbolicName + ".jar").toURL().toString() : location;
} catch (MalformedURLException e) {
Error err = new AssertionFailedError("We could not generate a valid url for the bundle");
err.initCause(e);
throw err;
}
}
public BundleContext getBundleContext()
{
return bc;
}
public Version getVersion()
{
String res = (String) headers.get("Bundle-Version");
if (res != null)
return new Version(res);
else
return new Version("0.0.0");
}
public int getState()
{
return Bundle.ACTIVE;
}
public void addToClassPath(URL ... urls)
{
if (cl != null) {
URL[] existingURLs = cl.getURLs();
final URL[] mergedURLs = new URL[urls.length + existingURLs.length];
int i = 0;
for (; i < existingURLs.length; i++) {
mergedURLs[i] = existingURLs[i];
}
for (int j = 0; j < urls.length; j++, i++) {
mergedURLs[i] = urls[j];
}
BundleClassLoader newCl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() {
public BundleClassLoader run()
{
return new BundleClassLoader(mergedURLs, cl.getParent());
}
});
newCl.addBundle(cl.getBundles());
cl = newCl;
}
}
public void addBundleToClassPath(Bundle ... bundles) {
if (cl != null) {
cl.addBundle(bundles);
}
}
public ClassLoader getClassLoader()
{
return cl;
}
// This is good enough for Mocks' needs in unit test, but isn't how it works in the real world!
public ServiceReference[] getRegisteredServices()
{
ServiceReference[] result = null;
try {
result = bc.getServiceReferences((String) null, null);
} catch (InvalidSyntaxException isx) {
// no-op: Swallow exception
}
return result;
}
} | 7,749 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/mocks/MockInitialContextFactoryBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.mocks;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import javax.naming.spi.NamingManager;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
public class MockInitialContextFactoryBuilder implements InitialContextFactoryBuilder
{
private static InitialContextFactory icf;
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment)
throws NamingException
{
return icf;
}
public static void start(Context ctx) throws NamingException
{
if (icf == null) {
NamingManager.setInitialContextFactoryBuilder(new MockInitialContextFactoryBuilder());
}
icf = Skeleton.newMock(InitialContextFactory.class);
getSkeleton().setReturnValue(new MethodCall(InitialContextFactory.class, "getInitialContext", Hashtable.class), ctx);
}
public static Skeleton getSkeleton()
{
return Skeleton.getSkeleton(icf);
}
} | 7,750 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/DefaultReturnTypeHandlers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <p>This class contains some return type handlers that provides some default behavior.</p>
*/
public class DefaultReturnTypeHandlers
{
/** A handler for Longs */
public static final ReturnTypeHandler LONG_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Long.valueOf(0);
}
};
/** A handler for Integers */
public static final ReturnTypeHandler INT_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Integer.valueOf(0);
}
};
/** A handler for Shorts */
public static final ReturnTypeHandler SHORT_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Short.valueOf((short)0);
}
};
/** A handler for Bytes */
public static final ReturnTypeHandler BYTE_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Byte.valueOf((byte)0);
}
};
/** A handler for Characters */
public static final ReturnTypeHandler CHAR_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Character.valueOf(' ');
}
};
/** A handler for Strings */
public static final ReturnTypeHandler STRING_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return "";
}
};
/** A handler for Lists */
public static final ReturnTypeHandler LIST_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return new ArrayList<Object>();
}
};
/** A handler for Maps */
public static final ReturnTypeHandler MAP_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return new HashMap<Object,Object>();
}
};
/** A handler for Setss */
public static final ReturnTypeHandler SET_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return new HashSet<Object>();
}
};
/** A handler for Floats */
public static final ReturnTypeHandler FLOAT_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return new Float(0.0f);
}
};
/** A handler for Doubles */
public static final ReturnTypeHandler DOUBLE_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return new Double(0.0d);
}
};
/** A handler for Booleans */
public static final ReturnTypeHandler BOOLEAN_HANDLER = new ReturnTypeHandler() {
public Object handle(Class<?> class1, Skeleton parent)
{
return Boolean.FALSE;
}
};
/**
* Register all the default handlers against the specified skeleton.
*
* @param s the skeleton
*/
public static void registerDefaultHandlers(Skeleton s)
{
s.registerReturnTypeHandler(Double.class, DOUBLE_HANDLER);
s.registerReturnTypeHandler(Float.class, FLOAT_HANDLER);
s.registerReturnTypeHandler(Long.class, LONG_HANDLER);
s.registerReturnTypeHandler(Integer.class, INT_HANDLER);
s.registerReturnTypeHandler(Short.class, SHORT_HANDLER);
s.registerReturnTypeHandler(Byte.class, BYTE_HANDLER);
s.registerReturnTypeHandler(Boolean.class, BOOLEAN_HANDLER);
s.registerReturnTypeHandler(Character.class, CHAR_HANDLER);
s.registerReturnTypeHandler(String.class, STRING_HANDLER);
s.registerReturnTypeHandler(List.class, LIST_HANDLER);
s.registerReturnTypeHandler(Map.class, MAP_HANDLER);
s.registerReturnTypeHandler(Set.class, SET_HANDLER);
s.registerReturnTypeHandler(double.class, DOUBLE_HANDLER);
s.registerReturnTypeHandler(float.class, FLOAT_HANDLER);
s.registerReturnTypeHandler(long.class, LONG_HANDLER);
s.registerReturnTypeHandler(int.class, INT_HANDLER);
s.registerReturnTypeHandler(short.class, SHORT_HANDLER);
s.registerReturnTypeHandler(byte.class, BYTE_HANDLER);
s.registerReturnTypeHandler(char.class, CHAR_HANDLER);
s.registerReturnTypeHandler(boolean.class, BOOLEAN_HANDLER);
}
} | 7,751 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/Skeleton.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.apache.aries.unittest.mocks.annotations.InjectSkeleton;
import org.apache.aries.unittest.mocks.annotations.Singleton;
/**
* <p>The Skeleton class is an implementation of the
* <code>java.lang.reflect.InvocationHandler</code> that can be used for
* dynamic mock objects.
* </p>
*
* <ol>
* <li>The static newMock methods can be used to create completely new mock
* objects backed by an entirely new skeleton.
* </li>
* <li>The static getSkeleton method can be used to obtain the skeleton
* backing a given mock.
* </li>
* <li>The createMock methods can be used to create a new mock object based on
* the skeleton that is invoked.
* </li>
* <li>The registerMethodCallHandler method can be used to register a handler
* that will be invoked when a method is called.
* </li>
* <li>The registerReturnTypeHandler method can be used to register a handler
* that will be invoked when a method with a specific return type is
* invoked. It should be noted that registered ReturnTypeHandlers will be
* invoked only if a method call handler has not been registered for the
* method that was invoked.
* </li>
* <li>The setReturnValue method can be used to set a value that will be
* returned when a method is invoked.
* </li>
* <li>The checkCalls methods can be used to determine if the methods in the
* list should have been called. They return a boolean to indicate if the
* expected calls occurred.
* </li>
* <li>The assertCalls method performs the same operation as the checkCalls,
* but throws an junit.framework.AssertionFailedError if the calls don't
* match. This intended for use within the junit test framework
* </li>
* <li>If no method call or return type handlers have been registered for a
* call then if the return type is an interface then a mock that implements
* that interface will be returned, otherwise null will be returned.
* </li>
* </ol>
*/
public final class Skeleton implements InvocationHandler
{
/** A list of calls made on this skeleton */
private List<MethodCall> _methodCalls;
/** The invocation handler to call after MethodCall and ReturnType handlers */
private DefaultInvocationHandler default_Handler;
/** The method call handlers */
private Map<MethodCall, MethodCallHandler> _callHandlers;
/** The type handlers */
private Map<Class<?>, ReturnTypeHandler> _typeHandlers;
/** The parameter map */
private Map<String, Object> _mockParameters;
/** A Map of mock objects to Maps of properties */
private Map<Object, Map<String, Object>> _objectProperties;
/** A Map of exception notification listeners */
private Map<Class<?>, List<ExceptionListener>> _notificationListeners;
/** The template class used to create this Skeleton, may be null */
private Object _template;
/** Cached template objects */
private static ConcurrentMap<Object, SoftReference<Object>> _singletonMocks = new ConcurrentHashMap<Object, SoftReference<Object>>();
// Constructors
/* ------------------------------------------------------------------------ */
/* Skeleton constructor
/* ------------------------------------------------------------------------ */
/**
* constructs the skeleton with the default method call handlers and the
* default return type handlers.
*/
private Skeleton()
{
reset();
}
// Static methods create methods
/* ------------------------------------------------------------------------ */
/* newMock method
/* ------------------------------------------------------------------------ */
/**
* This method returns a completely new mock object backed by a new skeleton
* object. It is equivalent to
* <code>new Skeleton().createMock(interfaceClazzes)</code>
*
* @param interfaceClazzes the classes the mock should implement
* @return the new mock object.
*/
public final static Object newMock(Class<?> ... interfaceClazzes)
{
return new Skeleton().createMock(interfaceClazzes);
}
/* ------------------------------------------------------------------------ */
/* newMock method
/* ------------------------------------------------------------------------ */
/**
* This method returns a completely new mock object backed by a new skeleton
* object. It is equivalent to
* <code>new Skeleton().createMock(interfaceClazzes)</code>
*
* @param <T> The object type.
* @param interfaceClazz the classes the mock should implement
* @return the new mock object.
*/
public final static <T> T newMock(Class<T> interfaceClazz)
{
return interfaceClazz.cast(new Skeleton().createMock(interfaceClazz));
}
/**
* It is often the case that only a subset of methods on an interface are needed, but
* those methods that are needed are quite complex. In this case a static mock forces
* you into implementing lots of methods you do not need, and produces problems when
* new methods are added to the interface being implemented. This method can essentially
* be used to complete the interface implementation. The object passed in is an instance
* of a class that implements a subset of the methods on the supplied interface. It does
* not need to implement the interface itself. The returned object will implement the full
* interface and delegate to the methods on the templateObject where necessary.
*
* @param <T> The object type.
* @param template The template object for the mock
* @param interfaceClazz The interface to implement
* @return An implementation of the interface that delegates (where appropraite) onto the template.
*/
public final static <T> T newMock(final Object template, Class<T> interfaceClazz)
{
Class<?> templateClass = template.getClass();
if (templateClass.getAnnotation(Singleton.class) != null) {
SoftReference<Object> mock = _singletonMocks.get(template);
if (mock != null) {
Object theMock = mock.get();
if (theMock == null) {
_singletonMocks.remove(template);
} else if (interfaceClazz.isInstance(theMock)) {
return interfaceClazz.cast(theMock);
}
}
}
Skeleton s = new Skeleton();
s._template = template;
for (Method m : interfaceClazz.getMethods()) {
try {
final Method m2 = templateClass.getMethod(m.getName(), m.getParameterTypes());
MethodCall mc = new MethodCall(interfaceClazz, m.getName(), (Object[])m.getParameterTypes());
s.registerMethodCallHandler(mc, new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
try {
m2.setAccessible(true);
return m2.invoke(template, methodCall.getArguments());
} catch (InvocationTargetException ite) {
if(ite.getTargetException() instanceof Exception)
throw (Exception)ite.getTargetException();
else throw new Exception(ite.getTargetException());
}
}
});
} catch (NoSuchMethodException e) {
// do nothing here, it is a method not on the interface so ignore it.
}
}
Field[] fs = template.getClass().getFields();
for (Field f : fs) {
InjectSkeleton sk = f.getAnnotation(InjectSkeleton.class);
if (sk != null) {
f.setAccessible(true);
try {
f.set(template, s);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Object o = s.createMock(interfaceClazz);
_singletonMocks.put(template, new SoftReference<Object>(o) {
@Override
public boolean enqueue()
{
_singletonMocks.remove(template);
System.out.println("Done cleanup");
return super.enqueue();
}
});
return interfaceClazz.cast(o);
}
// static mock query methods
/* ------------------------------------------------------------------------ */
/* getSkeleton method
/* ------------------------------------------------------------------------ */
/**
* This method returns the Skeleton backing the supplied mock object. If the
* supplied object is not a mock an IllegalArgumentException will be thrown.
*
* @param mock the mock object
* @return the skeleton backing the mock object
* @throws IllegalArgumentException thrown if the object is not a mock.
*/
public final static Skeleton getSkeleton(Object mock)
throws IllegalArgumentException
{
InvocationHandler ih = Proxy.getInvocationHandler(mock);
if (ih instanceof Skeleton)
{
return (Skeleton)ih;
}
throw new IllegalArgumentException("The supplied proxy (" + mock + ") was not an Aries dynamic mock ");
}
/* ------------------------------------------------------------------------ */
/* isSkeleton method
/* ------------------------------------------------------------------------ */
/**
* This method returns true if and only the provided object is backed by a
* Skeleton. Another way to think about this is if it returns true then a
* call to getSkeleton will not result in an IllegalArgumentException, and is
* guaranteed to return a Skeleton.
*
* @param mock the mock to test.
* @return true if it is backed by a skeleton.
*/
public final static boolean isSkeleton(Object mock)
{
if (Proxy.isProxyClass(mock.getClass())) {
InvocationHandler ih = Proxy.getInvocationHandler(mock);
return (ih instanceof Skeleton);
}
return false;
}
// InvocationHandler defined methods.
/* ------------------------------------------------------------------------ */
/* invoke method
/* ------------------------------------------------------------------------ */
/**
* This method is invoked by the mock objects. It constructs a MethodCall
* object representing the call and adds it to the list of calls that were
* made. (It should be noted that if the method is toString, hashCode or
* equals then they are not added to the list.) It then calls a registered
* MethodCallHandler, if a MethodCallHandler is not registered then a
* ReturnTypeHandler is invoked. If a ReturnTypeHandler is not invoked then
* the registered default InvocationHandler is called. By default the Skeleton
* is constructed with a DefaultInvocationHandler. If the invoked method has
* an interface as a return type then the DefaultInvocationHandler will return
* a new mock implementing that interface. If the return type is a class null
* will be returned.
*
* @param targetObject The mock object that was invoked.
* @param calledMethod The method that was called.
* @param arguments The arguments that were passed.
* @return The return of the method invoked.
* @throws Throwable Any exception thrown.
*/
public Object invoke(Object targetObject, Method calledMethod, Object[] arguments)
throws Throwable
{
String methodName = calledMethod.getName();
MethodCall call = new MethodCall(targetObject, methodName, arguments);
if (!DefaultMethodCallHandlers.isDefaultMethodCall(call))
{
_methodCalls.add(call);
}
Object result;
try
{
if (_callHandlers.containsKey(call))
{
MethodCallHandler handler = _callHandlers.get(call);
result = handler.handle(call, this);
}
else if (isReadWriteProperty(targetObject.getClass(), calledMethod))
{
String propertyName = methodName.substring(3);
if (methodName.startsWith("get") || methodName.startsWith("is"))
{
if (methodName.startsWith("is")) propertyName = methodName.substring(2);
Map<String, Object> properties = _objectProperties.get(targetObject);
if (properties == null)
{
properties = new HashMap<String, Object>();
_objectProperties.put(targetObject, properties);
}
if (properties.containsKey(propertyName))
{
result = properties.get(propertyName);
}
else if (_typeHandlers.containsKey(calledMethod.getReturnType()))
{
result = createReturnTypeProxy(calledMethod.getReturnType());
}
else
{
result = default_Handler.invoke(targetObject, calledMethod, arguments);
}
}
// Must be a setter.
else
{
Map<String, Object> properties = _objectProperties.get(targetObject);
if (properties == null)
{
properties = new HashMap<String, Object>();
_objectProperties.put(targetObject, properties);
}
properties.put(propertyName, arguments[0]);
result = null;
}
}
else if (_typeHandlers.containsKey(calledMethod.getReturnType()))
{
result = createReturnTypeProxy(calledMethod.getReturnType());
}
else
{
result = default_Handler.invoke(targetObject, calledMethod, arguments);
}
}
catch (Throwable t)
{
Class<?> throwableType = t.getClass();
List<ExceptionListener> listeners = _notificationListeners.get(throwableType);
if (listeners != null)
{
for (ExceptionListener listener : listeners)
{
listener.exceptionNotification(t);
}
}
throw t;
}
return result;
}
// MethodCall registration methods
/* ------------------------------------------------------------------------ */
/* registerMethodCallHandler method
/* ------------------------------------------------------------------------ */
/**
* This method registers a MethodCallHandler for the specified MethodCall.
*
* @param call The method that was called.
* @param handler The MethodCallHandler.
*/
public void registerMethodCallHandler(MethodCall call, MethodCallHandler handler)
{
deRegisterMethodCallHandler(call);
_callHandlers.put(call, handler);
}
/* ------------------------------------------------------------------------ */
/* deRegisterMethodCallHandler method
/* ------------------------------------------------------------------------ */
/**
* This method removes a registered MethodCallHandler for the specified
* MethodCall.
*
* @param call the specified MethodCall
*/
public void deRegisterMethodCallHandler(MethodCall call)
{
_callHandlers.remove(call);
}
/* ------------------------------------------------------------------------ */
/* reset method
/* ------------------------------------------------------------------------ */
/**
* This method resets the skeleton to the state it was in prior just after it
* was constructed.
*/
public void reset()
{
_methodCalls = new LinkedList<MethodCall>();
_callHandlers = new HashMap<MethodCall, MethodCallHandler>();
_typeHandlers = new HashMap<Class<?>, ReturnTypeHandler>();
DefaultReturnTypeHandlers.registerDefaultHandlers(this);
DefaultMethodCallHandlers.registerDefaultHandlers(this);
default_Handler = new DefaultInvocationHandler(this);
_mockParameters = new HashMap<String, Object>();
_objectProperties = new HashMap<Object, Map<String, Object>>();
_notificationListeners = new HashMap<Class<?>, List<ExceptionListener>>();
}
/* ------------------------------------------------------------------------ */
/* clearMethodCalls method
/* ------------------------------------------------------------------------ */
/**
* This method clears the method calls list for the skeleton
*/
public void clearMethodCalls()
{
_methodCalls = new LinkedList<MethodCall>();
}
/* ------------------------------------------------------------------------ */
/* setReturnValue method
/* ------------------------------------------------------------------------ */
/**
* This is a convenience method for registering a method call handler where
* a specific value should be returned when a method is called, rather than
* some logic needs to be applied. The value should be an object or the object
* version of the primitive for the methods return type, so if the method
* returns short the value must be an instance of java.lang.Short, not
* java.lang.Integer.
*
* @param call the method being called.
* @param value the value to be returned when that method is called.
*/
public void setReturnValue(MethodCall call, final Object value)
{
Class<?> clazz;
try {
clazz = Class.forName(call.getClassName());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("This should be impossible as we have already seen this class loaded");
}
Method[] methods = clazz.getMethods();
methods: for (Method m : methods) {
if(!!!m.getName().equals(call.getMethodName()))
continue methods;
Object[] args = call.getArguments();
Class<?>[] parms = m.getParameterTypes();
if (args.length == parms.length) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Class && args[i].equals(parms[i])) {
} else if (parms[i].isInstance(args[i])) {
} else {
continue methods;
}
}
Class<?> returnType = m.getReturnType();
if (returnType.isPrimitive()) {
if (returnType == boolean.class) returnType = Boolean.class;
else if (returnType == byte.class) returnType = Byte.class;
else if (returnType == short.class) returnType = Short.class;
else if (returnType == char.class) returnType = Character.class;
else if (returnType == int.class) returnType = Integer.class;
else if (returnType == long.class) returnType = Long.class;
else if (returnType == float.class) returnType = Float.class;
else if (returnType == double.class) returnType = Double.class;
}
if (value != null && !!!returnType.isInstance(value)) {
throw new IllegalArgumentException("The object cannot be returned by the requested method: " + call);
} else break methods;
}
}
registerMethodCallHandler(call, new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
return value;
}
});
}
/* ------------------------------------------------------------------------ */
/* setThrow method
/* ------------------------------------------------------------------------ */
/**
* This is a convenience method for registering a method call handler where
* a specific exception should be thrown when the method is called, rather
* than some logic needs to be applied.
*
* @param call the method being called
* @param thingToThrow the exception to throw.
*/
public void setThrows(MethodCall call, final Exception thingToThrow)
{
registerMethodCallHandler(call, new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
thingToThrow.fillInStackTrace();
throw thingToThrow;
}
});
}
/* ------------------------------------------------------------------------ */
/* setThrow method
/* ------------------------------------------------------------------------ */
/**
* This is a convenience method for registering a method call handler where
* a specific exception should be thrown when the method is called, rather
* than some logic needs to be applied.
*
* @param call the method being called
* @param thingToThrow the exception to throw.
*/
public void setThrows(MethodCall call, final Error thingToThrow)
{
registerMethodCallHandler(call, new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
thingToThrow.fillInStackTrace();
throw thingToThrow;
}
});
}
// ReturnType registration methods
/* ------------------------------------------------------------------------ */
/* registerReturnTypeHandler method
/* ------------------------------------------------------------------------ */
/**
* This method registers a ReturnTypeHandler for the specified class.
*
* @param clazz The class to be handled.
* @param handler The ReturnTypeHandler
*/
public void registerReturnTypeHandler(Class<?> clazz, ReturnTypeHandler handler)
{
deRegisterReturnTypeHandler(clazz);
_typeHandlers.put(clazz, handler);
}
/* ------------------------------------------------------------------------ */
/* deRegisterReturnTypeHandler method
/* ------------------------------------------------------------------------ */
/**
* This method removes a registration for a ReturnTypeHandler for the
* specified class.
*
* @param clazz The class to deregister the handler for.
*/
public void deRegisterReturnTypeHandler(Class<?> clazz)
{
_typeHandlers.remove(clazz);
}
// Exception notification methods
/* ------------------------------------------------------------------------ */
/* registerExceptionListener method
/* ------------------------------------------------------------------------ */
/**
* This method registers an ExceptionListener when the specified Exception is
* thrown.
*
* @param throwableType The type of the Throwable
* @param listener The listener.
*/
public void registerExceptionListener(Class<?> throwableType, ExceptionListener listener)
{
List<ExceptionListener> l = _notificationListeners.get(throwableType);
if (l == null)
{
l = new ArrayList<ExceptionListener>();
_notificationListeners.put(throwableType, l);
}
l.add(listener);
}
// parameter related methods
/* ------------------------------------------------------------------------ */
/* setParameter method
/* ------------------------------------------------------------------------ */
/**
* This method allows a parameter to be set. It is intended to be used by
* MethodCallHandlers and ReturnTypeHandlers.
*
* @param key The key
* @param value The value
*/
public void setParameter(String key, Object value)
{
_mockParameters.put(key, value);
}
/* ------------------------------------------------------------------------ */
/* getParameter method
/* ------------------------------------------------------------------------ */
/**
* This method allows a parameter to be retrieved.
*
* @param key the key the parameter was set using
* @return the parameter
*/
public Object getParameter(String key)
{
return _mockParameters.get(key);
}
/* ------------------------------------------------------------------------ */
/* getTemplateObject method
/* ------------------------------------------------------------------------ */
/**
* @return the template object, if one was used when initializing this skeleton.
*/
public Object getTemplateObject()
{
return _template;
}
// default InvocationHandler related methods
/**
* @param defaultHandler The defaultHandler to set.
*/
public void setDefaultHandler(DefaultInvocationHandler defaultHandler)
{
this.default_Handler = defaultHandler;
}
// MethodCall list check methods
/* ------------------------------------------------------------------------ */
/* checkCalls method
/* ------------------------------------------------------------------------ */
/**
* This method checks that the calls in the list occurred. If the addCalls
* boolean is true then their must be an exact match. If the allCalls boolean
* is false then the calls in the list must occur in that order, but other
* calls can be in between.
*
* @param calls The expected calls list
* @param allCalls true if an exact match comparison should be performed
* @return true if they the expected calls match.
*/
public boolean checkCalls(List<MethodCall> calls, boolean allCalls)
{
boolean found = false;
if (allCalls)
{
return calls.equals(_methodCalls);
}
else
{
Iterator<MethodCall> actual = _methodCalls.iterator();
for (MethodCall expectedCall : calls)
{
found = false;
actual: while (actual.hasNext())
{
MethodCall actualCall = actual.next();
if (actualCall.equals(expectedCall))
{
found = true;
break actual;
}
}
}
}
return found;
}
/* ------------------------------------------------------------------------ */
/* checkCall method
/* ------------------------------------------------------------------------ */
/**
* Checks that the specified method has been called on this skeleton
*
* @param call the call that should have been called.
* @return true if the MethodCall occurs in the list.
*/
public boolean checkCall(MethodCall call)
{
return this._methodCalls.contains(call);
}
// MethodCall list assert methods
/* ------------------------------------------------------------------------ */
/* assertCalls method
/* ------------------------------------------------------------------------ */
/**
* This method checks that the MethodCalls objects in the given list were
* made and throws an AssertionFailedError if they were not. If allCalls is
* true the given list and the calls list must be identical. If allCalls is
* false other calls could have been made on the skeleton in between ones
* specified in the list.
*
* @param calls the list of calls
* @param allCalls whether an exact match between the lists is required
* @throws AssertionFailedError if a failure has occurred.
*/
public void assertCalled(List<MethodCall> calls, boolean allCalls) throws AssertionFailedError
{
if (allCalls)
{
if ((calls == null) && (_methodCalls == null)) return;
if (calls == null)
{
throw new AssertionFailedError("expected null, but was " + _methodCalls);
}
if (_methodCalls == null)
{
throw new AssertionFailedError("expected:" + calls + " but was null");
}
if (calls.equals(_methodCalls)) return;
// OK compare lists and decide on differences - initially all the lists are different
int startOfDifferences = 0;
// Remove the common start of sequence
boolean lastItemSame = true;
for (int i = 0; i < calls.size() && i < _methodCalls.size() && lastItemSame; i++)
{
if ((calls.get(i) == null) && (_methodCalls.get(i) == null))
{
lastItemSame = true;
}
else if ((calls.get(i) == null) || (_methodCalls.get(i) == null))
{
lastItemSame = false;
}
else
{
lastItemSame = calls.get(i).equals(_methodCalls.get(i));
}
if (lastItemSame) startOfDifferences++;
}//for
// Now remove the common bit at the end
int endOfDifferencesInExpected = calls.size();
int endOfDifferencesInReceived = _methodCalls.size();
lastItemSame = true;
while ((endOfDifferencesInExpected > startOfDifferences)
&& (endOfDifferencesInReceived > startOfDifferences)
&& lastItemSame)
{
int ap = endOfDifferencesInExpected - 1;
int bp = endOfDifferencesInReceived - 1;
if ((calls.get(ap) == null) && (_methodCalls.get(bp) == null))
{
lastItemSame = true;
}
else if ((calls.get(ap) == null) || (_methodCalls.get(bp) == null))
{
lastItemSame = false;
}
else
{
lastItemSame = calls.get(ap).equals(_methodCalls.get(bp));
}
if (lastItemSame)
{
endOfDifferencesInExpected--;
endOfDifferencesInReceived--;
}
}//while
String failureText;
// OK, now build the failureText
if (endOfDifferencesInExpected == startOfDifferences)
{
failureText =
"Expected calls and actual calls differed because "
+ _methodCalls.subList(startOfDifferences, endOfDifferencesInReceived)
+ " inserted after element "
+ startOfDifferences;
}
else if (endOfDifferencesInReceived == startOfDifferences)
{
failureText =
"Expected calls and actual calls differed because "
+ calls.subList(startOfDifferences, endOfDifferencesInExpected)
+ " missing after element "
+ startOfDifferences;
}
else
{
if ((endOfDifferencesInExpected == startOfDifferences + 1)
&& (endOfDifferencesInReceived == startOfDifferences + 1))
{
failureText =
"Expected calls and actual calls differed because element "
+ startOfDifferences
+ " is different (calls:"
+ calls.get(startOfDifferences)
+ " but was:"+_methodCalls.get(startOfDifferences)+") ";
}
else if (endOfDifferencesInExpected == startOfDifferences + 1)
{
failureText =
"Expected calls and actual calls differed because element "
+ startOfDifferences
+ " ("
+ calls.get(startOfDifferences)
+ ") has been replaced by "
+ _methodCalls.subList(startOfDifferences, endOfDifferencesInReceived);
}
else
{
failureText =
"Expected calls and actual calls differed because elements between "
+ startOfDifferences
+ " and "
+ (endOfDifferencesInExpected - 1)
+ " are different (expected:"
+ calls.subList(startOfDifferences, endOfDifferencesInExpected)
+ " but was:"
+ _methodCalls.subList(startOfDifferences, endOfDifferencesInReceived)
+ ")";
}//if
}//if
throw new AssertionFailedError(failureText + " expected:" + calls + " but was:" + _methodCalls);
}
else
{
Iterator<MethodCall> expected = calls.iterator();
Iterator<MethodCall> actual = _methodCalls.iterator();
while (expected.hasNext())
{
boolean found = false;
MethodCall expectedCall = expected.next();
MethodCall actualCall = null;
actual: while (actual.hasNext())
{
actualCall = actual.next();
if (actualCall.equals(expectedCall))
{
found = true;
break actual;
}
}
if (!found)
{
throw new AssertionFailedError( "The method call " +
expectedCall +
" was expected but has not occurred (actual calls = "+_methodCalls+")");
}
}
}
}
/* ------------------------------------------------------------------------ */
/* assertCall method
/* ------------------------------------------------------------------------ */
/**
* This does the same as checkCall, but throws an
* junit.framework.AssertionFailedError if the call did not occur.
*
* @param call the call that was expected
*/
public void assertCalled(MethodCall call)
{
if (!checkCall(call))
{
throw new AssertionFailedError("The method call " +
call +
" was expected but has not occurred. Actual calls: " + getMethodCallsAsString());
}
}
/* ------------------------------------------------------------------------ */
/* assertCalledExactNumberOfTimes method
/* ------------------------------------------------------------------------ */
/**
* This method asserts that the method specified in the call parameter has
* been called the number of times specified by numberOfCalls. If
* numberOfCalls is zero this method is equivalent to assertNotCalled.
*
* @param call The call that was made.
* @param numberOfCalls The number of times the call should have been made.
*/
public void assertCalledExactNumberOfTimes(MethodCall call, int numberOfCalls)
{
int callCount = 0;
for (MethodCall callMade : _methodCalls)
{
if (callMade.equals(call))
{
callCount++;
}
}
if (numberOfCalls != callCount)
{
throw new AssertionFailedError("The method call " + call +
" should have been called " + numberOfCalls +
" time(s), but was called " + callCount + " time(s)");
}
}
/* ------------------------------------------------------------------------ */
/* assertNotCalled method
/* ------------------------------------------------------------------------ */
/**
* This method throws an junit.framework.AssertionFailedError if the specified
* call was invoked on the skeleton.
*
* @param call the call to check.
*/
public void assertNotCalled(MethodCall call)
{
Assert.assertFalse( "The method call " +
call +
" occurred in the skeleton " +
this.toString(), checkCall(call));
}
/* ------------------------------------------------------------------------ */
/* assertMockNotCalled method
/* ------------------------------------------------------------------------ */
/**
* This method throws an junit.framework.AssertionFailedError if the skeleton
* has had any methods invoked on it.
*/
public void assertSkeletonNotCalled()
{
Assert.assertEquals("The skeleton " + this.toString() +
" has had the following method invoked on it " + getMethodCallsAsString(),
0, _methodCalls.size());
}
// Instance mock creation methods
/* ------------------------------------------------------------------------ */
/* createMock method
/* ------------------------------------------------------------------------ */
/**
* Creates a new Mock using this skeleton backing it.
*
* @param interfaceClasses an array of interface the mock should implement.
* @return the mock
*/
public Object createMock(Class<?> ... interfaceClasses)
{
ClassLoader cl;
if (interfaceClasses.length > 0) cl = interfaceClasses[0].getClassLoader();
else cl = Thread.currentThread().getContextClassLoader();
return Proxy.newProxyInstance(cl, interfaceClasses, this);
}
/* ------------------------------------------------------------------------ */
/* createMock method
/* ------------------------------------------------------------------------ */
/**
* Creates a new Mock using this skeleton backing it.
*
* @param <T> The object type
* @param interfaceClass an array of interface the mock should implement.
* @return the mock
*/
public <T> T createMock(Class<T> interfaceClass)
{
return interfaceClass.cast(Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] {interfaceClass}, this));
}
/* ------------------------------------------------------------------------ */
/* invokeReturnTypeHandlers method
/* ------------------------------------------------------------------------ */
/**
* This method invokes the return type proxy for the specified class. If a
* ReturnTypeHandler for that type has not been registered then if the class
* represents an interface a new mock will be returned, backed by this
* skeleton, otherwise null will be returned.
*
* @param type the type to be invoked.
* @return the returned object.
* @throws Exception if an error occurs when invoking the return type handler.
*/
public Object invokeReturnTypeHandlers(Class<?> type) throws Exception
{
if (_typeHandlers.containsKey(type))
{
ReturnTypeHandler rth = _typeHandlers.get(type);
return rth.handle(type, this);
}
else if (type.isInterface())
{
return createMock(type);
}
else
{
return null;
}
}
// Miscellaneous methods that have been deprecated and will be removed.
/* ------------------------------------------------------------------------ */
/* createReturnTypeProxy method
/* ------------------------------------------------------------------------ */
/**
* create a proxy for given return type.
*
* @deprecated use invokeReturnTypeHandlers instead
*
* @param type The return type for which a handler is required
* @return ReturnTypeHandler The return type handler
* @throws Exception Thrown if an exception occurs.
*/
/* ------------------------------------------------------------------------ */
@Deprecated
private final Object createReturnTypeProxy(Class<?> type) throws Exception
{
return invokeReturnTypeHandlers(type);
}
/* ------------------------------------------------------------------------ */
/* isReadWriteProperty method
/* ------------------------------------------------------------------------ */
/**
* This method returns true if the method passed a getter for a read write
* java bean property. This is worked out by checking that a setter and getter
* exist for the property and that the setter and getter take and return
* exactly the same time.
*
* @param objClass The object the read write method has been invoked on.
* @param method The method to be checked.
* @return true if it is a getter or setter for a read write property.
*/
private boolean isReadWriteProperty(Class<?> objClass, Method method)
{
String methodName = method.getName();
String propertyName = methodName.substring(3);
Class<?>[] parameters = method.getParameterTypes();
Class<?> clazz;
boolean result = false;
if (methodName.startsWith("get") && parameters.length == 0)
{
clazz = method.getReturnType();
try
{
objClass.getMethod("set" + propertyName, clazz);
result = true;
}
catch (NoSuchMethodException e)
{
if (isPrimitive(clazz))
{
clazz = getOtherForm(clazz);
try
{
objClass.getMethod("set" + propertyName, clazz);
result = true;
}
catch (NoSuchMethodException e1)
{
}
}
}
}
else if (methodName.startsWith("is") && parameters.length == 0)
{
clazz = method.getReturnType();
if (clazz.equals(Boolean.class) || clazz.equals(boolean.class))
{
propertyName = methodName.substring(2);
try
{
objClass.getMethod("set" + propertyName, clazz);
result = true;
}
catch (NoSuchMethodException e)
{
if (isPrimitive(clazz))
{
clazz = getOtherForm(clazz);
try
{
objClass.getMethod("set" + propertyName, clazz);
result = true;
}
catch (NoSuchMethodException e1)
{
}
}
}
}
}
else if (methodName.startsWith("set") && parameters.length == 1)
{
clazz = parameters[0];
try
{
Method getter = objClass.getMethod("get" + propertyName, new Class[0]);
result = checkClasses(getter.getReturnType(), clazz);
}
catch (NoSuchMethodException e)
{
if (isPrimitive(clazz))
{
clazz = getOtherForm(clazz);
try
{
Method getter = objClass.getMethod("get" + propertyName, new Class[0]);
result = checkClasses(getter.getReturnType(), clazz);
}
catch (NoSuchMethodException e1)
{
if (clazz.equals(Boolean.class) || clazz.equals(boolean.class))
{
try
{
Method getter = objClass.getMethod("is" + propertyName, new Class[0]);
result = checkClasses(getter.getReturnType(), clazz);
}
catch (NoSuchMethodException e2)
{
clazz = getOtherForm(clazz);
try
{
Method getter = objClass.getMethod("is" + propertyName, new Class[0]);
result = checkClasses(getter.getReturnType(), clazz);
}
catch (NoSuchMethodException e3)
{
}
}
}
}
}
}
}
return result;
}
/* ------------------------------------------------------------------------ */
/* isPrimitive method
/* ------------------------------------------------------------------------ */
/**
* This method returns true if the class object represents a primitive or the
* object version of a primitive.
*
* @param clazz The class to be checked.
* @return true if it is a primitive or a wrapper.
*/
private boolean isPrimitive(Class<?> clazz)
{
boolean result = false;
if (clazz.isPrimitive())
{
result = true;
}
else
{
result = clazz.equals(Boolean.class) || clazz.equals(Byte.class) ||
clazz.equals(Short.class) || clazz.equals(Character.class) ||
clazz.equals(Integer.class) || clazz.equals(Long.class) ||
clazz.equals(Float.class) || clazz.equals(Double.class);
}
return result;
}
/* ------------------------------------------------------------------------ */
/* getOtherForm method
/* ------------------------------------------------------------------------ */
/**
* This method takes a class representing either a primitive or an object
* wrapper. If the class is a primitive type the object wrapper class is
* returned. If the class is an object wrapper class the primitive type is
* returned.
*
* @param clazz
* @return the class representing the primitive object wrapper.
*/
private Class<?> getOtherForm(Class<?> clazz)
{
Class<?> result = null;
if (clazz.equals(boolean.class)) result = Boolean.class;
else if (clazz.equals(byte.class)) result = Byte.class;
else if (clazz.equals(short.class)) result = Short.class;
else if (clazz.equals(char.class)) result = Character.class;
else if (clazz.equals(int.class)) result = Integer.class;
else if (clazz.equals(long.class)) result = Long.class;
else if (clazz.equals(float.class)) result = Float.class;
else if (clazz.equals(double.class)) result = Double.class;
else if (clazz.equals(Boolean.class)) result = boolean.class;
else if (clazz.equals(Byte.class)) result = byte.class;
else if (clazz.equals(Short.class)) result = short.class;
else if (clazz.equals(Character.class)) result = char.class;
else if (clazz.equals(Integer.class)) result = int.class;
else if (clazz.equals(Long.class)) result = long.class;
else if (clazz.equals(Float.class)) result = float.class;
else if (clazz.equals(Double.class)) result = double.class;
return result;
}
/* ------------------------------------------------------------------------ */
/* checkClasses method
/* ------------------------------------------------------------------------ */
/**
* This method returns true if the two classes are the same or if one is
* primitive that the other is a primitive wrapper.
*
* @param type1
* @param type2
* @return true if the classes are compatible.
*/
private boolean checkClasses(Class<?> type1, Class<?> type2)
{
boolean result = false;
if ((type1.isPrimitive() && type2.isPrimitive()) ||
(!type1.isPrimitive() && !type2.isPrimitive()))
{
result = type1.equals(type2);
}
else
{
result = (type1.equals(boolean.class) && type2.equals(Boolean.class)) ||
(type1.equals(byte.class) && type2.equals(Byte.class)) ||
(type1.equals(short.class) && type2.equals(Short.class)) ||
(type1.equals(char.class) && type2.equals(Character.class)) ||
(type1.equals(int.class) && type2.equals(Integer.class)) ||
(type1.equals(long.class) && type2.equals(Long.class)) ||
(type1.equals(float.class) && type2.equals(Float.class)) ||
(type1.equals(double.class) && type2.equals(Double.class)) ||
(type2.equals(boolean.class) && type1.equals(Boolean.class)) ||
(type2.equals(byte.class) && type1.equals(Byte.class)) ||
(type2.equals(short.class) && type1.equals(Short.class)) ||
(type2.equals(char.class) && type1.equals(Character.class)) ||
(type2.equals(int.class) && type1.equals(Integer.class)) ||
(type2.equals(long.class) && type1.equals(Long.class)) ||
(type2.equals(float.class) && type1.equals(Float.class)) ||
(type2.equals(double.class) && type1.equals(Double.class));
}
return result;
}
/* ------------------------------------------------------------------------ */
/* getMethodCallsAsString method
/* ------------------------------------------------------------------------ */
/**
* This method builds a String that contains the method calls that have been
* made on this skeleton. It puts each call on a separate line.
*
* @return the string representation of the method call.
*/
private String getMethodCallsAsString()
{
StringBuilder builder = new StringBuilder();
for (MethodCall call : _methodCalls)
{
builder.append(call);
builder.append("\r\n");
}
return builder.toString();
}
}
| 7,752 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/DefaultMethodCallHandlers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
/**
* <p>This class contains method call handlers for some default method handling.
* </p>
*
* <p>This class provides handlers for the toString, equals and hashCode
* methods. They reproduce the default Object implementations for dynamic
* mock objects, these can be overridden.
* </p>
*/
public class DefaultMethodCallHandlers
{
/** A MethodCall representing the equals method */
private static MethodCall _equals;
/** A MethodCall representing the toString method */
private static MethodCall _toString;
/** A MethodCall representing the hashCode method */
private static MethodCall _hashCode;
/* ------------------------------------------------------------------------ */
/* static initializer
/* ------------------------------------------------------------------------ */
static
{
_equals = new MethodCall(Object.class, "equals", new Object[] {Object.class});
_toString = new MethodCall(Object.class, "toString", new Object[0]);
_hashCode = new MethodCall(Object.class, "hashCode", new Object[0]);
}
/**
* The Default MethodCallHandler for the equals method, performs an == check.
*/
public static final MethodCallHandler EQUALS_HANDLER = new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
Object obj = methodCall.getInvokedObject();
Object toObj = methodCall.getArguments()[0];
if (toObj == null) return false;
if(parent.getTemplateObject() != null){
try {
if(Skeleton.isSkeleton(toObj) &&Skeleton.getSkeleton(toObj).getTemplateObject() != null){
return parent.getTemplateObject().equals(Skeleton.getSkeleton(toObj).getTemplateObject());
} else {
return false;
}
} catch (IllegalArgumentException iae) {
return parent.getTemplateObject().equals(toObj);
}
}
return obj == toObj ? Boolean.TRUE : Boolean.FALSE;
}
};
/**
* The Default MethodCallHandler for the toString method, reproduces
* <classname>@<hashCode>
*/
public static final MethodCallHandler TOSTRING_HANDLER = new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
if(parent.getTemplateObject() != null)
return parent.getTemplateObject().toString();
Object obj = methodCall.getInvokedObject();
return obj.getClass().getName() + "@" + System.identityHashCode(obj);
}
};
/**
* The Default MethodCallHandler for the hashCode method, returns the
* identity hashCode.
*/
public static final MethodCallHandler HASHCODE_HANDLER = new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception
{
if(parent.getTemplateObject() != null)
return parent.getTemplateObject().hashCode();
return Integer.valueOf(System.identityHashCode(methodCall.getInvokedObject()));
}
};
/* ------------------------------------------------------------------------ */
/* registerDefaultHandlers method
/* ------------------------------------------------------------------------ */
/**
* This method registers the DefaultMethodCall Handlers with the specified
* skeleton.
*
* @param s a skeleton
*/
public static void registerDefaultHandlers(Skeleton s)
{
s.registerMethodCallHandler(_equals, EQUALS_HANDLER);
s.registerMethodCallHandler(_toString, TOSTRING_HANDLER);
s.registerMethodCallHandler(_hashCode, HASHCODE_HANDLER);
}
/* ------------------------------------------------------------------------ */
/* isDefaultMethodCall method
/* ------------------------------------------------------------------------ */
/**
* This method returns true if and only if the specified call represents a
* default method call.
*
* @param call the call
* @return see above.
*/
public static boolean isDefaultMethodCall(MethodCall call)
{
return _toString.equals(call) || _equals.equals(call) || _hashCode.equals(call);
}
}
| 7,753 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/MethodCallHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
/**
* Implementations of this interface perform function when a method is called. The
* handler is provided details of the method called along with the skeleton used
* for the call.
*/
public interface MethodCallHandler
{
/**
* @param methodCall the method that was called
* @param parent the skeleton it was called on
* @return an object to be returned (optional)
* @throws Exception an exception in case of failure.
*/
public Object handle(MethodCall methodCall, Skeleton parent) throws Exception;
}
| 7,754 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/ExceptionListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
/**
* <p>This class receives notification that an exception has been thrown from
* a mock object.
* </p>
*/
public interface ExceptionListener
{
/* ------------------------------------------------------------------------ */
/* exceptionNotification method
/* ------------------------------------------------------------------------ */
/**
* This method is called when an exception has been thrown from a mock.
*
* @param t the exception or error thrown.
*/
public void exceptionNotification(Throwable t);
}
| 7,755 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/ReturnTypeHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
/**
* <p>Return type handlers return objects that implement the specified class.</p>
*/
public interface ReturnTypeHandler
{
/**
* This method is called when a method call handler has not been registered
* and an object of a specific type needs to be returned. The handle method
* is called along with the type that is required.
*
* @param clazz the class to create an object for
* @param parent the skeleton requesting the class.
* @return an instance of the class, or something that can be assigned to it.
* @throws Exception if a failure occurs.
*/
public Object handle(Class<?> clazz, Skeleton parent) throws Exception;
} | 7,756 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/MethodCall.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>This class represents a method call that has been or is expected to be
* made. It encapsulates the class that the call was made on, the method
* that was invoked and the arguments passed.</p>
*/
public final class MethodCall
{
/** An empty object array */
private static Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/** The name of the class invoked */
private String _className;
/** The array of interfaces implemented by the class */
private Class<?>[] _interfaces = new Class[0];
/** The method invoked */
private String _methodName;
/** The arguments passed */
private Object[] _arguments = EMPTY_OBJECT_ARRAY;
/** The object invoked */
private Object _invokedObject;
/** A list of comparators to use, instead of the objects .equals methods */
private static Map<Class<?>, Comparator<?>> equalsHelpers = new HashMap<Class<?>, Comparator<?>>();
/* ------------------------------------------------------------------------ */
/* MethodCall method
/* ------------------------------------------------------------------------ */
/**
* This constructor allows a MethodCall to be created when the class can be
* located statically, rather than dynamically.
*
* @param clazz The class.
* @param methodName The method name.
* @param arguments The arguments.
*/
public MethodCall(Class<?> clazz, String methodName, Object ... arguments)
{
_className = clazz.getName();
_methodName = methodName;
_arguments = arguments;
}
/* ------------------------------------------------------------------------ */
/* MethodCall method
/* ------------------------------------------------------------------------ */
/**
* This method is used by the Skeleton in order create an instance of a
* MethodCall representing an invoked interface.
*
* NOTE: If possible changing this so the constructor does not need to be
* default visibility would be good, given the problems with default
* visibility.
*
* @param invokedObject The object that was invoked.
* @param methodName The name of the method invoked.
* @param arguments The arguments passed.
*/
MethodCall(Object invokedObject, String methodName, Object ... arguments)
{
_className = invokedObject.getClass().getName();
_interfaces = invokedObject.getClass().getInterfaces();
_methodName = methodName;
this._arguments = (arguments == null) ? EMPTY_OBJECT_ARRAY : arguments;
_invokedObject = invokedObject;
}
/* ------------------------------------------------------------------------ */
/* getArguments method
/* ------------------------------------------------------------------------ */
/**
* This method returns the arguments.
*
* @return The arguments.
*/
public Object[] getArguments()
{
return _arguments;
}
/* ------------------------------------------------------------------------ */
/* getClassName method
/* ------------------------------------------------------------------------ */
/**
* Returns the name of the class the method was invoked or was defined on.
*
* @return the classname.
*/
public String getClassName()
{
return _className;
}
/* ------------------------------------------------------------------------ */
/* getMethodName method
/* ------------------------------------------------------------------------ */
/**
* Returns the name of the method that was (or will be) invoked.
*
* @return the method name
*/
public String getMethodName()
{
return _methodName;
}
/* ------------------------------------------------------------------------ */
/* checkClassName method
/* ------------------------------------------------------------------------ */
/**
* This method checks that the class names specified in the method call are
* compatible, i.e. one is a superclass of the other.
*
* @param one The first method call.
* @param two The second method call.
* @return true if the classes can be assigned to each other.
*/
private boolean checkClassName(MethodCall one, MethodCall two)
{
// TODO make this stuff work better.
if (one._className.equals("java.lang.Object"))
{
return true;
}
else if (two._className.equals("java.lang.Object"))
{
return true;
}
else if (one._className.equals(two._className))
{
return true;
}
else
{
// check the other class name is one of the implemented interfaces
boolean result = false;
for (int i = 0; i < two._interfaces.length; i++)
{
if (two._interfaces[i].getName().equals(one._className))
{
result = true;
break;
}
}
if (!result)
{
for (int i = 0; i < one._interfaces.length; i++)
{
if (one._interfaces[i].getName().equals(two._className))
{
result = true;
break;
}
}
}
return result;
}
}
/* ------------------------------------------------------------------------ */
/* equals method
/* ------------------------------------------------------------------------ */
/**
* Returns true if and only if the two object represent the same call.
*
* @param obj The object to be compared.
* @return true if the specified object is the same as this.
*/
@Override
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
if (obj instanceof MethodCall)
{
MethodCall other = (MethodCall)obj;
if (!checkClassName(this, other))
{
return false;
}
if (!other._methodName.equals(this._methodName)) return false;
if (other._arguments.length != this._arguments.length) return false;
for (int i = 0; i < this._arguments.length; i++)
{
boolean thisArgNull = this._arguments[i] == null;
boolean otherArgClazz = other._arguments[i] instanceof Class;
boolean otherArgNull = other._arguments[i] == null;
boolean thisArgClazz = this._arguments[i] instanceof Class;
if (thisArgNull)
{
if (otherArgNull)
{
// This is OK
}
else if (otherArgClazz)
{
// This is also OK
}
else
{
return false;
}
// this argument is OK.
}
else if (otherArgNull)
{
if (thisArgClazz)
{
// This is OK
}
else
{
return false;
}
// this argument is OK.
}
else if (otherArgClazz)
{
if (thisArgClazz)
{
Class<?> otherArgClass = (Class<?>) other._arguments[i];
Class<?> thisArgClass = (Class<?>) this._arguments[i];
if (otherArgClass.equals(Class.class) || thisArgClass.equals(Class.class))
{
// do nothing
} else if (!(otherArgClass.isAssignableFrom(thisArgClass) ||
thisArgClass.isAssignableFrom(otherArgClass)))
{
return false;
}
}
else
{
Class<?> clazz = (Class<?>)other._arguments[i];
if (clazz.isPrimitive())
{
if (clazz.equals(byte.class))
{
return this._arguments[i].getClass().equals(Byte.class);
}
else if (clazz.equals(boolean.class))
{
return this._arguments[i].getClass().equals(Boolean.class);
}
else if (clazz.equals(short.class))
{
return this._arguments[i].getClass().equals(Short.class);
}
else if (clazz.equals(char.class))
{
return this._arguments[i].getClass().equals(Character.class);
}
else if (clazz.equals(int.class))
{
return this._arguments[i].getClass().equals(Integer.class);
}
else if (clazz.equals(long.class))
{
return this._arguments[i].getClass().equals(Long.class);
}
else if (clazz.equals(float.class))
{
return this._arguments[i].getClass().equals(Float.class);
}
else if (clazz.equals(double.class))
{
return this._arguments[i].getClass().equals(Double.class);
}
}
else
{
if (!clazz.isInstance(this._arguments[i]))
{
return false;
}
}
}
}
else if (thisArgClazz)
{
Class<?> clazz = (Class<?>)this._arguments[i];
if (clazz.isPrimitive())
{
if (clazz.equals(byte.class))
{
return other._arguments[i].getClass().equals(Byte.class);
}
else if (clazz.equals(boolean.class))
{
return other._arguments[i].getClass().equals(Boolean.class);
}
else if (clazz.equals(short.class))
{
return other._arguments[i].getClass().equals(Short.class);
}
else if (clazz.equals(char.class))
{
return other._arguments[i].getClass().equals(Character.class);
}
else if (clazz.equals(int.class))
{
return other._arguments[i].getClass().equals(Integer.class);
}
else if (clazz.equals(long.class))
{
return other._arguments[i].getClass().equals(Long.class);
}
else if (clazz.equals(float.class))
{
return other._arguments[i].getClass().equals(Float.class);
}
else if (clazz.equals(double.class))
{
return other._arguments[i].getClass().equals(Double.class);
}
}
else
{
if (!clazz.isInstance(other._arguments[i]))
{
return false;
}
}
}
else if (this._arguments[i] instanceof Object[] && other._arguments[i] instanceof Object[])
{
return equals((Object[])this._arguments[i], (Object[])other._arguments[i]);
}
else
{
int result = compareUsingComparators(this._arguments[i], other._arguments[i]);
if (result == 0) continue;
else if (result == 1) return false;
else if (!!!this._arguments[i].equals(other._arguments[i])) return false;
}
}
}
return true;
}
/**
* Compare two arrays calling out to the custom comparators and handling
* AtomicIntegers nicely.
*
* TODO remove the special casing for AtomicInteger.
*
* @param arr1
* @param arr2
* @return true if the arrays are equals, false otherwise.
*/
private boolean equals(Object[] arr1, Object[] arr2)
{
if (arr1.length != arr2.length) return false;
for (int k = 0; k < arr1.length; k++) {
if (arr1[k] == arr2[k]) continue;
if (arr1[k] == null && arr2[k] != null) return false;
if (arr1[k] != null && arr2[k] == null) return false;
int result = compareUsingComparators(arr1[k], arr2[k]);
if (result == 0) continue;
else if (result == 1) return false;
if (arr1[k] instanceof AtomicInteger && arr2[k] instanceof AtomicInteger &&
((AtomicInteger)arr1[k]).intValue() == ((AtomicInteger)arr2[k]).intValue())
continue;
if (!!!arr1[k].equals(arr2[k])) return false;
}
return true;
}
/**
* Attempt to do the comparison using the comparators. This logic returns:
*
* <ul>
* <li>0 if they are equal</li>
* <li>1 if they are not equal</li>
* <li>-1 no comparison was run</li>
* </ul>
*
* @param o1 The first object.
* @param o2 The second object.
* @return 0, 1 or -1 depending on whether the objects were equal, not equal or no comparason was run.
*/
private int compareUsingComparators(Object o1, Object o2)
{
if (o1.getClass() == o2.getClass()) {
@SuppressWarnings("unchecked")
Comparator<Object> compare = (Comparator<Object>) equalsHelpers.get(o1.getClass());
if (compare != null) {
if (compare.compare(o1, o2) == 0) return 0;
else return 1;
}
}
return -1;
}
/* ------------------------------------------------------------------------ */
/* hashCode method
/* ------------------------------------------------------------------------ */
/**
* Returns the hashCode (obtained by returning the hashCode of the
* methodName).
*
* @return The hashCode
*/
@Override
public int hashCode()
{
return _methodName.hashCode();
}
/* ------------------------------------------------------------------------ */
/* toString method
/* ------------------------------------------------------------------------ */
/**
* Returns a string representation of the method call.
*
* @return string representation.
*/
@Override
public String toString()
{
StringBuffer buffer = new StringBuffer();
buffer.append(this._className);
buffer.append('.');
buffer.append(this._methodName);
buffer.append("(");
for (int i = 0; i < this._arguments.length; i++)
{
if (this._arguments[i] != null)
{
if (this._arguments[i] instanceof Class)
{
buffer.append(((Class<?>)this._arguments[i]).getName());
}
else if (Proxy.isProxyClass(this._arguments[i].getClass()))
{
// If the object is a dynamic proxy, just use the proxy class name to avoid calling toString on the proxy
buffer.append(this._arguments[i].getClass().getName());
}
else if (this._arguments[i] instanceof Object[])
{
buffer.append(Arrays.toString((Object[])this._arguments[i]));
}
else
{
buffer.append(String.valueOf(this._arguments[i]));
}
}
else
{
buffer.append("null");
}
if (i + 1 < this._arguments.length)
buffer.append(", ");
}
buffer.append(")");
String string = buffer.toString();
return string;
}
/* ------------------------------------------------------------------------ */
/* getInterfaces method
/* ------------------------------------------------------------------------ */
/**
* This method returns the list of interfaces implemented by the class that
* was called.
*
* @return Returns the interfaces.
*/
public Class<?>[] getInterfaces()
{
return this._interfaces;
}
/* ------------------------------------------------------------------------ */
/* getInvokedObject method
/* ------------------------------------------------------------------------ */
/**
* This method returns the invoked object.
*
* @return The object that was invoked or null if an expected call.
*/
public Object getInvokedObject()
{
return _invokedObject;
}
/* ------------------------------------------------------------------------ */
/* registerEqualsHelper method
/* ------------------------------------------------------------------------ */
/**
* The native equals for an object may not provide the behaviour required by
* the tests. As an example AtomicInteger does not define a .equals, but tests
* may wish to compare it being passed in a method call for equality. This
* method allows a Comparator to be specified for any type and the Comparator
* will be used to determine equality in place of the .equals method.
*
* <p>The Comparator must not throw exceptions, and must return 0 for equality
* or any other integer for inequality.
* </p>
*
* @param <T> the type of the class and comparator.
* @param type the type of the class for which the comparator will be called.
* @param comparator the comparator to call.
*/
public static <T> void registerEqualsHelper(Class<T> type, Comparator<T> comparator)
{
equalsHelpers.put(type, comparator);
}
/* ------------------------------------------------------------------------ */
/* removeEqualsHelper method
/* ------------------------------------------------------------------------ */
/**
* This method removes any registered comparator specified for the given type.
*
* @param type the type to remove the comparator from.
*/
public static void removeEqualsHelper(Class<?> type)
{
equalsHelpers.remove(type);
}
} | 7,757 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/DefaultInvocationHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* <p>This invocation handler is used by the Skeleton when nothing else is
* matched. If the return type is an interface it creates a dynamic proxy
* backed by the associated skeleton for return, if it is a class with a
* default constructor that will be returned.
* </p>
*/
public class DefaultInvocationHandler implements InvocationHandler
{
/** The skeleton this handler is associated with */
private Skeleton _s;
/* ------------------------------------------------------------------------ */
/* DefaultInvocationHandler constructor
/* ------------------------------------------------------------------------ */
/**
* Creates an instance called by the specified skeleton.
*
* @param s The caller.
*/
public DefaultInvocationHandler(Skeleton s)
{
this._s = s;
}
/* ------------------------------------------------------------------------ */
/* invoke method
/* ------------------------------------------------------------------------ */
/**
* Invoked when no ReturnType or MethodCall Handlers are defined.
*
* @param target The target object that was invoked.
* @param method The method that was invoked.
* @param arguments The arguments that were passed.
* @return A proxy or null.
* @throws Throwable
*/
public Object invoke(Object target, Method method, Object[] arguments)
throws Throwable
{
Class<?> returnType = method.getReturnType();
Object obj = null;
if (returnType.isInterface())
{
obj = createProxy(new Class[] { returnType });
}
else
{
try
{
obj = returnType.newInstance();
}
catch (Exception e)
{
// if this occurs then assume no default constructor was visible.
}
}
return obj;
}
/* ------------------------------------------------------------------------ */
/* createProxy method
/* ------------------------------------------------------------------------ */
/**
* Creates and returns a proxy backed by the associated skeleton, that
* implements the specified interfaces. Null is returned if the return
* type array contains non interfaces.
*
* @param returnTypes The classes.
* @return The proxy or null.
*/
public Object createProxy(Class<?> ... returnTypes)
{
Object result = null;
boolean allInterfaces = true;
for(int i = 0; (allInterfaces && i<returnTypes.length); i++)
allInterfaces = returnTypes[i].isInterface();
if (allInterfaces)
{
result = _s.createMock(returnTypes);
}
return result;
}
}
| 7,758 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/annotations/Singleton.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be applied to template objects. If a template object's
* class has this annotation and is passed multiple times to the Skeleton.newMock
* method with the same interface class the same mock will be returned, unless
* the garbage collector has cleared the previous mock.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Singleton
{
} | 7,759 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/mocks/annotations/InjectSkeleton.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.mocks.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* If a field on a template is marked with this annotation then it will be
* injected with the Skeleton instance for the most recently created mock.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectSkeleton
{
} | 7,760 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/fixture/ArchiveFixture.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.unittest.fixture;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.osgi.framework.Constants;
/**
* Utility class for creating archive-based fixtures such as EBA archives, jar files etc.
* This class provides a flow based api for defining such fixtures. For example, a simple EBA archive could
* be defined as such:
*
* <code>
* ArchiveFixtures.ZipFixture zip = ArchiveFixtures.newZip()
* .jar("test.jar")
* .manifest()
* .symbolicName("com.ibm.test")
* .version("2.0.0")
* .end()
* .file("random.txt", "Some text")
* .end();
* </code>
*
* This defines a zip archive containing a single jar file (hence no application manifest). The jar file itself has
* a manifest and a text file.
*
* To actually create the physical archive use the <code>writeOut</code> method on the archive fixture.
*/
public class ArchiveFixture
{
/**
* Create a new zip file fixture
* @return
*/
public static ZipFixture newZip() {
return new ZipFixture(null);
}
/**
* Create a new jar file fixture
* @return
*/
public static JarFixture newJar() {
return new JarFixture(null);
}
/**
* Utility to copy an InputStream into an OutputStream. Closes the InputStream afterwards.
* @param in
* @param out
* @throws IOException
*/
private static void copy(InputStream in, OutputStream out) throws IOException
{
try {
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1)
out.write(b,0,len);
}
finally {
in.close();
}
}
/**
* Base interface for every fixture.
*/
public interface Fixture {
/**
* Write the physical representation of the fixture to the given OutputStream
* @param out
* @throws IOException
*/
void writeOut(OutputStream out) throws IOException;
}
/**
* Abstract base class for fixtures. Archive fixtures are by nature hierarchical.
*/
public static abstract class AbstractFixture implements Fixture {
private ZipFixture parent;
protected AbstractFixture(ZipFixture parent) {
this.parent = parent;
}
/**
* Ends the current flow target and returns the parent flow target. For example, in the
* following code snippet the <code>end</code> after <code>.version("2.0.0")</code> marks
* the end of the manifest. Commands after that relate to the parent jar file of the manifest.
*
* <code>
* ArchiveFixtures.ZipFixture zip = ArchiveFixtures.newZip()
* .jar("test.jar")
* .manifest()
* .symbolicName("com.ibm.test")
* .version("2.0.0")
* .end()
* .file("random.txt", "Some text")
* .end();
* </code>
* @return
*/
public ZipFixture end() {
return (parent == null) ? (ZipFixture) this : parent;
}
}
/**
* Simple fixture for text files.
*/
public static class FileFixture extends AbstractFixture {
private StringBuffer text = new StringBuffer();
protected FileFixture(ZipFixture parent) {
super(parent);
}
/**
* Add a line to the file fixture. The EOL character is added automatically.
* @param line
* @return
*/
public FileFixture line(String line) {
text.append(line);
text.append("\n");
return this;
}
public void writeOut(OutputStream out) throws IOException {
out.write(text.toString().getBytes());
}
}
public static class IStreamFixture extends AbstractFixture {
private byte[] bytes;
protected IStreamFixture(ZipFixture parent, InputStream input) throws IOException {
super(parent);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
copy(input, output);
} finally {
output.close();
}
bytes = output.toByteArray();
}
public void writeOut(OutputStream out) throws IOException {
copy(new ByteArrayInputStream(bytes), out);
}
}
/**
* Fixture for (bundle) manifests. By default, they contain the lines
*
* <code>
* Manifest-Version: 1
* Bundle-ManifestVersion: 2
* </code>
*/
public static class ManifestFixture extends AbstractFixture {
private Manifest mf;
protected Manifest getManifest()
{
return mf;
}
protected ManifestFixture(ZipFixture parent) {
super(parent);
mf = new Manifest();
mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1");
mf.getMainAttributes().putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
}
/**
* Set the symbolic name of the bundle
* @param name
* @return
*/
public ManifestFixture symbolicName(String name)
{
mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, name);
return this;
}
/**
* Set the version of the bundle
* @param version
* @return
*/
public ManifestFixture version(String version)
{
mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);
return this;
}
/**
* Add a custom attribute to the manifest. Use the more specific methods for symbolic name and version.
* @param name
* @param value
* @return
*/
public ManifestFixture attribute(String name, String value)
{
mf.getMainAttributes().putValue(name, value);
return this;
}
public void writeOut(OutputStream out) throws IOException
{
mf.write(out);
}
}
/**
* Fixture for a jar archive. It offers the same functionality as zip fixtures.
* The main difference is that in a jar archive the manifest will be output as the first file,
* regardless of when it is added.
*/
public static class JarFixture extends ZipFixture {
private ManifestFixture mfFixture;
protected JarFixture(ZipFixture parent) {
super(parent);
}
@Override
public ManifestFixture manifest()
{
if (mfFixture != null)
throw new IllegalStateException("Only one manifest allowed, you dummy ;)");
mfFixture = new ManifestFixture(this);
return mfFixture;
}
@Override
public InputStream getInputStream() throws IOException
{
if (bytes == null) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
JarOutputStream jout;
if (mfFixture != null)
jout = new JarOutputStream(bout, mfFixture.getManifest());
else
jout = new JarOutputStream(bout);
try {
writeAllEntries(jout);
} finally {
jout.close();
}
bytes = bout.toByteArray();
}
return new ByteArrayInputStream(bytes);
}
}
/**
* Base fixture for any kind of zip archive. Zip archives can contain any number of child archives
* given by an archive type and a path. The order in which these child archives are added is important
* because it will be the order in which they are added to the zip.
*/
public static class ZipFixture extends AbstractFixture {
protected static class ChildFixture {
public String path;
public Fixture fixture;
public ChildFixture(String path, Fixture fixture)
{
this.path = path;
this.fixture = fixture;
}
}
protected List<ChildFixture> children = new ArrayList<ChildFixture>();
protected byte[] bytes = null;
protected ZipFixture(ZipFixture parent) {
super(parent);
}
/**
* Create a child zip fixture at the given target.
* @param path
* @return
*/
public ZipFixture zip(String path) {
ZipFixture res = new ZipFixture(this);
children.add(new ChildFixture(path, res));
return res;
}
/**
* Create a child jar fixture at the given path.
* @param path
* @return
*/
public ZipFixture jar(String path) {
JarFixture res = new JarFixture(this);
children.add(new ChildFixture(path, res));
return res;
}
/**
* Create a complete child file fixture at the given path and with the content.
* Note: this will return the current zip fixture and not the file fixture.
*
* @param path
* @param content
* @return
*/
public ZipFixture file(String path, String content)
{
return file(path).line(content).end();
}
/**
* Create an empty file fixture at the given path.
*
* @param path
* @return
*/
public FileFixture file(String path)
{
FileFixture res = new FileFixture(this);
children.add(new ChildFixture(path, res));
return res;
}
/**
* Create a binary file with the content from the input stream
* @param path
* @param input
* @return
*/
public ZipFixture binary(String path, InputStream input) throws IOException {
if (input == null) throw new IllegalArgumentException("Provided input stream cannot be null");
IStreamFixture child = new IStreamFixture(this, input);
children.add(new ChildFixture(path, child));
return this;
}
/**
* Create a binary file that is populated from content on the classloader
* @param path
* @param resourcePath Path that the resource can be found in the current classloader
* @return
*/
public ZipFixture binary(String path, String resourcePath) throws IOException {
return binary(path, getClass().getClassLoader().getResourceAsStream(resourcePath));
}
/**
* Create a manifest fixture at the given path.
* @return
*/
public ManifestFixture manifest()
{
ManifestFixture res = new ManifestFixture(this);
children.add(new ChildFixture("META-INF/MANIFEST.MF", res));
return res;
}
/**
* Ensure that the necessary directory entries for the entry are available
* in the zip file. Newly created entries are added to the set of directories.
*
* @param zout
* @param entry
* @param existingDirs
* @throws IOException
*/
private void mkDirs(ZipOutputStream zout, String entry, Set<String> existingDirs) throws IOException
{
String[] parts = entry.split("/");
String dirName = "";
for (int i=0;i<parts.length-1;i++) {
dirName += parts[i] + "/";
if (!!!existingDirs.contains(dirName)) {
ZipEntry ze = new ZipEntry(dirName);
zout.putNextEntry(ze);
zout.closeEntry();
existingDirs.add(dirName);
}
}
}
/**
* Add all entries to the ZipOutputStream
* @param zout
* @throws IOException
*/
protected void writeAllEntries(ZipOutputStream zout) throws IOException
{
Set<String> dirs = new HashSet<String>();
for (ChildFixture child : children) {
mkDirs(zout, child.path, dirs);
ZipEntry ze = new ZipEntry(child.path);
zout.putNextEntry(ze);
child.fixture.writeOut(zout);
zout.closeEntry();
}
}
public void writeOut(OutputStream out) throws IOException
{
copy(getInputStream(), out);
}
public InputStream getInputStream() throws IOException
{
/*
* For better reuse this method delegate the writing to writeAllEntries, which
* can be reused by the JarFixture.
*/
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(bout);
try {
writeAllEntries(zout);
} finally {
zout.close();
}
bytes = bout.toByteArray();
return new ByteArrayInputStream(bytes);
}
}
}
| 7,761 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/unittest/junit/Assert.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.unittest.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* A library of useful assertion routines.
*/
public class Assert
{
/**
* This method checks that the two objects have the same hashCode. If the
* equalsObjects parameter is true then the objects must also be .equals equal
* if the equalsObject parameter is false then they must not be .equals equal.
*
* @param <T>
* @param obj the first object.
* @param obj2 the second object.
* @param equalObjects whether the objects are also equal.
*/
public static <T> void assertHashCodeEquals(T obj, T obj2, boolean equalObjects)
{
assertEquals("The hashCodes were different, bad, bad, bad", obj.hashCode(), obj2.hashCode());
assertEquals("The two objects are not equal", equalObjects, obj.equals(obj2));
}
/**
* This method makes sure that the hashCodes are not equal. And that they
* are not .equals. This is because two objects of the same type cannot be
* .equals if they have different hashCodes.
*
* @param <T>
* @param obj
* @param obj2
*/
public static <T> void assertHashCodeNotEquals(T obj, T obj2)
{
assertFalse("The the two hashCodes should be different: " + obj.hashCode() + ", " + obj2.hashCode(), obj.hashCode() == obj2.hashCode());
assertFalse("The two objects not equal", obj.equals(obj2));
}
/**
* This method asserts that the equals contract is upheld by type T.
*
* @param <T>
* @param info an instance of T
* @param info2 a different instance of T that is .equal to info
* @param info3 an instance of T that is not equal to info
*/
public static <T> void assertEqualsContract(T info, T info2, T info3)
{
Object other = new Object();
if (info.getClass() == Object.class) other = "A string";
assertEquals(info, info);
assertFalse(info.equals(null));
assertTrue("Equals should be commutative", info.equals(info2) == info2.equals(info) && info2.equals(info3) == info3.equals(info2));
assertTrue("If two objects are equal, then they must both be equal (or not equal) to a third", info.equals(info3) == info2.equals(info3));
assertFalse("An object should not equal an object of a disparate type", info.equals(other));
}
} | 7,762 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/itest/RichBundleContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.itest;
import java.io.File;
import java.io.InputStream;
import java.util.Collection;
import java.util.Dictionary;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleListener;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
/**
* {@link BundleContext} wrapper that adds a couple of additional utilities
*
*/
public class RichBundleContext implements BundleContext {
public static final long DEFAULT_TIMEOUT = 15000;
private final BundleContext delegate;
public RichBundleContext(BundleContext delegate) {
this.delegate = delegate;
}
public <T> T getService(Class<T> type) {
return getService(type, null, DEFAULT_TIMEOUT);
}
public <T> T getService(Class<T> type, long timeout) {
return getService(type, null, timeout);
}
public <T> T getService(Class<T> type, String filter) {
return getService(type, filter, DEFAULT_TIMEOUT);
}
public <T> T getService(Class<T> type, String filter, long timeout) {
ServiceTracker tracker = null;
try {
String flt;
if (filter != null) {
if (filter.startsWith("(")) {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
} else {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
}
} else {
flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
}
Filter osgiFilter = FrameworkUtil.createFilter(flt);
tracker = new ServiceTracker(delegate, osgiFilter, null);
tracker.open();
Object svc = type.cast(tracker.waitForService(timeout));
if (svc == null) {
System.out.println("Could not obtain a service in time, service-ref="+
tracker.getServiceReference()+
", time="+System.currentTimeMillis());
throw new RuntimeException("Gave up waiting for service " + flt);
}
return type.cast(svc);
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Invalid filter", e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public Bundle getBundleByName(String symbolicName) {
for (Bundle b : delegate.getBundles()) {
if (b.getSymbolicName().equals(symbolicName)) {
return b;
}
}
return null;
}
public String getProperty(String key) {
return delegate.getProperty(key);
}
public Bundle getBundle() {
return delegate.getBundle();
}
public Bundle getBundle(String filter) { return delegate.getBundle(filter); }
public Bundle installBundle(String location, InputStream input)
throws BundleException {
return delegate.installBundle(location, input);
}
public Bundle installBundle(String location) throws BundleException {
return delegate.installBundle(location);
}
public Bundle getBundle(long id) {
return delegate.getBundle(id);
}
public Bundle[] getBundles() {
return delegate.getBundles();
}
public void addServiceListener(ServiceListener listener, String filter)
throws InvalidSyntaxException {
delegate.addServiceListener(listener, filter);
}
public void addServiceListener(ServiceListener listener) {
delegate.addServiceListener(listener);
}
public void removeServiceListener(ServiceListener listener) {
delegate.removeServiceListener(listener);
}
public void addBundleListener(BundleListener listener) {
delegate.addBundleListener(listener);
}
public void removeBundleListener(BundleListener listener) {
delegate.removeBundleListener(listener);
}
public void addFrameworkListener(FrameworkListener listener) {
delegate.addFrameworkListener(listener);
}
public void removeFrameworkListener(FrameworkListener listener) {
delegate.removeFrameworkListener(listener);
}
@SuppressWarnings("rawtypes")
public ServiceRegistration registerService(String[] clazzes,
Object service, Dictionary properties) {
return delegate.registerService(clazzes, service, properties);
}
@SuppressWarnings("rawtypes")
public ServiceRegistration registerService(String clazz, Object service,
Dictionary properties) {
return delegate.registerService(clazz, service, properties);
}
public ServiceRegistration registerService(Class clazz, Object service, Dictionary props) {
return delegate.registerService(clazz, service, props);
}
public ServiceReference[] getServiceReferences(String clazz, String filter)
throws InvalidSyntaxException {
return delegate.getServiceReferences(clazz, filter);
}
public Collection getServiceReferences(Class clazz, String filter) throws InvalidSyntaxException {
return delegate.getServiceReferences(clazz, filter);
}
public ServiceReference[] getAllServiceReferences(String clazz,
String filter) throws InvalidSyntaxException {
return delegate.getAllServiceReferences(clazz, filter);
}
public ServiceReference getServiceReference(String clazz) {
return delegate.getServiceReference(clazz);
}
public ServiceReference getServiceReference(Class clazz) { return delegate.getServiceReference(clazz); }
public Object getService(ServiceReference reference) {
return delegate.getService(reference);
}
public boolean ungetService(ServiceReference reference) {
return delegate.ungetService(reference);
}
public File getDataFile(String filename) {
return delegate.getDataFile(filename);
}
public Filter createFilter(String filter) throws InvalidSyntaxException {
return delegate.createFilter(filter);
}
}
| 7,763 |
0 | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries | Create_ds/aries/testsupport/testsupport-unit/src/main/java/org/apache/aries/itest/AbstractIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.itest;
import javax.inject.Inject;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
/**
* Base class for Pax Exam 1.2.x based unit tests
*
* Contains the injection point and various utilities used in most tests
*/
public abstract class AbstractIntegrationTest {
/** Gateway to the test OSGi framework */
@Inject
protected BundleContext bundleContext;
/**
* Get a richer version of {@link BundleContext}
*/
public RichBundleContext context() {
return new RichBundleContext(bundleContext);
}
public String getLocalRepo() {
String localRepo = System.getProperty("maven.repo.local");
if (localRepo == null) {
localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
}
return localRepo;
}
/**
* Help to diagnose bundles that did not start
*
* @throws BundleException
*/
public void showBundles() throws BundleException {
Bundle[] bundles = bundleContext.getBundles();
for (Bundle bundle : bundles) {
System.out.println(bundle.getBundleId() + ":" + bundle.getSymbolicName() + ":" + bundle.getVersion() + ":" + bundle.getState());
}
}
/**
* Helps to diagnose bundles that are not resolved as it will throw a detailed exception
*
* @throws BundleException
*/
public void resolveBundles() throws BundleException {
Bundle[] bundles = bundleContext.getBundles();
for (Bundle bundle : bundles) {
if (bundle.getState() == Bundle.INSTALLED) {
System.out.println("Found non resolved bundle " + bundle.getBundleId() + ":" + bundle.getSymbolicName() + ":" + bundle.getVersion());
bundle.start();
}
}
}
}
| 7,764 |
0 | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy/itests/WeavingProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.itests;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.apache.aries.proxy.weavinghook.ProxyWeavingController;
import org.apache.aries.proxy.weavinghook.WeavingHelper;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.hooks.weaving.WovenClass;
@ExamReactorStrategy(PerMethod.class)
public class WeavingProxyTest extends AbstractProxyTest
{
@Configuration
public Option[] configuration() {
return new Option[] //
{
proxyOptions()
};
}
/**
* This test does two things. First of all it checks that we can proxy a final
* class. It also validates that the class implements WovenProxy, and that the
* delegation still works
*/
@Test
public void checkProxyFinalClass() throws Exception
{
Bundle b = bundleContext.getBundle();
TestCallable dispatcher = new TestCallable();
TestCallable template = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(TestCallable.class);
@SuppressWarnings("unchecked")
Callable<Object> o = (Callable<Object>) mgr.createDelegatingProxy(b, classes,
dispatcher, template);
if(!!!(o instanceof WovenProxy))
fail("Proxy should be woven!");
Object inner = new Integer(3);
dispatcher.setReturn(new TestCallable());
((TestCallable)dispatcher.call()).setReturn(inner);
assertSame("Should return the same object", inner, o.call());
}
/**
* This method checks that we correctly proxy a class with final methods.
*/
@Test
public void checkProxyFinalMethods() throws Exception
{
Bundle b = bundleContext.getBundle();
Callable<Object> c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
Runnable r = new Runnable() {
public final void run() {
}
};
classes.add(r.getClass());
Object o = mgr.createDelegatingProxy(b, classes, c, r);
if(!!!(o instanceof WovenProxy))
fail("Proxy should be woven!");
}
@Test(expected = FinalModifierException.class)
public void checkProxyController() throws Exception
{
bundleContext.registerService(ProxyWeavingController.class.getName(), new ProxyWeavingController() {
public boolean shouldWeave(WovenClass arg0, WeavingHelper arg1)
{
return false;
}
}, null);
Bundle b = bundleContext.getBundle();
Callable<Object> c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
// Don't use anonymous inner class in this test as IBM and Sun load it at a different time
// For IBM JDK, the anonymous inner class will be loaded prior to the controller is registered.
Callable<?> callable = new TestFinalDelegate();
classes.add(callable.getClass());
Object o = mgr.createDelegatingProxy(b, classes, c, callable);
if(o instanceof WovenProxy)
fail("Proxy should not have been woven!");
}
private static class TestFinalDelegate extends AbstractList<String> implements Callable<String> {
@Override
public String get(int location)
{
return null;
}
@Override
public int size()
{
return 0;
}
public final String call() throws Exception
{
return null;
}
}
}
| 7,765 |
0 | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy/itests/BasicProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.UnableToProxyException;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
public class BasicProxyTest extends AbstractProxyTest
{
@Configuration
public Option[] configuration() {
return new Option[] //
{
proxyOptions()
};
}
/**
* This test does two things. First of all it checks that we throw a FinalModifierException if we
* try to proxy a final class. It also validates that the message and toString in the exception
* works as expected.
*/
@Test
public void checkProxyFinalClass() throws UnableToProxyException
{
Bundle b = bundleContext.getBundle();
Callable<Object> c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(TestCallable.class);
try {
mgr.createDelegatingProxy(b, classes, c, null);
} catch (FinalModifierException e) {
String msg = e.getMessage();
assertEquals("The message didn't look right", "The class " + TestCallable.class.getName() + " is final.", msg);
assertTrue("The message didn't appear in the toString", e.toString().endsWith(msg));
}
}
/**
* This method checks that we correctly proxy an interface with default methods on java 8
*/
@Test
public void checkProxydefaultMethodInterface() throws UnableToProxyException
{
Bundle b = bundleContext.getBundle();
Callable<Object> c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
// proxy an interface with a default methods (on Java 8).
classes.add(java.lang.CharSequence.class);
try {
mgr.createDelegatingProxy(b, classes, c, null);
} catch (FinalModifierException e) {
String msg = e.getMessage();
assertEquals("The message didn't look right", "The class " + TestCallable.class.getName() + " is final.", msg);
assertTrue("The message didn't appear in the toString", e.toString().endsWith(msg));
}
}
/**
* This method checks that we correctly fail to proxy a class with final methods.
* It also does a quick validation on the exception message.
*/
@Test
public void checkProxyFinalMethods() throws UnableToProxyException
{
Bundle b = bundleContext.getBundle();
Callable<Object> c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
Runnable r = new Runnable() {
public final void run() {
}
};
classes.add(r.getClass());
try {
mgr.createDelegatingProxy(b, classes, c, null);
} catch (FinalModifierException e) {
assertTrue("The methods didn't appear in the message", e.getMessage().contains("run"));
}
}
} | 7,766 |
0 | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-itests/src/test/java/org/apache/aries/proxy/itests/AbstractProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.when;
import java.lang.reflect.Method;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.ProxyManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public abstract class AbstractProxyTest {
@Inject
BundleContext bundleContext;
@Inject
ProxyManager mgr;
public final static class TestCallable implements Callable<Object> {
private Object list = new ArrayList<Object>();
public Object call() throws Exception {
return list;
}
public void setReturn(Object o) {
list = o;
}
}
public static class TestDelegate extends AbstractList<String> implements Callable<String> {
private final String message;
/**
* On HotSpot VMs newer than 1.6 u33, we can only generate subclass proxies for classes
* with a no-args constructor.
*/
protected TestDelegate() {
super();
this.message = null;
}
public TestDelegate(String message) {
super();
this.message = message;
}
public String call() throws Exception {
return message;
}
public boolean equals(Object o) {
if(o instanceof TestDelegate){
return message.equals(((TestDelegate)o).message);
}
return false;
}
public void throwException() {
throw new RuntimeException();
}
public void testInternallyCaughtException() {
try {
throw new RuntimeException();
} catch (RuntimeException re) {
// no op
}
}
@Override
public String get(int location) {
return null;
}
@Override
public int size() {
return 0;
}
}
private class TestListener implements InvocationListener {
boolean preInvoke = false;
boolean postInvoke = false;
boolean postInvokeExceptionalReturn = false;
Object token;
public Object preInvoke(Object proxy, Method m, Object[] args)
throws Throwable {
preInvoke = true;
token = new Object();
return token;
}
public void postInvoke(Object token, Object proxy, Method m,
Object returnValue) throws Throwable {
postInvoke = this.token == token;
}
public void postInvokeExceptionalReturn(Object token, Object proxy,
Method m, Throwable exception) throws Throwable {
postInvokeExceptionalReturn = this.token == token;
}
public void clear() {
preInvoke = false;
postInvoke = false;
postInvokeExceptionalReturn = false;
token = null;
}
}
@Test
public void testEquals() throws Exception {
Bundle b = bundleContext.getBundle();
TestCallable c = new TestCallable();
c.setReturn(new TestDelegate("One"));
TestCallable c2 = new TestCallable();
c.setReturn(new TestDelegate("Two"));
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(List.class);
Object proxy = mgr.createDelegatingProxy(b, classes, c, new TestDelegate("Three"));
Object otherProxy = mgr.createDelegatingProxy(b, classes, c, new TestDelegate("Four"));
Object totallyOtherProxy = mgr.createDelegatingProxy(b, classes, c2, new TestDelegate("Five"));
assertTrue("The object is not equal to itself", proxy.equals(proxy));
assertTrue("The object is not equal to another proxy of itself", proxy.equals(otherProxy));
assertFalse("The object is equal to proxy to another object", proxy.equals(totallyOtherProxy));
}
@Test
public void testDelegation() throws Exception {
Bundle b = bundleContext.getBundle();
TestCallable c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(TestDelegate.class);
TestDelegate proxy = (TestDelegate) mgr.createDelegatingProxy(b, classes, c, new TestDelegate(""));
c.setReturn(new TestDelegate("Hello"));
assertEquals("Wrong message", "Hello", proxy.call());
c.setReturn(new TestDelegate("Hello again"));
assertEquals("Wrong message", "Hello again", proxy.call());
}
@Test
public void testInterception() throws Exception {
Bundle b = bundleContext.getBundle();
TestDelegate td = new TestDelegate("Hello");
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(TestDelegate.class);
TestListener tl = new TestListener();
TestDelegate proxy = (TestDelegate) mgr.createInterceptingProxy(b, classes, td, tl);
//We need to call clear here, because the object will have had its toString() called
tl.clear();
assertCalled(tl, false, false, false);
assertEquals("Wrong message", "Hello", proxy.call());
assertCalled(tl, true, true, false);
tl.clear();
assertCalled(tl, false, false, false);
try {
proxy.throwException();
fail("Should throw an exception");
} catch (RuntimeException re) {
assertCalled(tl, true, false, true);
}
tl.clear();
assertCalled(tl, false, false, false);
try {
proxy.testInternallyCaughtException();
} finally {
assertCalled(tl, true, true, false);
}
}
@Test
public void testDelegationAndInterception() throws Exception {
Bundle b = bundleContext.getBundle();
TestCallable c = new TestCallable();
Collection<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(TestDelegate.class);
TestListener tl = new TestListener();
TestDelegate proxy = (TestDelegate) mgr.createDelegatingInterceptingProxy(b, classes, c, new TestDelegate(""), tl);
c.setReturn(new TestDelegate("Hello"));
//We need to call clear here, because the object will have had its toString() called
tl.clear();
assertCalled(tl, false, false, false);
assertEquals("Wrong message", "Hello", proxy.call());
assertCalled(tl, true, true, false);
tl.clear();
assertCalled(tl, false, false, false);
c.setReturn(new TestDelegate("Hello again"));
assertEquals("Wrong message", "Hello again", proxy.call());
assertCalled(tl, true, true, false);
tl.clear();
assertCalled(tl, false, false, false);
try {
proxy.throwException();
fail("Should throw an exception");
} catch (RuntimeException re) {
assertCalled(tl, true, false, true);
}
tl.clear();
assertCalled(tl, false, false, false);
try {
proxy.testInternallyCaughtException();
} finally {
assertCalled(tl, true, true, false);
}
}
private void assertCalled(TestListener listener, boolean pre, boolean post, boolean ex) {
assertEquals(pre, listener.preInvoke);
assertEquals(post, listener.postInvoke);
assertEquals(ex, listener.postInvokeExceptionalReturn);
}
protected Option proxyOptions() {
String localRepo = System.getProperty("maven.repo.local");
if (localRepo == null) {
localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
}
return composite(
CoreOptions.junitBundles(),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
when(localRepo != null).useOptions(CoreOptions.vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)),
mavenBundle("org.ow2.asm", "asm-commons").versionAsInProject(),
mavenBundle("org.ow2.asm", "asm").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject()
/* vmOption ("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"),
waitForFrameworkStartup(),*/
);
}
}
| 7,767 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/ProxyManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.osgi.framework.Bundle;
/**
* The proxy manager service allows clients to generate and manage proxies.
*/
public interface ProxyManager
{
/**
* Create a proxy that delegates to an object instance which may change
* over time
*
* @param clientBundle The bundle providing the class to be proxied
* @param classes The interfaces and/or classes to be proxied
* @param dispatcher A {@link Callable} that will called each time the proxy
* is invoked to locate the object to delegate to
* @param template A template object for the proxy, may be null if only interfaces
* need to be proxied. Supplying a templates typically offer a
* significant performance boost to the resulting proxy.
* @return A proxy object that delegates to real objects under the covers
* @throws UnableToProxyException
*/
public Object createDelegatingProxy(Bundle clientBundle, Collection<Class<?>> classes, Callable<Object> dispatcher, Object template) throws UnableToProxyException;
/**
* Creates a proxy that invokes the supplied {@link InvocationListener}
* immediately before and after any non-private method is called.
*
* @param clientBundle
* @param classes
* @param delegate
* @param wrapper
* @return
* @throws UnableToProxyException
*/
public Object createInterceptingProxy(Bundle clientBundle, Collection<Class<?>> classes,
Object delegate, InvocationListener wrapper) throws UnableToProxyException;
/**
* Creates a single proxy that both delegates and intercepts. See
* ProxyManager.createDelegatingProxy(Bundle, Collection, Callable)
* and ProxyManager.createInterceptingProxy(Bundle, Collection, Object, InvocationListener)
*
* @param clientBundle
* @param classes
* @param dispatcher
* @param template A template object for the proxy, may be null if only interfaces
* need to be proxied. Supplying a templates typically offer a
* significant performance boost to the resulting proxy.
* @param wrapper
* @return
* @throws UnableToProxyException
*/
public Object createDelegatingInterceptingProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, Object template, InvocationListener wrapper) throws UnableToProxyException;
/**
* This method unwraps the provided proxy returning the target object.
*
* @param proxy the proxy to unwrap.
* @return the target object.
*/
public Callable<Object> unwrap(Object proxy);
/**
* Returns true if and only if the specified object was generated by the ProxyManager. See
* ProxyManager.createDelegatingProxy(Bundle, Collection, Callable) for details on how to create a proxy.
* @param proxy The proxy object to test
* @return true if it is a proxy, false otherwise.
*/
public boolean isProxy(Object proxy);
}
| 7,768 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/FinalModifierException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy;
public class FinalModifierException extends UnableToProxyException
{
/**
*
*/
private static final long serialVersionUID = -3139392096074404448L;
private String finalMethods = null;
public FinalModifierException(Class<?> clazz)
{
super(clazz);
}
public FinalModifierException(Class<?> clazz, String finalMethods)
{
super(clazz);
this.finalMethods = finalMethods;
}
public boolean isFinalClass()
{
return (finalMethods == null || finalMethods.equals(""));
}
public String getFinalMethods()
{
return finalMethods;
}
public String getMessage()
{
if (isFinalClass()) {
return String.format("The class %s is final.", getClassName());
} else {
return String.format("The methods %s in class %s are final.", finalMethods, getClassName());
}
}
} | 7,769 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/InvocationListener.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* An {@link InvocationListener} is used in conjunction with the {@link ProxyManager}
* to intercept method calls on the proxy object
*/
public interface InvocationListener
{
public Object preInvoke(Object proxy, Method m, Object[] args) throws Throwable;
public void postInvoke(Object token, Object proxy, Method m, Object returnValue) throws Throwable;
public void postInvokeExceptionalReturn(Object token, Object proxy, Method m, Throwable exception) throws Throwable;
default Object aroundInvoke(Object token, Object proxy, Callable<Object> dispatcher, Method method, Object[] args) throws Throwable {
return method.invoke(dispatcher.call(), args);
}
} | 7,770 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/UnableToProxyException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy;
public class UnableToProxyException extends Exception
{
/**
*
*/
private static final long serialVersionUID = -17516969014644128L;
String className = null;
public UnableToProxyException(Class<?> clazz)
{
this(clazz.getName(), clazz.getName());
}
public UnableToProxyException(Class<?> clazz, Throwable e)
{
this(clazz.getName(), e);
}
public UnableToProxyException(String className, Throwable e)
{
super(e);
this.className = className;
}
public UnableToProxyException(String className, String message)
{
super(message);
this.className = className;
}
public UnableToProxyException(Object proxy, String msg)
{
this(proxy.getClass().getName(), msg);
}
public UnableToProxyException(Class<?> clazz, String msg)
{
this(clazz.getName(), msg);
}
public String getClassName()
{
return className;
}
}
| 7,771 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/weavinghook/ProxyWeavingController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.weavinghook;
import org.osgi.framework.hooks.weaving.WovenClass;
/**
* Services of this interface are used by the ProxyManager's weaving implementation to
* decide if a specific bundle should be subject to weaving.
*
* <p>If multiple ProxyWeavingController are registered all will be consulted to decide
* whether to weave or not. As soon as one service says to weave a class then
* it will be woven and following services may not be consulted.
* </p>
*/
public interface ProxyWeavingController
{
/**
* Returns true if the class should be subject to proxy weaving. If it returns
* false then the class will not be weaved. The result of this method is immutable
* for a given bundle. That means repeated calls given the same bundle MUST
* return the same response.
*
* @param classToWeave the class that is a candidate to be weaved.
* @param helper a helper calss to allow the implementation to make intelligent weaving decisions.
* @return true if it should be woven, false otherwise.
*/
public boolean shouldWeave(WovenClass classToWeave, WeavingHelper helper);
} | 7,772 |
0 | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-api/src/main/java/org/apache/aries/proxy/weavinghook/WeavingHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.weavinghook;
import org.osgi.framework.hooks.weaving.WovenClass;
/**
* This provides helper methods to allow a ProxyWeavingController to make
* sensible decisions without needing to know how the ProxyManager has implemented
* the weaving support.
*/
public interface WeavingHelper
{
/**
* Tests to see if the provided class has been woven for proxying.
*
* @param c the class to test
* @return true if it is woven, false otherwise.
*/
public boolean isWoven(Class<?> c);
/**
* Tests to see if the super class of the provided WovenClass has
* been woven to support proxying.
*
* @param wovenClass the class whose parent should be tested.
* @return true if it is woven, false otherwise.
*/
public boolean isSuperClassWoven(WovenClass wovenClass);
}
| 7,773 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/impl/weaving/ProxyWeavingHookTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.weaving;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ProxyWeavingHookTest {
@Test
public void tesDefault() {
BundleContext ctx = (BundleContext) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { BundleContext.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
});
ProxyWeavingHook hook = new ProxyWeavingHook(ctx);
assertTrue(hook.isEnabled("org.apache.foo.Bar"));
assertTrue(hook.isDisabled("javax.foo.Bar"));
}
@Test
public void testFilters() {
BundleContext ctx = (BundleContext) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { BundleContext.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getProperty")) {
if (ProxyWeavingHook.WEAVING_ENABLED_CLASSES.equals(args[0])) {
return "";
}
if (ProxyWeavingHook.WEAVING_DISABLED_CLASSES.equals(args[0])) {
return "org.apache.foo.*";
}
}
return null;
}
});
ProxyWeavingHook hook = new ProxyWeavingHook(ctx);
assertFalse(hook.isEnabled("org.apache.foo.Bar"));
assertTrue(hook.isDisabled("org.apache.foo.Bar"));
assertTrue(hook.isDisabled("org.apache.foo.bar.Bar"));
assertFalse(hook.isDisabled("org.apache.fooBar"));
assertFalse(hook.isDisabled("orgXapache.foo.Bar"));
}
}
| 7,774 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test/a/ProxyTestClassA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.test.a;
public class ProxyTestClassA {
private final String message;
public ProxyTestClassA(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
| 7,775 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test/c/ProxyTestClassC.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.test.c;
import org.apache.aries.proxy.test.b.ProxyTestClassB;
public class ProxyTestClassC extends ProxyTestClassB {
public ProxyTestClassC(String message) {
super(message);
}
public String hello() {
return getMessage();
}
}
| 7,776 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/proxy/test/b/ProxyTestClassB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.test.b;
import org.apache.aries.proxy.test.a.ProxyTestClassA;
public class ProxyTestClassB extends ProxyTestClassA {
public ProxyTestClassB(String message) {
super(message);
}
}
| 7,777 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSerializableWithSVUID.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import java.io.Serializable;
public class ProxyTestClassSerializableWithSVUID implements Serializable {
private static final long serialVersionUID = 5495891081675168306L;
}
| 7,778 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassInnerClasses.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassInnerClasses {
public static class ProxyTestClassStaticInner {
public String sayHello() {
return "Hello";
}
}
public class ProxyTestClassInner {
public String sayGoodbye() {
return "Goodbye";
}
}
public class ProxyTestClassUnweavableInnerParent {
public ProxyTestClassUnweavableInnerParent(int i) {
}
public String wave() {
return "Wave";
}
}
public class ProxyTestClassUnweavableInnerChild extends
ProxyTestClassUnweavableInnerParent {
public ProxyTestClassUnweavableInnerChild() {
super(1);
}
public ProxyTestClassUnweavableInnerChild(int i) {
super(i);
}
public String leave() {
return "Gone";
}
}
}
| 7,779 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSerializableChild.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
@SuppressWarnings("serial")
public class ProxyTestClassSerializableChild extends ProxyTestClassSerializable {
}
| 7,780 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableSibling.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
/**
* A class that has an unweavable super class, but there are no-noargs constructors to be found anywhere
*/
public class ProxyTestClassUnweavableSibling extends ProxyTestClassUnweavableSuper {
public ProxyTestClassUnweavableSibling(int i) {
super(i);
}
}
| 7,781 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassFinalMethod.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassFinalMethod
{
public final void someFinalMethod()
{
}
}
| 7,782 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassGeneralWithNoDefaultOrProtectedAccess.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassGeneralWithNoDefaultOrProtectedAccess extends ProxyTestClassSuperWithNoDefaultOrProtectedAccess
{
public String testMethod(String x, int y, Object z)
{
somePrivateMethod();
return x;
}
public String testArgs(double a, short b, long c, char d, byte e, boolean f)
{
return Character.toString(d);
}
public void testReturnVoid()
{
}
public int testReturnInt()
{
return 17;
}
public Integer testReturnInteger()
{
return Integer.valueOf(1);
}
private void somePrivateMethod()
{
}
public boolean equals(Object o) {
return o == this;
}
public void testException() {
throw new RuntimeException();
}
public void testInternallyCaughtException() {
try {
try {
throw new RuntimeException();
} catch (RuntimeException re) {
// no op
}
} catch (Exception e) {
}
}
}
| 7,783 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableGrandParent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassUnweavableGrandParent {
public ProxyTestClassUnweavableGrandParent(int i) {
}
public String doStuff() {
return "Hi!";
}
}
| 7,784 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassAbstract.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public abstract class ProxyTestClassAbstract {
public abstract String getMessage();
}
| 7,785 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSerializable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
@SuppressWarnings("serial")
public class ProxyTestClassSerializable implements Serializable {
public int value = 0;
/**
* We deserialize using this static method to ensure that the right classloader
* is used when deserializing our object, it will always be the classloader that
* loaded this class, which might be the JUnit one, or our weaving one.
*
* @param bytes
* @param value
* @throws Exception
*/
public static void checkDeserialization(byte[] bytes, int value) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
ProxyTestClassSerializable out = (ProxyTestClassSerializable) ois.readObject();
assertEquals(value, out.value);
}
}
| 7,786 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenSubclassGeneratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.SingleInstanceDispatcher;
import org.apache.aries.proxy.impl.gen.ProxySubclassGenerator;
import org.apache.aries.proxy.impl.gen.ProxySubclassMethodHashSet;
import org.apache.aries.proxy.impl.interfaces.InterfaceProxyGenerator;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.junit.Test;
/**
* This class uses the {@link ProxySubclassGenerator} to test
*/
@SuppressWarnings("unchecked")
public class WovenSubclassGeneratorTest extends AbstractProxyTest
{
private static final Class<?> FINAL_METHOD_CLASS = ProxyTestClassFinalMethod.class;
private static final Class<?> FINAL_CLASS = ProxyTestClassFinal.class;
private static final Class<?> GENERIC_CLASS = ProxyTestClassGeneric.class;
private static final Class<?> COVARIANT_CLASS = ProxyTestClassCovariantOverride.class;
private static ProxySubclassMethodHashSet<String> expectedMethods = new ProxySubclassMethodHashSet<String>(
12);
private Callable<Object> testCallable = null;
/**
* Test that the methods found declared on the generated proxy subclass are
* the ones that we expect.
*/
@Test
public void testExpectedMethods() throws Exception
{
Class<?> superclass = getTestClass();
do {
Method[] declaredMethods = superclass.getDeclaredMethods();
List<Method> listOfDeclaredMethods = new ArrayList<Method>();
for (Method m : declaredMethods) {
if(m.getName().equals("clone") || m.getName().equals("finalize"))
continue;
int i = m.getModifiers();
if (Modifier.isPrivate(i) || Modifier.isFinal(i)) {
// private or final don't get added
} else if (!(Modifier.isPublic(i) || Modifier.isPrivate(i) || Modifier.isProtected(i))) {
// the method is default visibility, check the package
if (m.getDeclaringClass().getPackage().equals(getTestClass().getPackage())) {
// default vis with same package gets added
listOfDeclaredMethods.add(m);
}
} else {
listOfDeclaredMethods.add(m);
}
}
declaredMethods = listOfDeclaredMethods.toArray(new Method[] {});
ProxySubclassMethodHashSet<String> foundMethods = new ProxySubclassMethodHashSet<String>(
declaredMethods.length);
foundMethods.addMethodArray(declaredMethods);
// as we are using a set we shouldn't get duplicates
expectedMethods.addAll(foundMethods);
superclass = superclass.getSuperclass();
} while (superclass != null);
Method[] subclassMethods = getProxyClass(getTestClass()).getDeclaredMethods();
List<Method> listOfDeclaredMethods = new ArrayList<Method>();
for (Method m : subclassMethods) {
if(m.getName().startsWith(WovenProxy.class.getName().replace('.', '_')))
continue;
listOfDeclaredMethods.add(m);
}
subclassMethods = listOfDeclaredMethods.toArray(new Method[] {});
ProxySubclassMethodHashSet<String> generatedMethods = new ProxySubclassMethodHashSet<String>(
subclassMethods.length);
generatedMethods.addMethodArray(subclassMethods);
// check that all the methods we have generated were expected
for (String gen : generatedMethods) {
assertTrue("Unexpected method: " + gen, expectedMethods.contains(gen));
}
// check that all the expected methods were generated
for (String exp : expectedMethods) {
assertTrue("Method was not generated: " + exp, generatedMethods.contains(exp));
}
// check the sets were the same
assertEquals("Sets were not the same", expectedMethods, generatedMethods);
}
/**
* Test a method marked final
*/
@Test
public void testFinalMethod() throws Exception
{
try {
InterfaceProxyGenerator.getProxyInstance(null, FINAL_METHOD_CLASS, Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (RuntimeException re) {
FinalModifierException e = (FinalModifierException) re.getCause();
assertFalse("Should have found final method not final class", e.isFinalClass());
}
}
/**
* Test a class marked final
*/
@Test
public void testFinalClass() throws Exception
{
try {
InterfaceProxyGenerator.getProxyInstance(null, FINAL_CLASS, Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (FinalModifierException e) {
assertTrue("Should have found final class", e.isFinalClass());
}
}
/**
* Test a covariant override method
*/
@Test
public void testCovariant() throws Exception
{
testCallable = new SingleInstanceDispatcher(COVARIANT_CLASS.newInstance());
Object o = setDelegate(getProxyInstance(getProxyClass(COVARIANT_CLASS)), testCallable);
Class<?> generatedProxySubclass = o.getClass();
Method m = generatedProxySubclass.getDeclaredMethod("getCovariant", new Class[] {});
Object returned = m.invoke(o);
assertTrue("Object was of wrong type: " + returned.getClass().getSimpleName(), COVARIANT_CLASS
.isInstance(returned));
}
/**
* Test a covariant override method
*/
@Test
public void testGenerics() throws Exception
{
testCallable = new SingleInstanceDispatcher(GENERIC_CLASS.newInstance());
super.testGenerics();
}
@Test
public void testInner() {
//This implementation can never pass this test. It doesn't support classes with no no-args constructor.
}
@Test
public void testAddingInterfacesToClass() throws Exception {
Object proxy = InterfaceProxyGenerator.getProxyInstance(null, getTestClass(), Arrays.asList(Map.class, Iterable.class), new Callable<Object>() {
int calls = 0;
private Map<String, String> map = new HashMap<String, String>();
{
map.put("key", "value");
}
public Object call() throws Exception {
switch(++calls) {
case 1 :
return getTestClass().newInstance();
case 2 :
return map;
default :
return map.values();
}
}
}, null);
assertEquals(17, ((ProxyTestClassGeneralWithNoDefaultOrProtectedAccess)proxy).testReturnInt());
assertEquals("value", ((Map<String, String>)proxy).put("key", "value2"));
Iterator<?> it = ((Iterable<?>)proxy).iterator();
assertEquals("value2", it.next());
assertFalse(it.hasNext());
}
@Override
protected Object getProxyInstance(Class<?> proxyClass) {
if(proxyClass == ProxyTestClassChildOfAbstract.class) {
return new ProxyTestClassChildOfAbstract();
}
try {
Constructor<?> con = proxyClass.getDeclaredConstructor(Callable.class, InvocationListener.class);
con.setAccessible(true);
return con.newInstance((testCallable == null) ? new SingleInstanceDispatcher(getTestClass().newInstance()) : testCallable, null);
} catch (Exception e) {
return null;
}
}
@Override
protected Class<?> getTestClass() {
return ProxyTestClassGeneralWithNoDefaultOrProtectedAccess.class;
}
@Override
protected Class<?> getProxyClass(Class<?> clazz) {
try {
return InterfaceProxyGenerator.getProxyInstance(null, clazz, Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (UnableToProxyException e) {
return null;
} catch (RuntimeException re) {
if(re.getCause() instanceof UnableToProxyException)
return null;
else
throw re;
}
}
@Override
protected Object setDelegate(Object proxy, Callable<Object> dispatcher) {
return ((WovenProxy)proxy).org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
dispatcher, null);
}
@Override
protected Object getProxyInstance(Class<?> proxyClass,
InvocationListener listener) {
WovenProxy proxy = (WovenProxy) getProxyInstance(proxyClass);
proxy = proxy.org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
new SingleInstanceDispatcher(proxy), listener);
return proxy;
}
protected Object getP3() throws Exception {
return getTestClass().newInstance();
}
} | 7,787 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassPrivateConstructor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassPrivateConstructor
{
private ProxyTestClassPrivateConstructor()
{
}
}
| 7,788 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxySubclassGeneratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.AbstractProxyManager;
import org.apache.aries.proxy.impl.AsmProxyManager;
import org.apache.aries.proxy.impl.ProxyHandler;
import org.apache.aries.proxy.impl.SingleInstanceDispatcher;
import org.apache.aries.proxy.impl.gen.ProxySubclassGenerator;
import org.apache.aries.proxy.impl.gen.ProxySubclassMethodHashSet;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
/**
* This class uses the {@link ProxySubclassGenerator} to test
*/
public class ProxySubclassGeneratorTest extends AbstractProxyTest
{
private static final Class<?> FINAL_METHOD_CLASS = ProxyTestClassFinalMethod.class;
private static final Class<?> FINAL_CLASS = ProxyTestClassFinal.class;
private static final Class<?> GENERIC_CLASS = ProxyTestClassGeneric.class;
private static final Class<?> COVARIANT_CLASS = ProxyTestClassCovariantOverride.class;
private static ProxySubclassMethodHashSet<String> expectedMethods = new ProxySubclassMethodHashSet<String>(
12);
private InvocationHandler ih = null;
Class<?> generatedProxySubclass = null;
Object o = null;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
ih = new FakeInvocationHandler();
((FakeInvocationHandler)ih).setDelegate(getTestClass().newInstance());
generatedProxySubclass = getGeneratedSubclass();
o = getProxyInstance(generatedProxySubclass);
}
/**
* Test that the methods found declared on the generated proxy subclass are
* the ones that we expect.
*/
@Test
public void testExpectedMethods() throws Exception
{
Class<?> superclass = getTestClass();
do {
Method[] declaredMethods = superclass.getDeclaredMethods();
List<Method> listOfDeclaredMethods = new ArrayList<Method>();
for (Method m : declaredMethods) {
int i = m.getModifiers();
if (Modifier.isPrivate(i) || Modifier.isFinal(i)) {
// private or final don't get added
} else if (!(Modifier.isPublic(i) || Modifier.isPrivate(i) || Modifier.isProtected(i))) {
// the method is default visibility, check the package
if (m.getDeclaringClass().getPackage().equals(getTestClass().getPackage())) {
// default vis with same package gets added
listOfDeclaredMethods.add(m);
}
} else {
listOfDeclaredMethods.add(m);
}
}
declaredMethods = listOfDeclaredMethods.toArray(new Method[] {});
ProxySubclassMethodHashSet<String> foundMethods = new ProxySubclassMethodHashSet<String>(
declaredMethods.length);
foundMethods.addMethodArray(declaredMethods);
// as we are using a set we shouldn't get duplicates
expectedMethods.addAll(foundMethods);
superclass = superclass.getSuperclass();
} while (superclass != null);
// add the getter and setter for the invocation handler to the expected
// set
// and the unwrapObject method
Method[] ihMethods = new Method[] {
generatedProxySubclass.getMethod("setInvocationHandler",
new Class[] { InvocationHandler.class }),
generatedProxySubclass.getMethod("getInvocationHandler", new Class[] {}) };
expectedMethods.addMethodArray(ihMethods);
Method[] generatedProxySubclassMethods = generatedProxySubclass.getDeclaredMethods();
ProxySubclassMethodHashSet<String> generatedMethods = new ProxySubclassMethodHashSet<String>(
generatedProxySubclassMethods.length);
generatedMethods.addMethodArray(generatedProxySubclassMethods);
// check that all the methods we have generated were expected
for (String gen : generatedMethods) {
assertTrue("Unexpected method: " + gen, expectedMethods.contains(gen));
}
// check that all the expected methods were generated
for (String exp : expectedMethods) {
assertTrue("Method was not generated: " + exp, generatedMethods.contains(exp));
}
// check the sets were the same
assertEquals("Sets were not the same", expectedMethods, generatedMethods);
}
/**
* Test a method marked final
*/
@Test
public void testFinalMethod() throws Exception
{
try {
ProxySubclassGenerator.getProxySubclass(FINAL_METHOD_CLASS);
} catch (FinalModifierException e) {
assertFalse("Should have found final method not final class", e.isFinalClass());
}
}
/**
* Test a class marked final
*/
@Test
public void testFinalClass() throws Exception
{
try {
ProxySubclassGenerator.getProxySubclass(FINAL_CLASS);
} catch (FinalModifierException e) {
assertTrue("Should have found final class", e.isFinalClass());
}
}
/**
* Test a private constructor
*/
@Test
public void testPrivateConstructor() throws Exception
{
Object o = ProxySubclassGenerator.newProxySubclassInstance(
ProxyTestClassPrivateConstructor.class, ih);
assertNotNull("The new instance was null", o);
}
/**
* Test a generating proxy class of class with package access constructor.
*/
@SuppressWarnings("unchecked")
@Test
public void testPackageAccessCtor() throws Exception {
Class<ProxyTestClassPackageAccessCtor> proxyClass =
(Class<ProxyTestClassPackageAccessCtor>) ProxySubclassGenerator.getProxySubclass(ProxyTestClassPackageAccessCtor.class);
ProxyTestClassPackageAccessCtor proxy = (ProxyTestClassPackageAccessCtor) getProxyInstance(proxyClass);
assertNotNull("The new instance was null", proxy);
}
// /**
// * Test object equality between real and proxy using a Collaborator
// */
// @Test
// public void testObjectEquality() throws Exception
// {
// Object delegate = getTestClass().newInstance();
// InvocationHandler collaborator = new Collaborator(null, null, AsmInterceptorWrapper.passThrough(delegate));
// Object o = ProxySubclassGenerator.newProxySubclassInstance(getTestClass(), collaborator);
// //Calling equals on the proxy with an arg of the unwrapped object should be true
// assertTrue("The proxy object should be equal to its delegate",o.equals(delegate));
// InvocationHandler collaborator2 = new Collaborator(null, null, AsmInterceptorWrapper.passThrough(delegate));
// Object o2 = ProxySubclassGenerator.newProxySubclassInstance(getTestClass(), collaborator2);
// //The proxy of a delegate should equal another proxy of the same delegate
// assertTrue("The proxy object should be equal to another proxy instance of the same delegate", o2.equals(o));
// }
//
// private static class ProxyTestOverridesFinalize {
// public boolean finalizeCalled = false;
//
// @Override
// protected void finalize() {
// finalizeCalled = true;
// }
// }
//
// @Test
// public void testFinalizeNotCalled() throws Exception {
// ProxyTestOverridesFinalize testObj = new ProxyTestOverridesFinalize();
// InvocationHandler ih = new Collaborator(null, null, AsmInterceptorWrapper.passThrough(testObj));
// Object o = ProxySubclassGenerator.newProxySubclassInstance(ProxyTestOverridesFinalize.class, ih);
//
// Method m = o.getClass().getDeclaredMethod("finalize");
// m.setAccessible(true);
// m.invoke(o);
//
// assertFalse(testObj.finalizeCalled);
// }
/**
* Test a covariant override method
*/
@Test
public void testCovariant() throws Exception
{
((FakeInvocationHandler)ih).setDelegate(COVARIANT_CLASS.newInstance());
o = ProxySubclassGenerator.newProxySubclassInstance(COVARIANT_CLASS, ih);
generatedProxySubclass = o.getClass();
Method m = generatedProxySubclass.getDeclaredMethod("getCovariant", new Class[] {});
Object returned = m.invoke(o);
assertTrue("Object was of wrong type: " + returned.getClass().getSimpleName(), COVARIANT_CLASS
.isInstance(returned));
}
/**
* Test a covariant override method
*/
@Test
public void testGenerics() throws Exception
{
((FakeInvocationHandler)ih).setDelegate(GENERIC_CLASS.newInstance());
super.testGenerics();
}
@SuppressWarnings("unchecked")
@Test
public void testClassLoaders() throws Exception {
ClassLoader clA = new LimitedClassLoader("org.apache.aries.proxy.test.a", null, null);
ClassLoader clB = new LimitedClassLoader("org.apache.aries.proxy.test.b", "org.apache.aries.proxy.test.a", clA);
ClassLoader clC = new LimitedClassLoader("org.apache.aries.proxy.test.c", "org.apache.aries.proxy.test.b", clB);
Class<?> clazzA = clA.loadClass("org.apache.aries.proxy.test.a.ProxyTestClassA");
Class<?> clazzB = clB.loadClass("org.apache.aries.proxy.test.b.ProxyTestClassB");
Class<?> clazzC = clC.loadClass("org.apache.aries.proxy.test.c.ProxyTestClassC");
final Object object = clazzC.getConstructor(String.class).newInstance("hello");
o = new AsmProxyManager().createNewProxy(null, Arrays.asList(clazzA, clazzB, clazzC), constantly(object), null);
generatedProxySubclass = o.getClass();
Method m = generatedProxySubclass.getDeclaredMethod("hello", new Class[] {});
Object returned = m.invoke(o);
assertEquals("hello", returned);
}
private static class LimitedClassLoader extends ClassLoader {
Set<String> providedPackages;
Set<String> importedPackages;
List<ClassLoader> parents;
public LimitedClassLoader(String provided, String imported, ClassLoader parent) {
providedPackages = Collections.singleton(provided);
importedPackages = imported != null ? Collections.singleton(imported) : Collections.<String>emptySet();
parents = parent != null ? Collections.singletonList(parent) : Collections.<ClassLoader>emptyList();
}
final Map<String, Object> clLocks = new HashMap<String, Object>();
protected synchronized Object getClassLoadingLock (String name) {
if (!clLocks.containsKey(name)) {
clLocks.put(name, new Object());
}
return clLocks.get(name);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
String pkg = name.substring(0, name.lastIndexOf('.'));
if (pkg.startsWith("java.") || pkg.startsWith("sun.reflect")) {
return getClass().getClassLoader().loadClass(name);
} else if (providedPackages.contains(pkg)) {
c = findClass(name);
} else if (importedPackages.contains(pkg)) {
for (ClassLoader cl : parents) {
try {
c = cl.loadClass(name);
} catch (ClassNotFoundException e) {
// Ignore
}
}
}
}
if (c == null) {
throw new ClassNotFoundException(name);
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String pkg = name.substring(0, name.lastIndexOf('.'));
if (getPackage(pkg) == null) {
definePackage(pkg, null, null, null, null, null, null, null);
}
String path = name.replace('.', '/').concat(".class");
InputStream is = LimitedClassLoader.class.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
IOUtils.copy(is, baos);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
byte[] buf = baos.toByteArray();
return defineClass(name, buf, 0, buf.length);
}
}
private Class<?> getGeneratedSubclass() throws Exception
{
return getProxyClass(getTestClass());
}
private class FakeInvocationHandler implements InvocationHandler
{
private Object delegate = null;
/*
* (non-Javadoc)
*
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
* java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try {
Object result = (delegate instanceof Callable) ?
method.invoke(((Callable<?>)delegate).call(), args) :
method.invoke(delegate, args) ;
return result;
} catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
void setDelegate(Object delegate){
this.delegate = delegate;
}
}
@Override
protected Object getProxyInstance(Class<?> proxyClass) {
return getProxyInstance(proxyClass, ih);
}
private Object getProxyInstance(Class<?> proxyClass, InvocationHandler ih) {
try {
if(proxyClass.equals(ProxyTestClassChildOfAbstract.class))
return proxyClass.newInstance();
Object proxyInstance = proxyClass.getConstructor().newInstance();
Method setIH = proxyInstance.getClass().getMethod("setInvocationHandler", InvocationHandler.class);
setIH.invoke(proxyInstance, ih);
return proxyInstance;
} catch (Exception e) {
return null;
}
}
@Override
protected Class<?> getProxyClass(Class<?> clazz) {
try {
return ProxySubclassGenerator.getProxySubclass(clazz);
} catch (UnableToProxyException e) {
return null;
}
}
@Override
protected Object setDelegate(Object proxy, Callable<Object> dispatcher) {
AbstractProxyManager apm = new AsmProxyManager();
return getProxyInstance(proxy.getClass(), new ProxyHandler(apm, dispatcher, null));
}
@Override
protected Object getProxyInstance(Class<?> proxyClass,
InvocationListener listener) {
AbstractProxyManager apm = new AsmProxyManager();
return getProxyInstance(proxyClass, new ProxyHandler(apm, new SingleInstanceDispatcher(getProxyInstance(proxyClass)), listener));
}
@Override
protected Object getP3() {
return new ProxyTestClassGeneral();
}
private Callable<Object> constantly(final Object result) {
return new Callable<Object>() {
public Object call() throws Exception {
return result;
}
};
}
}
| 7,789 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassStaticInitOfChild.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassStaticInitOfChild extends ProxyTestClassStaticInitOfChildParent
{
public ProxyTestClassStaticInitOfChild(){
super("test");
}
}
| 7,790 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableSuperWithFinalMethod.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassUnweavableSuperWithFinalMethod extends ProxyTestClassUnweavableGrandParent {
public ProxyTestClassUnweavableSuperWithFinalMethod(int i) {
super(i);
}
public final String doStuff2() {
return "Hello!";
}
}
| 7,791 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/InterfaceProxyingTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.aries.blueprint.proxy.AbstractProxyTest.TestListener;
import org.apache.aries.blueprint.proxy.complex.AriesTransactionManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.interfaces.InterfaceProxyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
@SuppressWarnings("unchecked")
public class InterfaceProxyingTest {
public final static class TestCallable implements Callable<Object> {
private Object list = new Callable<Object>() {
public Object call() throws Exception {
return null;
}
};
public Object call() throws Exception {
return list;
}
public void setReturn(Object o) {
list = o;
}
}
private Bundle testBundle;
@Before
public void setup() {
testBundle = Mockito.mock(Bundle.class);
BundleWiring bundleWiring = Mockito.mock(BundleWiring.class);
Mockito.when(testBundle.adapt(BundleWiring.class)).thenReturn(bundleWiring);
}
@Test
public void testGetProxyInstance1() throws Exception{
Collection<Class<?>> classes = new ArrayList<Class<?>>(Arrays.asList(Closeable.class));
Object o = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(null), null);
assertTrue(o instanceof Closeable);
}
@Test
public void testGetProxyInstance2() throws Exception{
Collection<Class<? extends Object>> classes = Arrays.asList(Closeable.class, Iterable.class, Map.class);
Object o = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(null), null);
assertTrue(o instanceof Closeable);
assertTrue(o instanceof Iterable);
assertTrue(o instanceof Map);
}
/**
* Test a class whose super couldn't be woven
*/
@Test
public void testDelegationAndInterception() throws Exception
{
Collection<Class<?>> classes = new ArrayList<Class<?>>(Arrays.asList(Callable.class));
TestListener tl = new TestListener();
TestCallable tc = new TestCallable();
Callable<Object> o = (Callable<Object>) InterfaceProxyGenerator.getProxyInstance(testBundle,
null, classes, tc, tl);
assertCalled(tl, false, false, false);
assertNull(null, o.call());
assertCalled(tl, true, true, false);
assertEquals(Callable.class.getMethod("call"),
tl.getLastMethod());
tl.clear();
assertCalled(tl, false, false, false);
tc.setReturn(new Callable<Object>() {
public Object call() throws Exception {
throw new RuntimeException();
}
});
try {
o.call();
fail("Should throw an exception");
} catch (RuntimeException re) {
assertCalled(tl, true, false, true);
assertSame(re, tl.getLastThrowable());
}
tl.clear();
assertCalled(tl, false, false, false);
tc.setReturn(new Callable<Object>() {
public Object call() throws Exception {
try {
throw new RuntimeException();
} catch (RuntimeException re) {
return new Object();
}
}
});
try {
assertNotNull(o.call());
} finally {
assertCalled(tl, true, true, false);
}
}
@Test
public void testCaching() throws Exception {
Collection<Class<?>> classes = new ArrayList<Class<?>>(Arrays.asList(Closeable.class));
Object o1 = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(null), null);
Object o2 = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(null), null);
assertSame(o1.getClass(), o2.getClass());
}
@Test
public void testComplexInterface() throws Exception {
Collection<Class<?>> classes = new ArrayList<Class<?>>(Arrays.asList(ProxyTestInterface.class));
final TestCallable tc = new TestCallable();
tc.setReturn(5);
Object o = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(tc), null);
assertTrue(o instanceof ProxyTestInterface);
assertTrue(o instanceof Callable);
assertEquals(5, ((Callable<Object>)o).call());
}
@Test
public void testHandlesObjectMethods() throws Exception {
TestListener listener = new TestListener();
List<String> list = Arrays.asList("one", "two", "three");
Object proxied = InterfaceProxyGenerator.getProxyInstance(testBundle, null, Arrays.<Class<?>>asList(List.class), constantly(list), listener);
// obeys hashCode and equals, they *are* on the interface (actually they're
// on several interfaces, we process them in alphabetical order, so Collection
// comes ahead of List.
assertTrue(proxied.equals(Arrays.asList("one", "two", "three")));
assertEquals(Collection.class.getMethod("equals", Object.class), listener.getLastMethod());
listener.clear();
assertEquals(Arrays.asList("one", "two", "three").hashCode(), proxied.hashCode());
assertEquals(Collection.class.getMethod("hashCode"), listener.getLastMethod());
listener.clear();
// and toString
assertEquals(list.toString(), proxied.toString());
assertEquals(Object.class.getMethod("toString"), listener.getLastMethod());
listener.clear();
Runnable runnable = new Runnable() {
public void run() {}
};
proxied = InterfaceProxyGenerator.getProxyInstance(testBundle, null, Arrays.<Class<?>>asList(Runnable.class), constantly(runnable), listener);
// obeys hashCode and equals, they *are not* on the interface
assertTrue(proxied.equals(runnable));
assertEquals(Object.class.getMethod("equals", Object.class), listener.getLastMethod());
listener.clear();
assertEquals(runnable.hashCode(), proxied.hashCode());
assertEquals(Object.class.getMethod("hashCode"), listener.getLastMethod());
listener.clear();
}
private static class TestClassLoader extends ClassLoader {
public TestClassLoader() throws Exception {
InputStream is = TestClassLoader.class.getClassLoader().getResourceAsStream("org/apache/aries/blueprint/proxy/TestInterface.class");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int b;
while ((b = is.read()) != -1) {
bout.write(b);
}
is.close();
byte[] bytes = bout.toByteArray();
defineClass("org.apache.aries.blueprint.proxy.TestInterface", bytes, 0, bytes.length);
}
}
@Test
public void testNoStaleProxiesForRefreshedBundle() throws Exception {
Bundle bundle = mock(Bundle.class);
TestClassLoader loader = new TestClassLoader();
when(bundle.getLastModified()).thenReturn(10l);
BundleWiring wiring = AbstractProxyTest.getWiring(loader);
when(bundle.adapt(BundleWiring.class)).thenReturn(wiring);
Class<?> clazz = loader.loadClass("org.apache.aries.blueprint.proxy.TestInterface");
Object proxy = InterfaceProxyGenerator.getProxyInstance(bundle, null, Arrays.<Class<?>>asList(clazz), constantly(null), null);
assertTrue(clazz.isInstance(proxy));
ClassLoader parent1 = proxy.getClass().getClassLoader().getParent();
/* Now again but with a changed classloader as if the bundle had refreshed */
TestClassLoader loaderToo = new TestClassLoader();
when(bundle.getLastModified()).thenReturn(20l);
// let's change the returned revision
BundleWiring wiring2 = AbstractProxyTest.getWiring(loaderToo);
when(bundle.adapt(BundleWiring.class)).thenReturn(wiring2);
Class<?> clazzToo = loaderToo.loadClass("org.apache.aries.blueprint.proxy.TestInterface");
Object proxyToo = InterfaceProxyGenerator.getProxyInstance(bundle, null, Arrays.<Class<?>>asList(clazzToo), constantly(null), null);
assertTrue(clazzToo.isInstance(proxyToo));
ClassLoader parent2= proxyToo.getClass().getClassLoader().getParent();
//
assertTrue("parents should be different, as the are the classloaders of different bundle revisions", parent1 != parent2);
}
// Test for https://issues.apache.org/jira/browse/ARIES-1618
@Test
public void checkDuplicateInterfaces() throws UnableToProxyException
{
Collection<Class<?>> classes = Collections.<Class<?>>singletonList(AriesTransactionManager.class);
Object o = InterfaceProxyGenerator.getProxyInstance(testBundle, null, classes, constantly(null), null);
assertTrue(o instanceof AriesTransactionManager);
}
protected void assertCalled(TestListener listener, boolean pre, boolean post, boolean ex) {
assertEquals(pre, listener.preInvoke);
assertEquals(post, listener.postInvoke);
assertEquals(ex, listener.postInvokeExceptionalReturn);
}
private Callable<Object> constantly(final Object result) {
return new Callable<Object>() {
public Object call() throws Exception {
return result;
}
};
}
}
| 7,792 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassGeneric.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassGeneric extends ProxyTestClassGenericSuper<String>
{
public void setSomething(String s)
{
super.setSomething(s);
}
}
| 7,793 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyGeneratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassInner;
import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassStaticInner;
import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassUnweavableInnerChild;
import org.apache.aries.blueprint.proxy.pkg.ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.AsmProxyManager;
import org.apache.aries.proxy.impl.SingleInstanceDispatcher;
import org.apache.aries.proxy.impl.SystemModuleClassLoader;
import org.apache.aries.proxy.impl.gen.ProxySubclassMethodHashSet;
import org.apache.aries.proxy.impl.weaving.WovenProxyGenerator;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.junit.BeforeClass;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
@SuppressWarnings({"unchecked", "rawtypes"})
public class WovenProxyGeneratorTest extends AbstractProxyTest
{
private static final String hexPattern = "[0-9_a-f]";
private static final int[] uuid_pattern = new int[] {8,4,4,4,12};
private static final String regexp;
static {
StringBuilder sb = new StringBuilder(".*");
for(int i : uuid_pattern) {
for(int j = 0; j < i; j++){
sb.append(hexPattern);
}
sb.append("_");
}
sb.deleteCharAt(sb.length() -1);
sb.append("\\d*");
regexp = sb.toString();
}
/** An array of classes that will be woven - note no UnweavableParents should be in here! */
private static final List<Class<?>> CLASSES = Arrays.asList(new Class<?>[]{ProxyTestClassGeneral.class, ProxyTestClassSuper.class,
ProxyTestClassFinalMethod.class, ProxyTestClassFinal.class, ProxyTestClassGeneric.class,
ProxyTestClassGenericSuper.class, ProxyTestClassCovariant.class, ProxyTestClassCovariantOverride.class,
ProxyTestClassUnweavableChild.class, ProxyTestClassUnweavableSibling.class, ProxyTestClassInner.class,
ProxyTestClassStaticInner.class, ProxyTestClassUnweavableInnerChild.class,
ProxyTestClassUnweavableChildWithFinalMethodParent.class,
ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent.class,
ProxyTestClassSerializable.class, ProxyTestClassSerializableWithSVUID.class,
ProxyTestClassSerializableChild.class, ProxyTestClassSerializableInterface.class,
ProxyTestClassStaticInitOfChild.class, ProxyTestClassAbstract.class});
/** An array of classes that are loaded by the WeavingLoader, but not actually woven **/
private static final List<Class<?>> OTHER_CLASSES = Arrays.asList(new Class<?>[] {ProxyTestClassUnweavableSuper.class,
ProxyTestClassStaticInitOfChildParent.class, ProxyTestClassChildOfAbstract.class});
private static final Map<String, byte[]> rawClasses = new HashMap<String, byte[]>();
protected static final ClassLoader weavingLoader = new SystemModuleClassLoader() {
public Class<?> loadClass(String className) throws ClassNotFoundException
{
return loadClass(className, false);
}
public Class<?> loadClass(String className, boolean b) throws ClassNotFoundException
{
if (!!!className.startsWith("org.apache.aries.blueprint.proxy.ProxyTest")){
return Class.forName(className);
}
Class<?> clazz = findLoadedClass(className);
if(clazz != null)
return clazz;
byte[] bytes = rawClasses.get(className);
if(bytes == null)
return super.loadClass(className, b);
boolean weave = false;
for(Class<?> c : CLASSES) {
if(c.getName().equals(className)) {
weave = true;
break;
}
}
if(weave)
bytes = WovenProxyGenerator.getWovenProxy(bytes, this);
return defineClass(className, bytes, 0, bytes.length);
}
protected URL findResource(String resName) {
return WovenProxyGeneratorTest.class.getResource(resName);
}
};
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUp() throws Exception
{
List<Class<?>> classes = new ArrayList<Class<?>>(CLASSES.size() + OTHER_CLASSES.size());
classes.addAll(CLASSES);
classes.addAll(OTHER_CLASSES);
for(Class<?> clazz : classes) {
InputStream is = clazz.getClassLoader().getResourceAsStream(
clazz.getName().replace('.', '/') + ".class");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int read = is.read(buffer);
while(read != -1) {
baos.write(buffer, 0, read);
read = is.read(buffer);
}
rawClasses.put(clazz.getName(), baos.toByteArray());
}
}
/**
* This test uses the WovenProxyGenerator to generate and load the specified getTestClass().
*
* Once the subclass is generated we check that it wasn't null.
*
* Test method for
* {@link WovenProxyGenerator#getProxySubclass(byte[], String)}.
*/
@Test
public void testGenerateAndLoadProxy() throws Exception
{
super.testGenerateAndLoadProxy();
assertTrue("Should be a WovenProxy", WovenProxy.class.isAssignableFrom(getProxyClass(getTestClass())));
}
/**
* Test that the methods found declared on the generated proxy are
* the ones that we expect.
*/
@Test
public void testExpectedMethods() throws Exception
{
ProxySubclassMethodHashSet<String> originalMethods = getMethods(getTestClass());
ProxySubclassMethodHashSet<String> generatedMethods = getMethods(weavingLoader.
loadClass(getTestClass().getName()));
// check that all the methods we have generated were expected
for (String gen : generatedMethods) {
assertTrue("Unexpected method: " + gen, originalMethods.contains(gen));
}
// check that all the expected methods were generated
for (String exp : originalMethods) {
assertTrue("Method was not generated: " + exp, generatedMethods.contains(exp));
}
// check the sets were the same
assertEquals("Sets were not the same", originalMethods, generatedMethods);
}
private ProxySubclassMethodHashSet<String> getMethods(Class<?> clazz) {
ProxySubclassMethodHashSet<String> foundMethods =
new ProxySubclassMethodHashSet<String>(12);
do {
Method[] declaredMethods = clazz.getDeclaredMethods();
List<Method> listOfDeclaredMethods = new ArrayList<Method>();
for (Method m : declaredMethods) {
if(m.getName().startsWith(WovenProxy.class.getName().replace('.', '_')) ||
m.getName().startsWith("getListener") || m.getName().startsWith("getInvocationTarget") ||
//four hex digits
m.getName().matches(regexp))
continue;
listOfDeclaredMethods.add(m);
}
declaredMethods = listOfDeclaredMethods.toArray(new Method[] {});
foundMethods.addMethodArray(declaredMethods);
clazz = clazz.getSuperclass();
} while (clazz != null);
return foundMethods;
}
/**
* Test a method marked final
*/
@Test
public void testFinalMethod() throws Exception
{
assertNotNull(weavingLoader.loadClass(ProxyTestClassFinalMethod.class
.getName()));
}
/**
* Test a class marked final
*/
@Test
public void testFinalClass() throws Exception
{
assertNotNull(weavingLoader.loadClass(ProxyTestClassFinal.class
.getName()));
}
/**
* Test a private constructor
*/
@Test
public void testPrivateConstructor() throws Exception
{
assertNotNull(weavingLoader.loadClass(ProxyTestClassFinal.class
.getName()));
}
/**
* Test a class whose super couldn't be woven
*/
@Test
public void testUnweavableSuper() throws Exception
{
Class<?> woven = getProxyClass(ProxyTestClassUnweavableChild.class);
assertNotNull(woven);
assertNotNull(getProxyInstance(woven));
TestListener tl = new TestListener();
Object ptcuc = getProxyInstance(woven, tl);
assertCalled(tl, false, false, false);
Method m = ptcuc.getClass().getMethod("doStuff");
assertEquals("Hi!", m.invoke(ptcuc));
assertCalled(tl, true, true, false);
assertEquals(ProxyTestClassUnweavableGrandParent.class.getMethod("doStuff"),
tl.getLastMethod());
tl.clear();
//Because default access works on the package, and we are defined on a different classloader
//we have to call setAccessible...
m = getDeclaredMethod(ProxyTestClassUnweavableChild.class, "doStuff2");
m.setAccessible(true);
assertEquals("Hello!", m.invoke(ptcuc));
assertCalled(tl, true, true, false);
assertEquals(weavingLoader.loadClass(ProxyTestClassUnweavableSuper.class.getName()).getDeclaredMethod("doStuff2"),
tl.getLastMethod());
}
@Test
public void testUnweavableSuperWithNoNoargsAllTheWay() throws Exception
{
try {
getProxyClass(ProxyTestClassUnweavableSibling.class);
fail();
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof UnableToProxyException);
assertEquals(ProxyTestClassUnweavableSibling.class.getName(),
((UnableToProxyException)re.getCause()).getClassName());
}
}
/**
* Test a class whose super couldn't be woven
*/
@Test
public void testUnweavableSuperWithFinalMethod() throws Exception
{
try{
getProxyClass(ProxyTestClassUnweavableChildWithFinalMethodParent.class);
fail();
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof FinalModifierException);
assertEquals(ProxyTestClassUnweavableSuperWithFinalMethod.class.getName(),
((FinalModifierException)re.getCause()).getClassName());
assertEquals("doStuff2", ((FinalModifierException)re.getCause())
.getFinalMethods());
}
}
/**
* Test a class whose super couldn't be woven
*/
@Test
public void testUnweavableSuperWithDefaultMethodInWrongPackage() throws Exception
{
try{
getProxyClass(ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent.class);
fail();
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof UnableToProxyException);
assertEquals(ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent
.class.getName(), ((UnableToProxyException)re.getCause()).getClassName());
}
}
@Test
public void testInnerWithNoParentNoArgs() throws Exception {
//An inner class has no no-args (the parent gets added as an arg) so we can't
//get an instance
try{
getProxyClass(ProxyTestClassUnweavableInnerChild.class);
fail();
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof UnableToProxyException);
assertEquals(ProxyTestClassUnweavableInnerChild.class.getName(),
((UnableToProxyException)re.getCause()).getClassName());
}
}
@Test(expected=NoSuchFieldException.class)
public void testNonSerializableClassHasNoGeneratedSerialVersionUID() throws Exception {
Class<?> woven = getProxyClass(getTestClass());
woven.getDeclaredField("serialVersionUID");
}
@Test
public void testSerialization() throws Exception {
ProxyTestClassSerializable in = new ProxyTestClassSerializable();
in.value = 5;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(in);
ProxyTestClassSerializable.checkDeserialization(baos.toByteArray(), 5);
Class<?> woven = getProxyClass(ProxyTestClassSerializable.class);
woven.getMethod("checkDeserialization", byte[].class, int.class).invoke(null, baos.toByteArray(), 5);
}
@Test
public void testInheritedSerialization() throws Exception {
ProxyTestClassSerializableChild in = new ProxyTestClassSerializableChild();
in.value = 4;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(in);
ProxyTestClassSerializable.checkDeserialization(baos.toByteArray(), 4);
Class<?> woven = getProxyClass(ProxyTestClassSerializable.class);
woven.getMethod("checkDeserialization", byte[].class, int.class).invoke(null, baos.toByteArray(), 4);
}
@Test
public void testInterfaceInheritedSerialization() throws Exception {
ProxyTestClassSerializableInterface in = new ProxyTestClassSerializableInterface();
in.value = 3;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(in);
ProxyTestClassSerializableInterface.checkDeserialization(baos.toByteArray(), 3);
Class<?> woven = getProxyClass(ProxyTestClassSerializableInterface.class);
woven.getMethod("checkDeserialization", byte[].class, int.class).invoke(null, baos.toByteArray(), 3);
}
@Test
public void testGeneratedSVUIDisSynthetic() throws Exception {
Class<?> woven = getProxyClass(ProxyTestClassSerializable.class);
assertTrue(woven.getDeclaredField("serialVersionUID").isSynthetic());
woven = getProxyClass(ProxyTestClassSerializableWithSVUID.class);
assertFalse(woven.getDeclaredField("serialVersionUID").isSynthetic());
}
/**
* This test covers a weird case on Mac VMs where we sometimes
* get a ClassCircularityError if a static initializer in a
* non-woven superclass references a subclass that's being
* woven, and gets triggered by the weaving process. Not known
* to fail on IBM or Sun/Oracle VMs
*/
@Test
public void testSuperStaticInitOfChild() throws Exception {
Class<?> parent = weavingLoader.loadClass(ProxyTestClassStaticInitOfChildParent.class.getName());
parent.getMethod("doStuff").invoke(null);
}
@Override
protected Object getProxyInstance(Class<?> proxyClass) {
try {
if(proxyClass.getName().equals(ProxyTestClassAbstract.class.getName())) {
Collection<Class<?>> coll = new ArrayList<Class<?>>();
coll.add(proxyClass);
return new AsmProxyManager().createNewProxy(null, coll, new Callable() {
public Object call() throws Exception {
return null;
}}, null);
}
return proxyClass.newInstance();
} catch (Exception e) {
return null;
}
}
@Override
protected Class<?> getProxyClass(Class<?> clazz) {
try {
return weavingLoader.loadClass(clazz.getName());
} catch (ClassNotFoundException e) {
return null;
}
}
@Override
protected Object setDelegate(Object proxy, Callable<Object> dispatcher) {
return ((WovenProxy) proxy).
org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
dispatcher, null);
}
@Override
protected Object getProxyInstance(Class<?> proxyClass,
InvocationListener listener) {
WovenProxy proxy = (WovenProxy) getProxyInstance(proxyClass);
proxy = proxy.org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
new SingleInstanceDispatcher(proxy), listener);
return proxy;
}
protected Object getP3() {
return getProxyInstance(getProxyClass(getTestClass()));
}
/**
* This tests that the Synthesizer ran correctly and the packaged
* WovenProxy class has been modified with the synthetic modifier
*/
@Test
public void testWovenProxyIsSynthetic(){
assertTrue(WovenProxy.class.isSynthetic());
}
/**
* This test checks that we can add interfaces to classes that don't implement
* them using dynamic subclassing. This is a little odd, but it came for
* free with support for proxying abstract classes!
* @throws Exception
*/
@Test
public void testWovenClassPlusInterfaces() throws Exception {
Bundle b = mock(Bundle.class);
BundleWiring wiring = getWiring(weavingLoader);
when(b.adapt(BundleWiring.class)).thenReturn(wiring);
Object toCall = new AsmProxyManager().createDelegatingProxy(b, Arrays.asList(
getProxyClass(ProxyTestClassAbstract.class), Callable.class), new Callable() {
public Object call() throws Exception {
return weavingLoader.loadClass(ProxyTestClassChildOfAbstract.class.getName()).newInstance();
}
}, null);
//Should proxy the abstract method on the class
Method m = getProxyClass(ProxyTestClassAbstract.class).getMethod("getMessage");
assertEquals("Working", m.invoke(toCall));
//Should be a callable too!
assertEquals("Callable Works too!", ((Callable)toCall).call());
}
}
| 7,794 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassGeneral.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassGeneral extends ProxyTestClassSuper
{
public String testMethod(String x, int y, Object z)
{
somePrivateMethod();
return x;
}
public String testArgs(double a, short b, long c, char d, byte e, boolean f)
{
return Character.toString(d);
}
protected void testReturnVoid()
{
}
int testReturnInt()
{
return 17;
}
public Integer testReturnInteger()
{
return Integer.valueOf(1);
}
private void somePrivateMethod()
{
}
public boolean equals(Object o) {
return o == this;
}
public void testException() {
throw new RuntimeException();
}
public void testInternallyCaughtException() {
try {
try {
throw new RuntimeException();
} catch (RuntimeException re) {
// no op
}
} catch (Exception e) {
}
}
}
| 7,795 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassCovariantOverride.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassCovariantOverride extends ProxyTestClassCovariant
{
//this method is here to make sure we don't break on covariant override
public ProxyTestClassCovariantOverride getCovariant()
{
return this;
}
}
| 7,796 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import org.apache.aries.blueprint.proxy.pkg.ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent;
public class ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent extends ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent{
}
| 7,797 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/TestInterface.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public interface TestInterface {
public Object call(Object argument);
}
| 7,798 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassPackageAccessCtor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassPackageAccessCtor {
int[] arr;
String str;
boolean bool;
/* Test with package access constructor
*
*/
ProxyTestClassPackageAccessCtor(int[] a, String s, boolean b) {
arr=a;
str=s;
bool=b;
};
public String getMessage() {
return str;
}
}
| 7,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.