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/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/WorkerContext.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.geronimo.connector.work;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.NotSupportedException;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.WorkContext;
import jakarta.resource.spi.work.WorkContextErrorCodes;
import jakarta.resource.spi.work.WorkContextProvider;
import jakarta.resource.spi.work.TransactionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkAdapter;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.resource.spi.work.WorkEvent;
import jakarta.resource.spi.work.WorkException;
import jakarta.resource.spi.work.WorkListener;
import jakarta.resource.spi.work.WorkManager;
import jakarta.resource.spi.work.WorkRejectedException;
/**
* Work wrapper providing an execution context to a Work instance.
*
* @version $Rev$ $Date$
*/
public class WorkerContext implements Work {
private static final Logger log = Logger.getLogger(WorkerContext.class.getName());
private static final List<WorkContext> NO_INFLOW_CONTEXT = Collections.emptyList();
/**
* Null WorkListener used as the default WorkListener.
*/
private static final WorkListener NULL_WORK_LISTENER = new WorkAdapter() {
public void workRejected(WorkEvent event) {
if (event.getException() != null) {
if (event.getException() instanceof WorkCompletedException && event.getException().getCause() != null) {
log.log(Level.SEVERE, event.getWork().toString(), event.getException().getCause());
} else {
log.log(Level.SEVERE, event.getWork().toString(), event.getException());
}
}
}
};
/**
* Priority of the thread, which will execute this work.
*/
private int threadPriority;
/**
* Actual work to be executed.
*/
private Work adaptee;
/**
* Indicates if this work has been accepted.
*/
private boolean isAccepted;
/**
* System.currentTimeMillis() when the wrapped Work has been accepted.
*/
private long acceptedTime;
/**
* Number of times that the execution of this work has been tried.
*/
private int nbRetry;
/**
* Time duration (in milliseconds) within which the execution of the Work
* instance must start.
*/
private long startTimeOut;
/**
* Listener to be notified during the life-cycle of the work treatment.
*/
private final WorkListener workListener;
/**
* Work exception, if any.
*/
private WorkException workException;
/**
* A latch, which is released when the work is started.
*/
private CountDownLatch startLatch = new CountDownLatch(1);
/**
* A latch, which is released when the work is completed.
*/
private CountDownLatch endLatch = new CountDownLatch(1);
/**
* Execution context of the actual work to be executed.
*/
private final ExecutionContext executionContext;
private final List<WorkContextHandler> workContextHandlers;
/**
* Create a WorkWrapper.
* TODO include a WorkContextLifecycleListener
* @param work Work to be wrapped.
* @param workContextHandlers WorkContextHandlers supported by this work manager
*/
public WorkerContext(Work work, Collection<WorkContextHandler> workContextHandlers) {
adaptee = work;
this.workContextHandlers = new ArrayList<WorkContextHandler>(workContextHandlers);
executionContext = null;
workListener = NULL_WORK_LISTENER;
}
/**
* Create a WorkWrapper with the specified execution context.
*
* TODO include a WorkContextLifecycleListener
* @param aWork Work to be wrapped.
* @param aStartTimeout a time duration (in milliseconds) within which the
* execution of the Work instance must start.
* @param execContext an object containing the execution context with which
* the submitted Work instance must be executed.
* @param workListener an object which would be notified when the various
* @param workContextHandlers WorkContextHandlers supported by this work manager
* @throws jakarta.resource.spi.work.WorkRejectedException if executionContext supplied yet Work implements WorkContextProvider
*/
public WorkerContext(Work aWork,
long aStartTimeout,
ExecutionContext execContext,
WorkListener workListener, Collection<WorkContextHandler> workContextHandlers) throws WorkRejectedException {
adaptee = aWork;
startTimeOut = aStartTimeout;
if (null == workListener) {
this.workListener = NULL_WORK_LISTENER;
} else {
this.workListener = workListener;
}
if (aWork instanceof WorkContextProvider) {
if (execContext != null) {
throw new WorkRejectedException("Execution context provided but Work implements WorkContextProvider");
}
executionContext = null;
} else {
executionContext = execContext;
}
this.workContextHandlers = new ArrayList<WorkContextHandler>(workContextHandlers);
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.Work#release()
*/
public void release() {
adaptee.release();
}
/**
* Defines the thread priority level of the thread, which will be dispatched
* to process this work. This priority level must be the same one for a
* given resource adapter.
*
* @param aPriority Priority of the thread to be used to process the wrapped
* Work instance.
*/
public void setThreadPriority(int aPriority) {
threadPriority = aPriority;
}
/**
* Gets the priority level of the thread, which will be dispatched
* to process this work. This priority level must be the same one for a
* given resource adapter.
*
* @return The priority level of the thread to be dispatched to
* process the wrapped Work instance.
*/
public int getThreadPriority() {
return threadPriority;
}
/**
* Call-back method used by a Work executor in order to notify this
* instance that the wrapped Work instance has been accepted.
*
* @param anObject Object on which the event initially occurred. It should
* be the work executor.
*/
public synchronized void workAccepted(Object anObject) {
isAccepted = true;
acceptedTime = System.currentTimeMillis();
workListener.workAccepted(new WorkEvent(anObject,
WorkEvent.WORK_ACCEPTED, adaptee, null));
}
/**
* System.currentTimeMillis() when the Work has been accepted. This method
* can be used to compute the duration of a work.
*
* @return When the work has been accepted.
*/
public synchronized long getAcceptedTime() {
return acceptedTime;
}
/**
* Gets the time duration (in milliseconds) within which the execution of
* the Work instance must start.
*
* @return Time out duration.
*/
public long getStartTimeout() {
return startTimeOut;
}
/**
* Used by a Work executor in order to know if this work, which should be
* accepted but not started has timed out. This method MUST be called prior
* to retry the execution of a Work.
*
* @return true if the Work has timed out and false otherwise.
*/
public synchronized boolean isTimedOut() {
assert isAccepted : "The work is not accepted.";
// A value of 0 means that the work never times out.
//??? really?
if (0 == startTimeOut || startTimeOut == WorkManager.INDEFINITE) {
return false;
}
boolean isTimeout = acceptedTime + startTimeOut > 0 &&
System.currentTimeMillis() > acceptedTime + startTimeOut;
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, this
+ " accepted at "
+ acceptedTime
+ (isTimeout ? " has timed out." : " has not timed out. ")
+ nbRetry
+ " retries have been performed.");
}
if (isTimeout) {
workException = new WorkRejectedException(this + " has timed out.",
WorkException.START_TIMED_OUT);
workListener.workRejected(new WorkEvent(this,
WorkEvent.WORK_REJECTED,
adaptee,
workException));
return true;
}
nbRetry++;
return isTimeout;
}
/**
* Gets the WorkException, if any, thrown during the execution.
*
* @return WorkException, if any.
*/
public synchronized WorkException getWorkException() {
return workException;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
if (isTimedOut()) {
// In case of a time out, one releases the start and end latches
// to prevent a dead-lock.
startLatch.countDown();
endLatch.countDown();
return;
}
// Implementation note: the work listener is notified prior to release
// the start lock. This behavior is intentional and seems to be the
// more conservative.
workListener.workStarted(new WorkEvent(this, WorkEvent.WORK_STARTED, adaptee, null));
startLatch.countDown();
//Implementation note: we assume this is being called without an interesting TransactionContext,
//and ignore/replace whatever is associated with the current thread.
try {
List<WorkContext> workContexts = NO_INFLOW_CONTEXT;
if (executionContext != null) {
TransactionContext txWorkContext = new TransactionContext();
try {
txWorkContext.setTransactionTimeout(executionContext.getTransactionTimeout());
} catch (NotSupportedException e) {
//not set, continue to not set it.
}
txWorkContext.setXid(executionContext.getXid());
workContexts = Collections.<WorkContext>singletonList(txWorkContext);
log.info("Translated ExecutionContext to TransactionContext");
} else if (adaptee instanceof WorkContextProvider) {
workContexts = ((WorkContextProvider) adaptee).getWorkContexts();
}
List<WorkContextHandler> sortedHandlers = new ArrayList<WorkContextHandler>(workContexts.size());
for (WorkContext workContext : workContexts) {
boolean found = false;
for (Iterator<WorkContextHandler> it = workContextHandlers.iterator(); it.hasNext();) {
WorkContextHandler workContextHandler = it.next();
log.info("sorting WorkContextHandler: " + workContextHandler + " for work context: " + workContext);
if (workContextHandler.supports(workContext.getClass())) {
it.remove();
log.info("adding sorted WorkContextHandler: " + workContextHandler);
sortedHandlers.add(workContextHandler);
found = true;
break;
}
}
if (!found) {
for (WorkContextHandler workContextHandler: sortedHandlers) {
if (workContextHandler.supports(workContext.getClass())) {
throw new WorkCompletedException("Duplicate WorkContext: " + workContext, WorkContextErrorCodes.DUPLICATE_CONTEXTS);
}
}
throw new WorkCompletedException("Unhandled WorkContext: " + workContext, WorkContextErrorCodes.UNSUPPORTED_CONTEXT_TYPE);
}
}
for (Iterator<WorkContextHandler> it = workContextHandlers.iterator(); it.hasNext();) {
WorkContextHandler workContextHandler = it.next();
if (!workContextHandler.required()) {
log.info("Removing non-required WorkContextHandler with no context: " + workContextHandler);
it.remove();
}
}
// TODO use a WorkContextLifecycleListener
int i = 0;
for (WorkContext workContext : workContexts) {
WorkContextHandler contextHandler = sortedHandlers.get(i++);
log.info("calling before on WorkContextHandler: " + contextHandler + " with workContext: " + workContext);
contextHandler.before(workContext);
}
for (WorkContextHandler workContextHandler: workContextHandlers) {
log.info("calling before on WorkContextHandler: " + workContextHandler + " with null workContext");
workContextHandler.before(null);
}
try {
adaptee.run();
} finally {
int j = 0;
for (WorkContext workContext : workContexts) {
WorkContextHandler contextHandler = sortedHandlers.get(j++);
log.info("calling after on WorkContextHandler: " + contextHandler + " with workContext: " + workContext);
contextHandler.after(workContext);
}
for (WorkContextHandler workContextHandler: workContextHandlers) {
log.info("calling after on WorkContextHandler: " + workContextHandler + " with null workContext");
workContextHandler.after(null);
}
}
workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, adaptee, null));
} catch (Throwable e) {
workException = (WorkException) (e instanceof WorkCompletedException ? e : new WorkCompletedException("Unknown error", WorkCompletedException.UNDEFINED).initCause(e));
workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_REJECTED, adaptee,
workException));
} finally {
endLatch.countDown();
}
}
/**
* Provides a latch, which can be used to wait the start of a work
* execution.
*
* @return Latch that a caller can acquire to wait for the start of a
* work execution.
*/
public synchronized CountDownLatch provideStartLatch() {
return startLatch;
}
/**
* Provides a latch, which can be used to wait the end of a work
* execution.
*
* @return Latch that a caller can acquire to wait for the end of a
* work execution.
*/
public synchronized CountDownLatch provideEndLatch() {
return endLatch;
}
public String toString() {
return "Work :" + adaptee;
}
}
| 6,400 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/WorkExecutor.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.geronimo.connector.work.pool;
import java.util.concurrent.Executor;
import jakarta.resource.spi.work.WorkException;
import org.apache.geronimo.connector.work.WorkerContext;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface WorkExecutor {
/**
* This method must be implemented by sub-classes in order to provide the
* relevant synchronization policy. It is called by the executeWork template
* method.
*
* @param work Work to be executed.
*
* @throws jakarta.resource.spi.work.WorkException Indicates that the work has failed.
* @throws InterruptedException Indicates that the thread in charge of the
* execution of the specified work has been interrupted.
*/
void doExecute(WorkerContext work, Executor executor)
throws WorkException, InterruptedException;
}
| 6,401 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/SyncWorkExecutor.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.geronimo.connector.work.pool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import jakarta.resource.spi.work.WorkException;
import org.apache.geronimo.connector.work.WorkerContext;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class SyncWorkExecutor implements WorkExecutor {
public void doExecute(WorkerContext work, Executor executor)
throws WorkException, InterruptedException {
CountDownLatch latch = work.provideEndLatch();
executor.execute(new NamedRunnable("A J2EE Connector", work));
latch.await();
}
}
| 6,402 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/NullWorkExecutorPool.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.geronimo.connector.work.pool;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class NullWorkExecutorPool implements WorkExecutorPool {
private int maxSize;
public NullWorkExecutorPool(int maxSize) {
this.maxSize = maxSize;
}
public int getPoolSize() {
return 0;
}
public int getMaximumPoolSize() {
return maxSize;
}
public void setMaximumPoolSize(int maxSize) {
this.maxSize = maxSize;
}
public WorkExecutorPool start() {
return new WorkExecutorPoolImpl(maxSize);
}
public WorkExecutorPool stop() {
return this;
}
public void execute(Runnable command) {
throw new IllegalStateException("Stopped");
}
}
| 6,403 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/NamedRunnable.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.geronimo.connector.work.pool;
/**
* @version $Rev$ $Date$
*/
public class NamedRunnable implements Runnable {
private final String name;
private final Runnable runnable;
public NamedRunnable(String name, Runnable runnable) {
this.name = name;
this.runnable = runnable;
}
public void run() {
runnable.run();
}
public String toString() {
return name;
}
}
| 6,404 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/WorkExecutorPoolImpl.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.geronimo.connector.work.pool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Based class for WorkExecutorPool. Sub-classes define the synchronization
* policy (should the call block until the end of the work; or when it starts
* et cetera).
*
* @version $Rev$ $Date$
*/
public class WorkExecutorPoolImpl implements WorkExecutorPool {
/**
* A timed out pooled executor.
*/
private ThreadPoolExecutor pooledExecutor;
private static Logger log = Logger.getLogger(WorkExecutorPoolImpl.class.getName());
/**
* Creates a pool with the specified minimum and maximum sizes. The Channel
* used to enqueue the submitted Work instances is queueless synchronous
* one.
*
* @param maxSize Maximum size of the work executor pool.
*/
public WorkExecutorPoolImpl(int maxSize) {
pooledExecutor = new ThreadPoolExecutor(1, maxSize, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
/*
FIXME: How to do this with concurrent.util ?
pooledExecutor.waitWhenBlocked();
*/
}
/**
* Execute the specified Work.
*
* @param work Work to be executed.
*/
public void execute(Runnable work) {
if(pooledExecutor.getPoolSize() == pooledExecutor.getMaximumPoolSize()) {
log.log(Level.WARNING, "Maximum Pool size has been exceeded. Current Pool Size = "+pooledExecutor.getMaximumPoolSize());
}
pooledExecutor.execute(work);
}
/**
* Gets the size of this pool.
*/
public int getPoolSize() {
return pooledExecutor.getPoolSize();
}
/**
* Gets the maximum size of this pool.
*/
public int getMaximumPoolSize() {
return pooledExecutor.getMaximumPoolSize();
}
/**
* Sets the maximum size of this pool.
* @param maxSize New maximum size of this pool.
*/
public void setMaximumPoolSize(int maxSize) {
pooledExecutor.setMaximumPoolSize(maxSize);
}
public WorkExecutorPool start() {
throw new IllegalStateException("This pooled executor is already started");
}
/**
* Stops this pool. Prior to stop this pool, all the enqueued Work instances
* are processed. This is an orderly shutdown.
*/
public WorkExecutorPool stop() {
int maxSize = getMaximumPoolSize();
pooledExecutor.shutdown();
return new NullWorkExecutorPool(maxSize);
}
}
| 6,405 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/StartWorkExecutor.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.geronimo.connector.work.pool;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import jakarta.resource.spi.work.WorkException;
import org.apache.geronimo.connector.work.WorkerContext;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class StartWorkExecutor implements WorkExecutor {
public void doExecute(WorkerContext work, Executor executor)
throws WorkException, InterruptedException {
CountDownLatch latch = work.provideStartLatch();
executor.execute(new NamedRunnable("A J2EE Connector", work));
latch.await();
}
}
| 6,406 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/ScheduleWorkExecutor.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.geronimo.connector.work.pool;
import java.util.concurrent.Executor;
import jakarta.resource.spi.work.WorkException;
import org.apache.geronimo.connector.work.WorkerContext;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ScheduleWorkExecutor implements WorkExecutor {
public void doExecute(WorkerContext work, Executor executor)
throws WorkException, InterruptedException {
executor.execute(new NamedRunnable("A J2EE Connector", work));
}
}
| 6,407 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/pool/WorkExecutorPool.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.geronimo.connector.work.pool;
import java.util.concurrent.Executor;
/**
* Defines the operations that a pool in charge of the execution of Work
* instances must expose.
*
* @version $Rev$ $Date$
*/
public interface WorkExecutorPool extends Executor {
/**
* Gets the current number of active threads in the pool.
*
* @return Number of active threads in the pool.
*/
public int getPoolSize();
/**
* Gets the maximum number of threads to simultaneously execute.
*
* @return Maximum size.
*/
public int getMaximumPoolSize();
/**
* Sets the maximum number of threads to simultaneously execute.
*
* @param aSize Maximum size.
*/
public void setMaximumPoolSize(int aSize);
public WorkExecutorPool start();
public WorkExecutorPool stop();
}
| 6,408 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/PoolIdleReleaserTimer.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.geronimo.connector.outbound;
import java.util.Timer;
/**
* @version $Rev$ $Date$
*/
public class PoolIdleReleaserTimer {
private static final Timer timer = new Timer("PoolIdleReleaseTimer", true);
public static Timer getTimer() {
return timer;
}
}
| 6,409 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ThreadLocalCachingConnectionInterceptor.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.geronimo.connector.outbound;
import java.util.Collections;
import jakarta.resource.ResourceException;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ThreadLocalCachingConnectionInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final ThreadLocal<ManagedConnectionInfo> connections = new ThreadLocal<ManagedConnectionInfo>();
private final boolean matchConnections;
public ThreadLocalCachingConnectionInterceptor(final ConnectionInterceptor next, final boolean matchConnections) {
this.next = next;
this.matchConnections = matchConnections;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
if (connectionInfo.isUnshareable()) {
next.getConnection(connectionInfo);
return;
}
ManagedConnectionInfo managedConnectionInfo = connections.get();
if (managedConnectionInfo != null) {
if (matchConnections) {
ManagedConnectionInfo mciRequest = connectionInfo.getManagedConnectionInfo();
if (null != managedConnectionInfo.getManagedConnectionFactory().matchManagedConnections(
Collections.singleton(managedConnectionInfo.getManagedConnection()),
mciRequest.getSubject(),
mciRequest.getConnectionRequestInfo()
)) {
connectionInfo.setManagedConnectionInfo(managedConnectionInfo);
return;
} else {
//match failed, get a new cx after returning this one
connections.set(null);
next.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
}
} else {
connectionInfo.setManagedConnectionInfo(managedConnectionInfo);
return;
}
}
//nothing for this thread or match failed
next.getConnection(connectionInfo);
connections.set(connectionInfo.getManagedConnectionInfo());
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
if (connectionReturnAction == ConnectionReturnAction.DESTROY
|| connectionInfo.isUnshareable()
|| !connectionInfo.getManagedConnectionInfo().hasConnectionHandles()) {
if (connections.get() == connectionInfo.getManagedConnectionInfo()) {
connections.remove();
}
next.returnConnection(connectionInfo, connectionReturnAction);
}
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[matchConnections=").append(matchConnections).append("]\n");
next.info(s);
}
}
| 6,410 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/TxUtil.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.geronimo.connector.outbound;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
/**
* @version $Rev$ $Date$
*/
public final class TxUtil {
private TxUtil() {
}
public static Transaction getTransactionIfActive(TransactionManager transactionManager) {
Transaction transaction = null;
int status = Status.STATUS_NO_TRANSACTION;
try {
transaction = transactionManager.getTransaction();
if (transaction != null) status = transaction.getStatus();
} catch (SystemException ignored) {
}
if (transaction != null && status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK) {
return transaction;
}
return null;
}
public static boolean isTransactionActive(TransactionManager transactionManager) {
try {
int status = transactionManager.getStatus();
return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
} catch (SystemException ignored) {
return false;
}
}
public static boolean isActive(Transaction transaction) {
try {
int status = transaction.getStatus();
return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
} catch (SystemException ignored) {
return false;
}
}
}
| 6,411 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionTrackingInterceptor.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.geronimo.connector.outbound;
import java.util.Collection;
import java.util.Iterator;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.DissociatableManagedConnection;
import jakarta.resource.spi.ManagedConnection;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTracker;
/**
* ConnectionTrackingInterceptor.java handles communication with the
* CachedConnectionManager. On method call entry, cached handles are
* checked for the correct Subject. On method call exit, cached
* handles are disassociated if possible. On getting or releasing
* a connection the CachedConnectionManager is notified.
*
*
* @version $Rev$ $Date$
*/
public class ConnectionTrackingInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final String key;
private final ConnectionTracker connectionTracker;
public ConnectionTrackingInterceptor(
final ConnectionInterceptor next,
final String key,
final ConnectionTracker connectionTracker
) {
this.next = next;
this.key = key;
this.connectionTracker = connectionTracker;
}
/**
* called by: GenericConnectionManager.allocateConnection, GenericConnectionManager.associateConnection, and enter.
* in: connectionInfo is non-null, and has non-null ManagedConnectionInfo with non-null managedConnectionfactory.
* connection handle may or may not be null.
* out: connectionInfo has non-null connection handle, non null ManagedConnectionInfo with non-null ManagedConnection and GeronimoConnectionEventListener.
* connection tracker has been notified of handle-managed connection association.
* @param connectionInfo
* @throws ResourceException
*/
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
connectionTracker.setEnvironment(connectionInfo, key);
next.getConnection(connectionInfo);
connectionTracker.handleObtained(this, connectionInfo, false);
}
/**
* Called when a proxied connection which has been released need to be reassociated with a real connection.
*/
public void reassociateConnection(ConnectionInfo connectionInfo) throws ResourceException {
connectionTracker.setEnvironment(connectionInfo, key);
next.getConnection(connectionInfo);
connectionTracker.handleObtained(this, connectionInfo, true);
}
/**
* called by: GeronimoConnectionEventListener.connectionClosed, GeronimoConnectionEventListener.connectionErrorOccurred, exit
* in: handle has already been dissociated from ManagedConnection. connectionInfo not null, has non-null ManagedConnectionInfo, ManagedConnectionInfo has non-null ManagedConnection
* handle can be null if called from error in ManagedConnection in pool.
* out: connectionTracker has been notified, ManagedConnectionInfo null.
* @param connectionInfo
* @param connectionReturnAction
*/
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
connectionTracker.handleReleased(this, connectionInfo, connectionReturnAction);
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void enter(Collection<ConnectionInfo> connectionInfos) throws ResourceException {
for (ConnectionInfo connectionInfo : connectionInfos) {
next.getConnection(connectionInfo);
}
}
public void exit(Collection<ConnectionInfo> connectionInfos)
throws ResourceException {
for (Iterator<ConnectionInfo> iterator = connectionInfos.iterator(); iterator.hasNext();) {
ConnectionInfo connectionInfo = iterator.next();
if (connectionInfo.isUnshareable()) {
//if one is, they all are
return;
}
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
ManagedConnection managedConnection = managedConnectionInfo.getManagedConnection();
if (managedConnection instanceof DissociatableManagedConnection
&& managedConnectionInfo.isFirstConnectionInfo(connectionInfo)) {
iterator.remove();
((DissociatableManagedConnection) managedConnection).dissociateConnections();
managedConnectionInfo.clearConnectionHandles();
//todo this needs some kind of check so cx isn't returned more than once
//in case dissociate calls connection closed event and returns cx to pool.
returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
}
}
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[key=").append(key).append("]\n");
if (next == null) {
s.append("<end>");
} else {
next.info(s);
}
}
}
| 6,412 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/TransactionEnlistingInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TransactionEnlistingInterceptor.java
* <p/>
* <p/>
* Created: Fri Sep 26 14:52:24 2003
*
* @version 1.0
*/
public class TransactionEnlistingInterceptor implements ConnectionInterceptor {
protected static Logger log = Logger.getLogger(TransactionEnlistingInterceptor.class.getName());
private final ConnectionInterceptor next;
private final TransactionManager transactionManager;
public TransactionEnlistingInterceptor(ConnectionInterceptor next, TransactionManager transactionManager) {
this.next = next;
this.transactionManager = transactionManager;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
next.getConnection(connectionInfo);
try {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
// get the current transation and status... if there is a problem just assume there is no transaction present
Transaction transaction = TxUtil.getTransactionIfActive(transactionManager);
if (transaction != null) {
XAResource xares = mci.getXAResource();
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Enlisting connection " + connectionInfo + " with XAResource " + xares + " in transaction: " + transaction);
}
transaction.enlistResource(xares);
} else {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"not enlisting connection " + connectionInfo + " with XAResource " + mci.getXAResource() + " no transaction");
}
}
} catch (SystemException e) {
returnConnection(connectionInfo, ConnectionReturnAction.DESTROY);
throw new ResourceException("Could not get transaction", e);
} catch (RollbackException e) {
//transaction is marked rolled back, so the xaresource could not have been enlisted
next.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
throw new ResourceException("Could not enlist resource in rolled back transaction", e);
} catch (Throwable t) {
returnConnection(connectionInfo, ConnectionReturnAction.DESTROY);
throw new ResourceException("Unknown throwable when trying to enlist connection in tx", t);
}
}
/**
* The <code>returnConnection</code> method
* <p/>
* todo Probably the logic needs improvement if a connection
* error occurred and we are destroying the handle.
*
* @param connectionInfo a <code>ConnectionInfo</code> value
* @param connectionReturnAction a <code>ConnectionReturnAction</code> value
*/
public void returnConnection(ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
try {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
Transaction transaction = TxUtil.getTransactionIfActive(transactionManager);
if (transaction != null) {
XAResource xares = mci.getXAResource();
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Delisting connection " + connectionInfo + " with XAResource " + xares + " in transaction: " + transaction, new Exception("stack trace"));
}
transaction.delistResource(xares, XAResource.TMSUSPEND);
} else {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"not delisting connection " + connectionInfo + " with XAResource " + mci.getXAResource() + " no transaction");
}
}
} catch (SystemException e) {
//maybe we should warn???
log.log(Level.INFO,"Could not delist resource: " + connectionInfo + " with XAResource: " + connectionInfo.getManagedConnectionInfo().getXAResource(), e);
connectionReturnAction = ConnectionReturnAction.DESTROY;
} catch (IllegalStateException e) {
connectionReturnAction = ConnectionReturnAction.DESTROY;
}
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[transactionManager=").append(transactionManager).append("]\n");
next.info(s);
}
}
| 6,413 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/XAResourceInsertionInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
/**
* XAResourceInsertionInterceptor.java
*
*
* @version $Rev$ $Date$
*/
public class XAResourceInsertionInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final String name;
public XAResourceInsertionInterceptor(final ConnectionInterceptor next, final String name) {
this.next = next;
this.name = name;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
next.getConnection(connectionInfo);
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
mci.setXAResource(new WrapperNamedXAResource(mci.getManagedConnection().getXAResource(), name));
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[name=").append(name).append("]\n");
next.info(s);
}
}
| 6,414 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/OutboundNamedXAResourceFactory.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnectionFactory;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
/**
* @version $Rev$ $Date$
*/
public class OutboundNamedXAResourceFactory implements NamedXAResourceFactory {
private final String name;
private final ConnectionInterceptor recoveryStack;
private final ManagedConnectionFactory managedConnectionFactory;
public OutboundNamedXAResourceFactory(String name, ConnectionInterceptor recoveryStack, ManagedConnectionFactory managedConnectionFactory) {
this.name = name;
this.recoveryStack = recoveryStack;
this.managedConnectionFactory = managedConnectionFactory;
}
public String getName() {
return name;
}
public NamedXAResource getNamedXAResource() throws SystemException {
try {
ManagedConnectionInfo mci = new ManagedConnectionInfo(managedConnectionFactory, null);
ConnectionInfo recoveryConnectionInfo = new ConnectionInfo(mci);
recoveryStack.getConnection(recoveryConnectionInfo);
// For pooled resources, we may now have a new MCI (not the one constructed above). Make sure we use the correct MCI
return new NamedXAResourceWithConnectioninfo((NamedXAResource) recoveryConnectionInfo.getManagedConnectionInfo().getXAResource(), recoveryConnectionInfo);
} catch (ResourceException e) {
throw (SystemException) new SystemException("Could not get XAResource for recovery for mcf: " + name).initCause(e);
}
}
public void returnNamedXAResource(NamedXAResource namedXAResource) {
NamedXAResourceWithConnectioninfo xares = (NamedXAResourceWithConnectioninfo) namedXAResource;
recoveryStack.returnConnection(xares.getConnectionInfo(), ConnectionReturnAction.DESTROY);
}
private static class NamedXAResourceWithConnectioninfo implements NamedXAResource {
private final NamedXAResource delegate;
private final ConnectionInfo connectionInfo;
private NamedXAResourceWithConnectioninfo(NamedXAResource delegate, ConnectionInfo connectionInfo) {
this.delegate = delegate;
this.connectionInfo = connectionInfo;
}
public ConnectionInfo getConnectionInfo() {
return connectionInfo;
}
public String getName() {
return delegate.getName();
}
public void commit(Xid xid, boolean b) throws XAException {
delegate.commit(xid, b);
}
public void end(Xid xid, int i) throws XAException {
delegate.end(xid, i);
}
public void forget(Xid xid) throws XAException {
delegate.forget(xid);
}
public int getTransactionTimeout() throws XAException {
return delegate.getTransactionTimeout();
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return delegate.isSameRM(xaResource);
}
public int prepare(Xid xid) throws XAException {
return delegate.prepare(xid);
}
public Xid[] recover(int i) throws XAException {
return delegate.recover(i);
}
public void rollback(Xid xid) throws XAException {
delegate.rollback(xid);
}
public boolean setTransactionTimeout(int i) throws XAException {
return delegate.setTransactionTimeout(i);
}
public void start(Xid xid, int i) throws XAException {
delegate.start(xid, i);
}
}
}
| 6,415 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/LocalXAResourceInsertionInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
/**
* LocalXAResourceInsertionInterceptor.java
*
*
* @version $Rev$ $Date$
*/
public class LocalXAResourceInsertionInterceptor
implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final String name;
public LocalXAResourceInsertionInterceptor(final ConnectionInterceptor next, final String name) {
this.next = next;
this.name = name;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
next.getConnection(connectionInfo);
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
mci.setXAResource(
new LocalXAResource(mci.getManagedConnection().getLocalTransaction(), name));
}
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[name=").append(name).append("]\n");
if (next == null) {
s.append("<end>");
} else {
next.info(s);
}
}
}
| 6,416 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionInfo.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.geronimo.connector.outbound;
/**
* ConnectionInfo.java
*
*
* Created: Thu Sep 25 14:29:07 2003
*
* @version 1.0
*/
public class ConnectionInfo {
private ManagedConnectionInfo mci;
private Object connection;
private Object connectionProxy;
private boolean unshareable;
private boolean applicationManagedSecurity;
private Exception trace;
public ConnectionInfo() {
} // ConnectionInfo constructor
public ConnectionInfo(ManagedConnectionInfo mci) {
this.mci = mci;
}
/**
* Get the Mci value.
* @return the Mci value.
*/
public ManagedConnectionInfo getManagedConnectionInfo() {
return mci;
}
/**
* Set the Mci value.
* @param mci The new Mci value.
*/
public void setManagedConnectionInfo(ManagedConnectionInfo mci) {
this.mci = mci;
}
/**
* Get the Connection value.
* @return the Connection value.
*/
public Object getConnectionHandle() {
return connection;
}
/**
* Set the Connection value.
* @param connection The new Connection value.
*/
public void setConnectionHandle(Object connection) {
assert this.connection == null;
this.connection = connection;
}
public Object getConnectionProxy() {
return connectionProxy;
}
public void setConnectionProxy(Object connectionProxy) {
this.connectionProxy = connectionProxy;
}
public boolean isUnshareable() {
return unshareable;
}
public void setUnshareable(boolean unshareable) {
this.unshareable = unshareable;
}
public boolean isApplicationManagedSecurity() {
return applicationManagedSecurity;
}
public void setApplicationManagedSecurity(boolean applicationManagedSecurity) {
this.applicationManagedSecurity = applicationManagedSecurity;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ConnectionInfo) {
ConnectionInfo other = (ConnectionInfo) obj;
return (connection == other.connection)
&& (mci == other.mci);
}
return false;
}
public int hashCode() {
return ((connection != null) ? connection.hashCode() : 7) ^
((mci != null) ? mci.hashCode() : 7);
}
public void setTrace() {
this.trace = new Exception("Stack Trace");
}
public Exception getTrace() {
return trace;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("handle: ").append(connection);
b.append(mci);
return b.toString();
}
} // ConnectionInfo
| 6,417 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/MultiPoolConnectionInterceptor.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.geronimo.connector.outbound;
import java.util.HashMap;
import java.util.Map;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionRequestInfo;
import javax.security.auth.Subject;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
/**
* MultiPoolConnectionInterceptor maps the provided subject and connection request info to a
* "SinglePool". This can be used to make sure all matches will succeed, avoiding synchronization
* slowdowns.
*
* Created: Fri Oct 10 12:53:11 2003
*
* @version $Rev$ $Date$
*/
public class MultiPoolConnectionInterceptor implements ConnectionInterceptor, PoolingAttributes{
private final ConnectionInterceptor next;
private final PoolingSupport singlePoolFactory;
private final boolean useSubject;
private final boolean useCRI;
private final Map<SubjectCRIKey,PoolingAttributes> pools = new HashMap<SubjectCRIKey,PoolingAttributes>();
// volatile is not necessary, here, because of synchronization. but maintained for consistency with other Interceptors...
private volatile boolean destroyed = false;
public MultiPoolConnectionInterceptor(
final ConnectionInterceptor next,
PoolingSupport singlePoolFactory,
final boolean useSubject,
final boolean useCRI) {
this.next = next;
this.singlePoolFactory = singlePoolFactory;
this.useSubject = useSubject;
this.useCRI = useCRI;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
SubjectCRIKey key =
new SubjectCRIKey(
useSubject ? mci.getSubject() : null,
useCRI ? mci.getConnectionRequestInfo() : null);
ConnectionInterceptor poolInterceptor = null;
synchronized (pools) {
if (destroyed) {
throw new ResourceException("ConnectionManaged has been destroyed");
}
poolInterceptor = (ConnectionInterceptor) pools.get(key);
if (poolInterceptor == null) {
poolInterceptor = singlePoolFactory.addPoolingInterceptors(next);
pools.put(key, (PoolingAttributes) poolInterceptor);
}
}
poolInterceptor.getConnection(connectionInfo);
connectionInfo.getManagedConnectionInfo().setPoolInterceptor(poolInterceptor);
}
// let underlying pools handle destroyed processing...
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
ConnectionInterceptor poolInterceptor = mci.getPoolInterceptor();
poolInterceptor.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
synchronized (pools) {
destroyed = true;
for (PoolingAttributes poolingAttributes : pools.values()) {
ConnectionInterceptor poolInterceptor = (ConnectionInterceptor) poolingAttributes;
poolInterceptor.destroy();
}
pools.clear();
}
next.destroy();
}
public int getPartitionCount() {
return pools.size();
}
public int getPartitionMaxSize() {
return singlePoolFactory.getPartitionMaxSize();
}
public void setPartitionMaxSize(int maxSize) throws InterruptedException {
singlePoolFactory.setPartitionMaxSize(maxSize);
for (PoolingAttributes poolingAttributes : pools.values()) {
poolingAttributes.setPartitionMaxSize(maxSize);
}
}
public int getPartitionMinSize() {
return singlePoolFactory.getPartitionMinSize();
}
public void setPartitionMinSize(int minSize) {
singlePoolFactory.setPartitionMinSize(minSize);
for (PoolingAttributes poolingAttributes : pools.values()) {
poolingAttributes.setPartitionMinSize(minSize);
}
}
public int getIdleConnectionCount() {
int count = 0;
for (PoolingAttributes poolingAttributes : pools.values()) {
count += poolingAttributes.getIdleConnectionCount();
}
return count;
}
public int getConnectionCount() {
int count = 0;
for (PoolingAttributes poolingAttributes : pools.values()) {
count += poolingAttributes.getConnectionCount();
}
return count;
}
public int getBlockingTimeoutMilliseconds() {
return singlePoolFactory.getBlockingTimeoutMilliseconds();
}
public void setBlockingTimeoutMilliseconds(int timeoutMilliseconds) {
singlePoolFactory.setBlockingTimeoutMilliseconds(timeoutMilliseconds);
for (PoolingAttributes poolingAttributes : pools.values()) {
poolingAttributes.setBlockingTimeoutMilliseconds(timeoutMilliseconds);
}
}
public int getIdleTimeoutMinutes() {
return singlePoolFactory.getIdleTimeoutMinutes();
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
singlePoolFactory.setIdleTimeoutMinutes(idleTimeoutMinutes);
for (PoolingAttributes poolingAttributes : pools.values()) {
poolingAttributes.setIdleTimeoutMinutes(idleTimeoutMinutes);
}
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[useSubject=").append(useSubject).append(",useCRI=").append(useCRI).append(",pool count=").append(pools.size()).append("]\n");
next.info(s);
}
static class SubjectCRIKey {
private final Subject subject;
private final ConnectionRequestInfo cri;
private final int hashcode;
public SubjectCRIKey(
final Subject subject,
final ConnectionRequestInfo cri) {
this.subject = subject;
this.cri = cri;
this.hashcode =
(subject == null ? 17 : subject.hashCode() * 17)
^ (cri == null ? 1 : cri.hashCode());
}
@Override
public int hashCode() {
return hashcode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SubjectCRIKey that = (SubjectCRIKey) o;
if (hashcode != that.hashcode) return false;
if (cri != null ? !cri.equals(that.cri) : that.cri != null) return false;
if (subject != null ? !subject.equals(that.subject) : that.subject != null) return false;
return true;
}
}
}
| 6,418 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/AbstractSinglePoolConnectionInterceptor.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.geronimo.connector.outbound;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionFactory;
import javax.security.auth.Subject;
/**
* @version $Rev$ $Date$
*/
public abstract class AbstractSinglePoolConnectionInterceptor implements ConnectionInterceptor, PoolingAttributes {
protected static Logger log = Logger.getLogger(AbstractSinglePoolConnectionInterceptor.class.getName());
protected final ConnectionInterceptor next;
private final ReadWriteLock resizeLock = new ReentrantReadWriteLock();
protected Semaphore permits;
protected int blockingTimeoutMilliseconds;
protected int connectionCount = 0;
protected long idleTimeoutMilliseconds;
private IdleReleaser idleReleaser;
protected Timer timer = PoolIdleReleaserTimer.getTimer();
protected int maxSize = 0;
protected int minSize = 0;
protected int shrinkLater = 0;
protected volatile boolean destroyed = false;
public AbstractSinglePoolConnectionInterceptor(final ConnectionInterceptor next,
int maxSize,
int minSize,
int blockingTimeoutMilliseconds,
int idleTimeoutMinutes) {
this.next = next;
this.maxSize = maxSize;
this.minSize = minSize;
this.blockingTimeoutMilliseconds = blockingTimeoutMilliseconds;
setIdleTimeoutMinutes(idleTimeoutMinutes);
permits = new Semaphore(maxSize, true);
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
if (connectionInfo.getManagedConnectionInfo().getManagedConnection() != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"supplying already assigned connection from pool " + this + " " + connectionInfo);
}
return;
}
try {
resizeLock.readLock().lock();
try {
if (permits.tryAcquire(blockingTimeoutMilliseconds, TimeUnit.MILLISECONDS)) {
try {
internalGetConnection(connectionInfo);
} catch (ResourceException e) {
permits.release();
throw e;
}
} else {
throw new ResourceException("No ManagedConnections available "
+ "within configured blocking timeout ( "
+ blockingTimeoutMilliseconds
+ " [ms] ) for pool " + this);
}
} finally {
resizeLock.readLock().unlock();
}
} catch (InterruptedException ie) {
throw new ResourceException("Interrupted while requesting permit.", ie);
} // end of try-catch
}
protected abstract void internalGetConnection(ConnectionInfo connectionInfo) throws ResourceException;
public void returnConnection(ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"returning connection " + connectionInfo.getConnectionHandle() + " for MCI " + connectionInfo.getManagedConnectionInfo() + " and MC " + connectionInfo.getManagedConnectionInfo().getManagedConnection() + " to pool " + this);
}
// not strictly synchronized with destroy(), but pooled operations in internalReturn() are...
if (destroyed) {
try {
connectionInfo.getManagedConnectionInfo().getManagedConnection().destroy();
} catch (ResourceException re) {
// empty
}
return;
}
resizeLock.readLock().lock();
try {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
if (connectionReturnAction == ConnectionReturnAction.RETURN_HANDLE && mci.hasConnectionHandles()) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Return request at pool with connection handles! " + connectionInfo.getConnectionHandle() + " for MCI " + connectionInfo.getManagedConnectionInfo() + " and MC " + connectionInfo.getManagedConnectionInfo().getManagedConnection() + " to pool " + this, new Exception("Stack trace"));
}
return;
}
boolean releasePermit = internalReturn(connectionInfo, connectionReturnAction);
if (releasePermit) {
permits.release();
}
} finally {
resizeLock.readLock().unlock();
}
}
/**
*
* @param connectionInfo connection info to return to pool
* @param connectionReturnAction whether to return to pool or destroy
* @return true if a connection for which a permit was issued was returned (so the permit should be released),
* false if no permit was issued (for instance if the connection was already in the pool and we are destroying it).
*/
protected boolean internalReturn(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
ManagedConnection mc = mci.getManagedConnection();
try {
mc.cleanup();
} catch (ResourceException e) {
connectionReturnAction = ConnectionReturnAction.DESTROY;
}
boolean releasePermit;
synchronized (getPool()) {
// a bit redundant, but this closes a small timing hole...
if (destroyed) {
try {
mc.destroy();
}
catch (ResourceException re) {
//ignore
}
return doRemove(mci);
}
if (shrinkLater > 0) {
//nothing can get in the pool while shrinkLater > 0, so releasePermit is false here.
connectionReturnAction = ConnectionReturnAction.DESTROY;
shrinkLater--;
releasePermit = false;
} else if (connectionReturnAction == ConnectionReturnAction.RETURN_HANDLE) {
mci.setLastUsed(System.currentTimeMillis());
doAdd(mci);
return true;
} else {
releasePermit = doRemove(mci);
}
}
//we must destroy connection.
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Discarding connection in pool " + this + " " + connectionInfo);
}
next.returnConnection(connectionInfo, connectionReturnAction);
connectionCount--;
return releasePermit;
}
protected abstract void internalDestroy();
// Cancel the IdleReleaser TimerTask (fixes memory leak) and clean up the pool
public void destroy() {
destroyed = true;
if (idleReleaser != null)
idleReleaser.cancel();
internalDestroy();
next.destroy();
}
public int getPartitionCount() {
return 1;
}
public int getPartitionMaxSize() {
return maxSize;
}
public void setPartitionMaxSize(int newMaxSize) throws InterruptedException {
if (newMaxSize <= 0) {
throw new IllegalArgumentException("Max size must be positive, not " + newMaxSize);
}
if (newMaxSize != getPartitionMaxSize()) {
resizeLock.writeLock().lock();
try {
ResizeInfo resizeInfo = new ResizeInfo(this.minSize, permits.availablePermits(), connectionCount, newMaxSize);
permits = new Semaphore(newMaxSize, true);
//pre-acquire permits for the existing checked out connections that will not be closed when they are returned.
for (int i = 0; i < resizeInfo.getTransferCheckedOut(); i++) {
permits.acquire();
}
//make sure shrinkLater is 0 while discarding excess connections
this.shrinkLater = 0;
//transfer connections we are going to keep
transferConnections(newMaxSize, resizeInfo.getShrinkNow());
this.shrinkLater = resizeInfo.getShrinkLater();
this.minSize = resizeInfo.getNewMinSize();
this.maxSize = newMaxSize;
} finally {
resizeLock.writeLock().unlock();
}
}
}
protected abstract boolean doRemove(ManagedConnectionInfo mci);
protected abstract void doAdd(ManagedConnectionInfo mci);
protected abstract Object getPool();
static final class ResizeInfo {
private final int newMinSize;
private final int shrinkNow;
private final int shrinkLater;
private final int transferCheckedOut;
ResizeInfo(final int oldMinSize, final int oldPermitsAvailable, final int oldConnectionCount, final int newMaxSize) {
final int checkedOut = oldConnectionCount - oldPermitsAvailable;
int shrinkLater = checkedOut - newMaxSize;
if (shrinkLater < 0) {
shrinkLater = 0;
}
this.shrinkLater = shrinkLater;
int shrinkNow = oldConnectionCount - newMaxSize - shrinkLater;
if (shrinkNow < 0) {
shrinkNow = 0;
}
this.shrinkNow = shrinkNow;
if (newMaxSize >= oldMinSize) {
newMinSize = oldMinSize;
} else {
newMinSize = newMaxSize;
}
this.transferCheckedOut = checkedOut - shrinkLater;
}
public int getNewMinSize() {
return newMinSize;
}
public int getShrinkNow() {
return shrinkNow;
}
public int getShrinkLater() {
return shrinkLater;
}
public int getTransferCheckedOut() {
return transferCheckedOut;
}
}
protected abstract void transferConnections(int maxSize, int shrinkNow);
public abstract int getIdleConnectionCount();
public int getConnectionCount() {
return connectionCount;
}
public int getPartitionMinSize() {
return minSize;
}
public void setPartitionMinSize(int minSize) {
this.minSize = minSize;
}
public int getBlockingTimeoutMilliseconds() {
return blockingTimeoutMilliseconds;
}
public void setBlockingTimeoutMilliseconds(int blockingTimeoutMilliseconds) {
if (blockingTimeoutMilliseconds < 0) {
throw new IllegalArgumentException("blockingTimeoutMilliseconds must be positive or 0, not " + blockingTimeoutMilliseconds);
}
if (blockingTimeoutMilliseconds == 0) {
this.blockingTimeoutMilliseconds = Integer.MAX_VALUE;
} else {
this.blockingTimeoutMilliseconds = blockingTimeoutMilliseconds;
}
}
public int getIdleTimeoutMinutes() {
return (int) idleTimeoutMilliseconds / (1000 * 60);
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
if (idleTimeoutMinutes < 0) {
throw new IllegalArgumentException("idleTimeoutMinutes must be positive or 0, not " + idleTimeoutMinutes);
}
if (idleReleaser != null) {
idleReleaser.cancel();
}
if (idleTimeoutMinutes > 0) {
this.idleTimeoutMilliseconds = idleTimeoutMinutes * 60 * 1000;
idleReleaser = new IdleReleaser(this);
timer.schedule(idleReleaser, this.idleTimeoutMilliseconds, this.idleTimeoutMilliseconds);
}
}
protected abstract void getExpiredManagedConnectionInfos(long threshold, List<ManagedConnectionInfo> killList);
protected boolean addToPool(ManagedConnectionInfo mci) {
boolean added;
synchronized (getPool()) {
connectionCount++;
added = getPartitionMaxSize() > getIdleConnectionCount();
if (added) {
doAdd(mci);
}
}
return added;
}
// static class to permit chain of strong references from preventing ClassLoaders
// from being GC'ed.
private static class IdleReleaser extends TimerTask {
private AbstractSinglePoolConnectionInterceptor parent;
private IdleReleaser(AbstractSinglePoolConnectionInterceptor parent) {
this.parent = parent;
}
public boolean cancel() {
this.parent = null;
return super.cancel();
}
public void run() {
// protect against interceptor being set to null mid-execution
AbstractSinglePoolConnectionInterceptor interceptor = parent;
if (interceptor == null)
return;
interceptor.resizeLock.readLock().lock();
try {
long threshold = System.currentTimeMillis() - interceptor.idleTimeoutMilliseconds;
List<ManagedConnectionInfo> killList = new ArrayList<ManagedConnectionInfo>(interceptor.getPartitionMaxSize());
interceptor.getExpiredManagedConnectionInfos(threshold, killList);
for (ManagedConnectionInfo managedConnectionInfo : killList) {
ConnectionInfo killInfo = new ConnectionInfo(managedConnectionInfo);
parent.next.returnConnection(killInfo, ConnectionReturnAction.DESTROY);
}
} catch (Throwable t) {
log.log(Level.SEVERE, "Error occurred during execution of ExpirationMonitor TimerTask", t);
} finally {
interceptor.resizeLock.readLock().unlock();
}
}
}
// Currently only a short-lived (10 millisecond) task.
// So, FillTask, unlike IdleReleaser, shouldn't cause GC problems.
protected class FillTask extends TimerTask {
private final ManagedConnectionFactory managedConnectionFactory;
private final Subject subject;
private final ConnectionRequestInfo cri;
public FillTask(ConnectionInfo connectionInfo) {
managedConnectionFactory = connectionInfo.getManagedConnectionInfo().getManagedConnectionFactory();
subject = connectionInfo.getManagedConnectionInfo().getSubject();
cri = connectionInfo.getManagedConnectionInfo().getConnectionRequestInfo();
}
public void run() {
resizeLock.readLock().lock();
try {
while (connectionCount < minSize) {
ManagedConnectionInfo mci = new ManagedConnectionInfo(managedConnectionFactory, cri);
mci.setSubject(subject);
ConnectionInfo ci = new ConnectionInfo(mci);
try {
next.getConnection(ci);
} catch (ResourceException e) {
return;
}
boolean added = addToPool(mci);
if (!added) {
internalReturn(ci, ConnectionReturnAction.DESTROY);
return;
}
}
} catch (Throwable t) {
log.log(Level.SEVERE, "FillTask encountered error in run method", t);
} finally {
resizeLock.readLock().unlock();
}
}
}
}
| 6,419 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionHandleInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
/**
* ConnectionHandleInterceptor.java
*
*
* @version $Rev$ $Date$
*/
public class ConnectionHandleInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
public ConnectionHandleInterceptor(ConnectionInterceptor next) {
this.next = next;
}
/**
* in: connectionInfo not null, managedConnectionInfo not null. ManagedConnection may or may not be null. ConnectionHandle may or may not be null
* out: managedConnection not null. connection handle not null. managedConnectionInfo has connection handle registered. Connection handle is associated with ManagedConnection.
* @param connectionInfo
* @throws ResourceException
*/
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
next.getConnection(connectionInfo);
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
if (connectionInfo.getConnectionHandle() == null) {
connectionInfo.setConnectionHandle(
mci.getManagedConnection().getConnection(
mci.getSubject(),
mci.getConnectionRequestInfo()));
mci.addConnectionHandle(connectionInfo);
} else if (!mci.hasConnectionInfo(connectionInfo)) {
mci.getManagedConnection().associateConnection(
connectionInfo.getConnectionHandle());
mci.addConnectionHandle(connectionInfo);
}
connectionInfo.setTrace();
}
/**
* in: connectionInfo not null, managedConnectionInfo not null, managedConnection not null. Handle can be null if mc is being destroyed from pool.
* out: managedCOnnectionInfo null, handle not in mci.handles.
* @param connectionInfo
* @param connectionReturnAction
*/
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
if (connectionInfo.getConnectionHandle() != null) {
connectionInfo.getManagedConnectionInfo().removeConnectionHandle(
connectionInfo);
}
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("\n");
if (next == null) {
s.append("<end>");
} else {
next.info(s);
}
}
}
| 6,420 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/SubjectSource.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.geronimo.connector.outbound;
import javax.security.auth.Subject;
/**
* @version $Rev:$ $Date:$
*/
public interface SubjectSource {
Subject getSubject() throws SecurityException;
}
| 6,421 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/LocalXAResource.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.LocalTransaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.manager.NamedXAResource;
/**
* LocalXAResource adapts a local transaction to be controlled by a
* JTA transaction manager. Of course, it cannot provide xa
* semantics.
*
*
* @version $Rev$ $Date$
*/
public class LocalXAResource implements NamedXAResource {
//accessible in package for testing
final LocalTransaction localTransaction;
private final String name;
private Xid xid;
private int transactionTimeout;
public LocalXAResource(LocalTransaction localTransaction, String name) {
this.localTransaction = localTransaction;
this.name = name;
}
// Implementation of javax.transaction.xa.XAResource
public void commit(Xid xid, boolean flag) throws XAException {
if (this.xid == null || !this.xid.equals(xid)) {
throw new XAException("Invalid Xid");
}
try {
localTransaction.commit();
} catch (ResourceException e) {
throw (XAException)new XAException().initCause(e);
} finally {
this.xid = null;
}
}
public void forget(Xid xid) throws XAException {
this.xid = null;
}
public int getTransactionTimeout() throws XAException {
return transactionTimeout;
}
public boolean isSameRM(XAResource xares) throws XAException {
return this == xares;
}
public Xid[] recover(int n) throws XAException {
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
if (this.xid == null || !this.xid.equals(xid)) {
throw new XAException("Invalid Xid");
}
try {
localTransaction.rollback();
} catch (ResourceException e) {
throw (XAException)new XAException().initCause(e);
} finally {
this.xid = null;
}
}
public boolean setTransactionTimeout(int txTimeout) throws XAException {
this.transactionTimeout = txTimeout;
return true;
}
public void start(Xid xid, int flag) throws XAException {
if (flag == XAResource.TMNOFLAGS) {
// first time in this transaction
if (this.xid != null) {
throw new XAException("already enlisted");
}
this.xid = xid;
try {
localTransaction.begin();
} catch (ResourceException e) {
throw (XAException) new XAException("could not start local tx").initCause(e);
}
} else if (flag == XAResource.TMRESUME) {
if (xid != this.xid) {
throw new XAException("attempting to resume in different transaction");
}
} else {
throw new XAException("unknown state");
}
}
public void end(Xid xid, int flag) throws XAException {
if (xid != this.xid) {
throw new XAException("Invalid Xid");
}
//we could keep track of if the flag is TMSUCCESS...
}
public int prepare(Xid xid) throws XAException {
//log warning that semantics are incorrect...
return XAResource.XA_OK;
}
public String getName() {
return name;
}
}
| 6,422 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/AbstractConnectionManager.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionManager;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.LazyAssociatableConnectionManager;
import jakarta.resource.spi.ManagedConnectionFactory;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
/**
* @version $Rev$ $Date$
*/
public abstract class AbstractConnectionManager implements ConnectionManagerContainer, ConnectionManager, LazyAssociatableConnectionManager, PoolingAttributes {
protected transient final Interceptors interceptors;
private transient final RecoverableTransactionManager transactionManager;
private transient final ManagedConnectionFactory managedConnectionFactory;
private final String name;
//default constructor to support externalizable subclasses
public AbstractConnectionManager() {
interceptors = null;
transactionManager = null;
managedConnectionFactory = null;
this.name = null;
}
public AbstractConnectionManager(Interceptors interceptors, RecoverableTransactionManager transactionManager, ManagedConnectionFactory mcf, String name) {
this.interceptors = interceptors;
this.transactionManager = transactionManager;
this.managedConnectionFactory = mcf;
this.name = name;
}
public Object createConnectionFactory() throws ResourceException {
return managedConnectionFactory.createConnectionFactory(this);
}
protected ConnectionManager getConnectionManager() {
return this;
}
public ManagedConnectionFactory getManagedConnectionFactory() {
return managedConnectionFactory;
}
public void doRecovery() {
if (!getIsRecoverable()) {
return;
}
transactionManager.registerNamedXAResourceFactory(new OutboundNamedXAResourceFactory(name, getRecoveryStack(), managedConnectionFactory));
}
/**
* in: mcf != null, is a deployed mcf
* out: useable connection object.
*/
public Object allocateConnection(ManagedConnectionFactory managedConnectionFactory,
ConnectionRequestInfo connectionRequestInfo)
throws ResourceException {
ManagedConnectionInfo mci = new ManagedConnectionInfo(managedConnectionFactory, connectionRequestInfo);
ConnectionInfo ci = new ConnectionInfo(mci);
getStack().getConnection(ci);
Object connection = ci.getConnectionProxy();
if (connection == null) {
connection = ci.getConnectionHandle();
} else {
// connection proxy is used only once so we can be notified
// by the garbage collector when a connection is abandoned
ci.setConnectionProxy(null);
}
return connection;
}
/**
* in: non-null connection object, from non-null mcf.
* connection object is not associated with a managed connection
* out: supplied connection object is assiciated with a non-null ManagedConnection from mcf.
*/
public void associateConnection(Object connection,
ManagedConnectionFactory managedConnectionFactory,
ConnectionRequestInfo connectionRequestInfo)
throws ResourceException {
ManagedConnectionInfo mci = new ManagedConnectionInfo(managedConnectionFactory, connectionRequestInfo);
ConnectionInfo ci = new ConnectionInfo(mci);
ci.setConnectionHandle(connection);
getStack().getConnection(ci);
}
public void inactiveConnectionClosed(Object connection, ManagedConnectionFactory managedConnectionFactory) {
//TODO If we are tracking connections, we need to stop tracking this one.
//I don't see why we don't get a connectionClosed event for it.
}
ConnectionInterceptor getConnectionInterceptor() {
return getStack();
}
//statistics
public int getPartitionCount() {
return getPooling().getPartitionCount();
}
public int getPartitionMaxSize() {
return getPooling().getPartitionMaxSize();
}
public void setPartitionMaxSize(int maxSize) throws InterruptedException {
getPooling().setPartitionMaxSize(maxSize);
}
public int getPartitionMinSize() {
return getPooling().getPartitionMinSize();
}
public void setPartitionMinSize(int minSize) {
getPooling().setPartitionMinSize(minSize);
}
public int getIdleConnectionCount() {
return getPooling().getIdleConnectionCount();
}
public int getConnectionCount() {
return getPooling().getConnectionCount();
}
public int getBlockingTimeoutMilliseconds() {
return getPooling().getBlockingTimeoutMilliseconds();
}
public void setBlockingTimeoutMilliseconds(int timeoutMilliseconds) {
getPooling().setBlockingTimeoutMilliseconds(timeoutMilliseconds);
}
public int getIdleTimeoutMinutes() {
return getPooling().getIdleTimeoutMinutes();
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
getPooling().setIdleTimeoutMinutes(idleTimeoutMinutes);
}
private ConnectionInterceptor getStack() {
return interceptors.getStack();
}
private ConnectionInterceptor getRecoveryStack() {
return interceptors.getRecoveryStack();
}
private boolean getIsRecoverable() {
return interceptors.getRecoveryStack() != null;
}
//public for persistence of pooling attributes (max, min size, blocking/idle timeouts)
public PoolingSupport getPooling() {
return interceptors.getPoolingAttributes();
}
public interface Interceptors {
ConnectionInterceptor getStack();
ConnectionInterceptor getRecoveryStack();
PoolingSupport getPoolingAttributes();
}
public void doStart() throws Exception {
}
public void doStop() throws Exception {
if (transactionManager != null) {
transactionManager.unregisterNamedXAResourceFactory(name);
}
interceptors.getStack().destroy();
}
public void doFail() {
if (transactionManager != null) {
transactionManager.unregisterNamedXAResourceFactory(name);
}
interceptors.getStack().destroy();
}
}
| 6,423 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/SubjectInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ApplicationServerInternalException;
import javax.security.auth.Subject;
/**
* SubjectInterceptor.java This is installed only when the plan includes a container-managed-security element.
*
*
* Created: Mon Oct 6 14:31:56 2003
*
* @version $Rev$ $Date$
*/
public class SubjectInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final SubjectSource subjectSource;
public SubjectInterceptor(final ConnectionInterceptor next, final SubjectSource subjectSource) {
this.next = next;
this.subjectSource = subjectSource;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
Subject currentSubject = null;
if (!connectionInfo.isApplicationManagedSecurity()) {
try {
currentSubject = subjectSource.getSubject();
} catch (SecurityException e) {
throw new ResourceException("Can not obtain Subject for login", e);
}
if (currentSubject == null) {
throw new ResourceException("No subject for container managed security");
}
}
ManagedConnectionInfo originalManagedConnectionInfo = connectionInfo.getManagedConnectionInfo();
//No existing managed connection, get an appropriate one and return.
if (originalManagedConnectionInfo.getManagedConnection() == null) {
originalManagedConnectionInfo.setSubject(currentSubject);
next.getConnection(connectionInfo);
} else {
Subject oldSubject = originalManagedConnectionInfo.getSubject();
if (currentSubject == null ? oldSubject != null : !currentSubject.equals(oldSubject)) {
if (connectionInfo.isUnshareable()) {
throw new ApplicationServerInternalException("Unshareable resource is attempting to change security context: expected request under: " + oldSubject + ", received request under: " + currentSubject);
} else {
//existing managed connection, wrong subject: must re-associate.
//make a ConnectionInfo to process removing the handle from the old mc
ConnectionInfo returningConnectionInfo = new ConnectionInfo();
returningConnectionInfo.setManagedConnectionInfo(originalManagedConnectionInfo);
//This should decrement handle count, but not close the handle, when returnConnection is called
//I'm not sure how to test/assure this.
returningConnectionInfo.setConnectionHandle(connectionInfo.getConnectionHandle());
//make a new ManagedConnectionInfo for the mc we will ask for
ManagedConnectionInfo newManagedConnectionInfo =
new ManagedConnectionInfo(
originalManagedConnectionInfo.getManagedConnectionFactory(),
originalManagedConnectionInfo.getConnectionRequestInfo());
newManagedConnectionInfo.setSubject(currentSubject);
connectionInfo.setManagedConnectionInfo(newManagedConnectionInfo);
next.getConnection(connectionInfo);
//process the removal of the handle from the previous mc
returnConnection(returningConnectionInfo, ConnectionReturnAction.RETURN_HANDLE);
}
} else {
//otherwise, the current ManagedConnection matches the security info, we keep it.
//set up the tx context
next.getConnection(connectionInfo);
}
}
}
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[subjectSource=").append(subjectSource).append("]\n");
next.info(s);
}
}
| 6,424 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionManagerContainer.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnectionFactory;
/**
* ConnectionManagerContainer
*
* @version $Rev$ $Date$
*/
public interface ConnectionManagerContainer {
Object createConnectionFactory() throws ResourceException;
void doRecovery();
}
| 6,425 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ManagedConnectionInfo.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.geronimo.connector.outbound;
import java.util.Collection;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionFactory;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
/**
* ConnectionRequest.java
*
*
* Created: Thu Sep 25 14:29:07 2003
*
* @version 1.0
*/
public class ManagedConnectionInfo {
private ManagedConnectionFactory managedConnectionFactory;
private ConnectionRequestInfo connectionRequestInfo;
private Subject subject;
private ManagedConnection managedConnection;
private XAResource xares;
private long lastUsed;
private ConnectionInterceptor poolInterceptor;
private GeronimoConnectionEventListener listener;
public ManagedConnectionInfo(
ManagedConnectionFactory managedConnectionFactory,
ConnectionRequestInfo connectionRequestInfo) {
this.managedConnectionFactory = managedConnectionFactory;
this.connectionRequestInfo = connectionRequestInfo;
}
public ManagedConnectionFactory getManagedConnectionFactory() {
return managedConnectionFactory;
}
public void setManagedConnectionFactory(ManagedConnectionFactory managedConnectionFactory) {
this.managedConnectionFactory = managedConnectionFactory;
}
public ConnectionRequestInfo getConnectionRequestInfo() {
return connectionRequestInfo;
}
public void setConnectionRequestInfo(ConnectionRequestInfo cri) {
this.connectionRequestInfo = cri;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
public ManagedConnection getManagedConnection() {
return managedConnection;
}
public void setManagedConnection(ManagedConnection managedConnection) {
assert this.managedConnection == null;
this.managedConnection = managedConnection;
}
public XAResource getXAResource() {
return xares;
}
public void setXAResource(XAResource xares) {
this.xares = xares;
}
public long getLastUsed() {
return lastUsed;
}
public void setLastUsed(long lastUsed) {
this.lastUsed = lastUsed;
}
public void setPoolInterceptor(ConnectionInterceptor poolInterceptor) {
this.poolInterceptor = poolInterceptor;
}
public ConnectionInterceptor getPoolInterceptor() {
return poolInterceptor;
}
public void setConnectionEventListener(GeronimoConnectionEventListener listener) {
this.listener = listener;
}
public void addConnectionHandle(ConnectionInfo connectionInfo) {
listener.addConnectionInfo(connectionInfo);
}
public void removeConnectionHandle(ConnectionInfo connectionInfo) {
listener.removeConnectionInfo(connectionInfo);
}
public boolean hasConnectionHandles() {
return listener.hasConnectionInfos();
}
public void clearConnectionHandles() {
listener.clearConnectionInfos();
}
public Collection<ConnectionInfo> getConnectionInfos() {
return listener.getConnectionInfos();
}
public boolean securityMatches(ManagedConnectionInfo other) {
return (
subject == null
? other.getSubject() == null
: subject.equals(other.getSubject()))
&& (connectionRequestInfo == null
? other.getConnectionRequestInfo() == null
: connectionRequestInfo.equals(other.getConnectionRequestInfo()));
}
public boolean hasConnectionInfo(ConnectionInfo connectionInfo) {
return listener.hasConnectionInfo(connectionInfo);
}
public boolean isFirstConnectionInfo(ConnectionInfo connectionInfo) {
return listener.isFirstConnectionInfo(connectionInfo);
}
@Override
public String toString() {
return "ManagedConnectionInfo: " + super.toString() + ". mc: " + managedConnection + "]";
}
}
| 6,426 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionInterceptorSource.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.geronimo.connector.outbound;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface ConnectionInterceptorSource {
ConnectionInterceptor getConnectionInterceptor();
}
| 6,427 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/TransactionCachingInterceptor.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.geronimo.connector.outbound;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.ResourceException;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.ConnectionReleaser;
import org.apache.geronimo.connector.ConnectorTransactionContext;
/**
* TransactionCachingInterceptor.java
* TODO: This implementation does not take account of unshareable resources
* TODO: This implementation does not take account of application security
* where several connections with different security info are obtained.
* TODO: This implementation does not take account of container managed security where,
* within one transaction, a security domain boundary is crossed
* and connections are obtained with two (or more) different subjects.
* <p/>
* I suggest a state pattern, with the state set in a threadlocal upon entering a component,
* will be a usable implementation.
* <p/>
* The afterCompletion method will need to move to an interface, and that interface include the
* security info to distinguish connections.
* <p/>
* <p/>
* Created: Mon Sep 29 15:07:07 2003
*
* @version 1.0
*/
public class TransactionCachingInterceptor implements ConnectionInterceptor, ConnectionReleaser {
protected static Logger log = Logger.getLogger(TransactionCachingInterceptor.class.getName());
private final ConnectionInterceptor next;
private final TransactionManager transactionManager;
public TransactionCachingInterceptor(ConnectionInterceptor next, TransactionManager transactionManager) {
this.next = next;
this.transactionManager = transactionManager;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
//There can be an inactive transaction context when a connection is requested in
//Synchronization.afterCompletion().
// get the current transaction and status... if there is a problem just assume there is no transaction present
Transaction transaction = TxUtil.getTransactionIfActive(transactionManager);
if (transaction != null) {
ManagedConnectionInfos managedConnectionInfos = ConnectorTransactionContext.get(transaction, this);
if (connectionInfo.isUnshareable()) {
if (!managedConnectionInfos.containsUnshared(connectionInfo.getManagedConnectionInfo())) {
next.getConnection(connectionInfo);
managedConnectionInfos.addUnshared(connectionInfo.getManagedConnectionInfo());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Enlisting connection already associated with handle " + infoString(connectionInfo));
}
}
} else {
ManagedConnectionInfo managedConnectionInfo = managedConnectionInfos.getShared();
if (managedConnectionInfo != null) {
ManagedConnectionInfo previousMci = connectionInfo.getManagedConnectionInfo();
if (previousMci != null && previousMci != managedConnectionInfo && previousMci.getManagedConnection() != null) {
//This might occur if more than one connection were obtained before a UserTransaction were started.
//enlists connection
next.getConnection(connectionInfo);
managedConnectionInfos.addUnshared(previousMci);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Enlisting existing connection associated with connection handle with current tx " + infoString(connectionInfo));
}
} else {
connectionInfo.setManagedConnectionInfo(managedConnectionInfo);
//return;
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"supplying connection from tx cache " + infoString(connectionInfo));
}
}
} else {
next.getConnection(connectionInfo);
managedConnectionInfos.setShared(connectionInfo.getManagedConnectionInfo());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"supplying connection from pool " + connectionInfo.getConnectionHandle() + " for managed connection " + connectionInfo.getManagedConnectionInfo().getManagedConnection() + " to tx caching interceptor " + this);
}
}
}
} else {
next.getConnection(connectionInfo);
}
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
if (connectionReturnAction == ConnectionReturnAction.DESTROY) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"destroying connection " + infoString(connectionInfo));
}
next.returnConnection(connectionInfo, connectionReturnAction);
return;
}
Transaction transaction;
try {
transaction = transactionManager.getTransaction();
if (transaction != null) {
if (TxUtil.isActive(transaction)) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"tx active, not returning connection " + infoString(connectionInfo));
}
return;
}
//We are called from an afterCompletion synchronization. Remove the MCI from the ManagedConnectionInfos
//so we don't close it twice
ManagedConnectionInfos managedConnectionInfos = ConnectorTransactionContext.get(transaction, this);
managedConnectionInfos.remove(connectionInfo.getManagedConnectionInfo());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"tx ended, return during synchronization afterCompletion " + infoString(connectionInfo));
}
}
} catch (SystemException e) {
//ignore
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"tx ended, returning connection " + infoString(connectionInfo));
}
internalReturn(connectionInfo, connectionReturnAction);
}
private void internalReturn(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
if (connectionInfo.getManagedConnectionInfo().hasConnectionHandles()) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"not returning connection from tx cache (has handles) " + infoString(connectionInfo));
}
return;
}
//No transaction, no handles, we return it.
next.returnConnection(connectionInfo, connectionReturnAction);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"completed return of connection through tx cache " + infoString(connectionInfo));
}
}
public void destroy() {
next.destroy();
}
public void afterCompletion(Object stuff) {
ManagedConnectionInfos managedConnectionInfos = (ManagedConnectionInfos) stuff;
ManagedConnectionInfo sharedMCI = managedConnectionInfos.getShared();
if (sharedMCI != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Transaction completed, attempting to return shared connection MCI: " + infoString(sharedMCI));
}
returnHandle(sharedMCI);
}
for (ManagedConnectionInfo managedConnectionInfo : managedConnectionInfos.getUnshared()) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Transaction completed, attempting to return unshared connection MCI: " + infoString(managedConnectionInfo));
}
returnHandle(managedConnectionInfo);
}
}
private void returnHandle(ManagedConnectionInfo managedConnectionInfo) {
ConnectionInfo connectionInfo = new ConnectionInfo();
connectionInfo.setManagedConnectionInfo(managedConnectionInfo);
internalReturn(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
}
private String infoString(Object connectionInfo) {
return "for tx caching interceptor " + this + " " + connectionInfo;
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[transactionManager=").append(transactionManager).append("]\n");
next.info(s);
}
public static class ManagedConnectionInfos {
private ManagedConnectionInfo shared;
private Set<ManagedConnectionInfo> unshared = new HashSet<ManagedConnectionInfo>(1);
public ManagedConnectionInfo getShared() {
return shared;
}
public void setShared(ManagedConnectionInfo shared) {
this.shared = shared;
}
public Set<ManagedConnectionInfo> getUnshared() {
return unshared;
}
public void addUnshared(ManagedConnectionInfo unsharedMCI) {
unshared.add(unsharedMCI);
}
public boolean containsUnshared(ManagedConnectionInfo unsharedMCI) {
return unshared.contains(unsharedMCI);
}
public void remove(ManagedConnectionInfo managedConnectionInfo) {
if (shared == managedConnectionInfo) {
shared = null;
} else {
unshared.remove(managedConnectionInfo);
}
}
}
}
| 6,428 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/MCFConnectionInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* MCFConnectionInterceptor.java
*
* @version $Rev$ $Date$
*/
public class MCFConnectionInterceptor implements ConnectionInterceptor {
protected static final Logger log = Logger.getLogger(MCFConnectionInterceptor.class.getName());
private ConnectionInterceptor stack;
public MCFConnectionInterceptor() {
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
if (mci.getManagedConnection() != null) {
return;
}
try {
ManagedConnection mc = mci.getManagedConnectionFactory().createManagedConnection(
mci.getSubject(),
mci.getConnectionRequestInfo());
mci.setManagedConnection(mc);
GeronimoConnectionEventListener listener = new GeronimoConnectionEventListener(stack, mci);
mci.setConnectionEventListener(listener);
mc.addConnectionEventListener(listener);
} catch (ResourceException re) {
log.log(Level.SEVERE, "Error occurred creating ManagedConnection for " + connectionInfo, re);
throw re;
}
}
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
ManagedConnection mc = mci.getManagedConnection();
try {
mc.destroy();
} catch (ResourceException e) {
//log and forget
} catch (Error e) {
throw e;
} catch (Throwable t) {
//log and forget
}
}
public void destroy() {
// MCF is the "tail" of the stack. So, we're all done...
}
public void setStack(ConnectionInterceptor stack) {
this.stack = stack;
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[stack=").append(stack).append("]\n");
s.append("<end>");
}
}
| 6,429 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/PoolingAttributes.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.geronimo.connector.outbound;
/**
* @version $Rev$ $Date$
*/
public interface PoolingAttributes {
int getPartitionCount();
int getConnectionCount();
int getIdleConnectionCount();
int getPartitionMaxSize();
void setPartitionMaxSize(int maxSize) throws InterruptedException;
int getPartitionMinSize();
void setPartitionMinSize(int minSize);
int getBlockingTimeoutMilliseconds();
void setBlockingTimeoutMilliseconds(int timeoutMilliseconds);
int getIdleTimeoutMinutes();
void setIdleTimeoutMinutes(int idleTimeoutMinutes);
}
| 6,430 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/SinglePoolMatchAllConnectionInterceptor.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.geronimo.connector.outbound;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.logging.Level;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionFactory;
/**
* This pool is the most spec-compliant pool. It can be used by itself with no partitioning.
* It is apt to be the slowest pool.
* For each connection request, it synchronizes access to the pool and asks the
* ManagedConnectionFactory for a match from among all managed connections. If none is found,
* it may discard a random existing connection, and creates a new connection.
*
* @version $Rev$ $Date$
*/
public class SinglePoolMatchAllConnectionInterceptor extends AbstractSinglePoolConnectionInterceptor {
private final Map<ManagedConnection, ManagedConnectionInfo> pool;
public SinglePoolMatchAllConnectionInterceptor(final ConnectionInterceptor next,
int maxSize,
int minSize,
int blockingTimeoutMilliseconds,
int idleTimeoutMinutes) {
super(next, maxSize, minSize, blockingTimeoutMilliseconds, idleTimeoutMinutes);
pool = new IdentityHashMap<ManagedConnection, ManagedConnectionInfo>(maxSize);
}
protected void internalGetConnection(ConnectionInfo connectionInfo) throws ResourceException {
synchronized (pool) {
if (destroyed) {
throw new ResourceException("ManagedConnection pool has been destroyed");
}
if (!pool.isEmpty()) {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
ManagedConnectionFactory managedConnectionFactory = mci.getManagedConnectionFactory();
ManagedConnection matchedMC =
managedConnectionFactory
.matchManagedConnections(pool.keySet(),
mci.getSubject(),
mci.getConnectionRequestInfo());
if (matchedMC != null) {
connectionInfo.setManagedConnectionInfo(pool.get(matchedMC));
pool.remove(matchedMC);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Supplying existing connection from pool " + this + " " + connectionInfo);
}
if (connectionCount < minSize) {
timer.schedule(new FillTask(connectionInfo), 10);
}
return;
}
}
//matching failed or pool is empty
//if pool is at maximum size, pick a cx to kill
if (connectionCount == maxSize) {
log.log(Level.FINEST,"Pool is at max size but no connections match, picking one to destroy");
Iterator iterator = pool.entrySet().iterator();
ManagedConnectionInfo kill = (ManagedConnectionInfo) ((Map.Entry) iterator.next()).getValue();
iterator.remove();
ConnectionInfo killInfo = new ConnectionInfo(kill);
internalReturn(killInfo, ConnectionReturnAction.DESTROY);
}
next.getConnection(connectionInfo);
connectionCount++;
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Supplying new connection from pool " + this + " " + connectionInfo);
}
if (connectionCount < minSize) {
timer.schedule(new FillTask(connectionInfo), 10);
}
}
}
protected void doAdd(ManagedConnectionInfo mci) {
pool.put(mci.getManagedConnection(), mci);
}
protected Object getPool() {
return pool;
}
protected boolean doRemove(ManagedConnectionInfo mci) {
return pool.remove(mci.getManagedConnection()) == null;
}
protected void internalDestroy() {
synchronized (pool) {
for (ManagedConnection managedConnection : pool.keySet()) {
try {
managedConnection.destroy();
} catch (ResourceException ignore) {
}
}
pool.clear();
}
}
public int getIdleConnectionCount() {
synchronized (pool) {
return pool.size();
}
}
protected void transferConnections(int maxSize, int shrinkNow) {
List<ConnectionInfo> killList = new ArrayList<ConnectionInfo>(shrinkNow);
Iterator<Map.Entry<ManagedConnection, ManagedConnectionInfo>> it = pool.entrySet().iterator();
for (int i = 0; i < shrinkNow; i++) {
killList.add(new ConnectionInfo(it.next().getValue()));
}
for (ConnectionInfo killInfo: killList) {
internalReturn(killInfo, ConnectionReturnAction.DESTROY);
}
}
protected void getExpiredManagedConnectionInfos(long threshold, List<ManagedConnectionInfo> killList) {
synchronized (pool) {
for (Iterator<Map.Entry<ManagedConnection, ManagedConnectionInfo>> mcis = pool.entrySet().iterator(); mcis.hasNext(); ) {
ManagedConnectionInfo mci = mcis.next().getValue();
if (mci.getLastUsed() < threshold) {
mcis.remove();
killList.add(mci);
connectionCount--;
}
}
}
}
public void info(StringBuilder s) {
s.append(getClass().getName());
s.append("[minSize=").append(minSize);
s.append(",maxSize=").append(maxSize);
s.append(",idleTimeoutMilliseconds=").append(idleTimeoutMilliseconds);
s.append(",blockingTimeoutMilliseconds=").append(blockingTimeoutMilliseconds).append("]\n");
next.info(s);
}
}
| 6,431 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
/**
* ConnectionInterceptor is the interface implemented by
* ConnectionManager "aspects". A ConnectionInterceptor
* implementation can provide one step of functionality for obtaining
* or releasing a ManagedConnection.
*
*
* @version $Rev$ $Date$
*/
public interface ConnectionInterceptor {
void getConnection(ConnectionInfo connectionInfo) throws ResourceException;
void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction);
void destroy();
void info(StringBuilder s);
} // ConnectionInterceptor
| 6,432 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/GeronimoConnectionEventListener.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.geronimo.connector.outbound;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.spi.ConnectionEvent;
import jakarta.resource.spi.ConnectionEventListener;
/**
* ConnectionEventListener.java
*
*
* Created: Thu Oct 2 14:57:43 2003
*
* @version 1.0
*/
public class GeronimoConnectionEventListener implements ConnectionEventListener {
private static Logger log = Logger.getLogger(GeronimoConnectionEventListener.class.getName());
private final ManagedConnectionInfo managedConnectionInfo;
private final ConnectionInterceptor stack;
private final List<ConnectionInfo> connectionInfos = new ArrayList<ConnectionInfo>();
private boolean errorOccurred = false;
public GeronimoConnectionEventListener(
final ConnectionInterceptor stack,
final ManagedConnectionInfo managedConnectionInfo) {
this.stack = stack;
this.managedConnectionInfo = managedConnectionInfo;
}
public void connectionClosed(ConnectionEvent connectionEvent) {
if (connectionEvent.getSource() != managedConnectionInfo.getManagedConnection()) {
throw new IllegalArgumentException(
"ConnectionClosed event received from wrong ManagedConnection. Expected "
+ managedConnectionInfo.getManagedConnection()
+ ", actual "
+ connectionEvent.getSource());
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"connectionClosed called with " + connectionEvent.getConnectionHandle() + " for MCI: " + managedConnectionInfo + " and MC: " + managedConnectionInfo.getManagedConnection());
}
ConnectionInfo ci = new ConnectionInfo(managedConnectionInfo);
ci.setConnectionHandle(connectionEvent.getConnectionHandle());
try {
stack.returnConnection(ci, ConnectionReturnAction.RETURN_HANDLE);
} catch (Throwable e) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"connectionClosed failed with " + connectionEvent.getConnectionHandle() + " for MCI: " + managedConnectionInfo + " and MC: " + managedConnectionInfo.getManagedConnection(), e);
}
if (e instanceof Error) {
throw (Error)e;
}
}
}
public void connectionErrorOccurred(ConnectionEvent connectionEvent) {
if (connectionEvent.getSource() != managedConnectionInfo.getManagedConnection()) {
throw new IllegalArgumentException(
"ConnectionError event received from wrong ManagedConnection. Expected "
+ managedConnectionInfo.getManagedConnection()
+ ", actual "
+ connectionEvent.getSource());
}
log.log(Level.WARNING,"connectionErrorOccurred called with " + connectionEvent.getConnectionHandle(), connectionEvent.getException());
boolean errorOccurred = this.errorOccurred;
this.errorOccurred = true;
if (!errorOccurred) {
ConnectionInfo ci = new ConnectionInfo(managedConnectionInfo);
ci.setConnectionHandle(connectionEvent.getConnectionHandle());
stack.returnConnection(ci, ConnectionReturnAction.DESTROY);
}
}
public void localTransactionStarted(ConnectionEvent event) {
//TODO implement this method
}
/**
* The <code>localTransactionCommitted</code> method
*
* @param event a <code>ConnectionEvent</code> value
* todo implement this method
*/
public void localTransactionCommitted(ConnectionEvent event) {
}
/**
* The <code>localTransactionRolledback</code> method
*
* @param event a <code>ConnectionEvent</code> value
* todo implement this method
*/
public void localTransactionRolledback(ConnectionEvent event) {
}
public void addConnectionInfo(ConnectionInfo connectionInfo) {
assert connectionInfo.getConnectionHandle() != null;
connectionInfos.add(connectionInfo);
}
public void removeConnectionInfo(ConnectionInfo connectionInfo) {
assert connectionInfo.getConnectionHandle() != null;
connectionInfos.remove(connectionInfo);
}
public boolean hasConnectionInfos() {
return !connectionInfos.isEmpty();
}
public void clearConnectionInfos() {
connectionInfos.clear();
}
public boolean hasConnectionInfo(ConnectionInfo connectionInfo) {
return connectionInfos.contains(connectionInfo);
}
public boolean isFirstConnectionInfo(ConnectionInfo connectionInfo) {
return !connectionInfos.isEmpty() && connectionInfos.get(0) == connectionInfo;
}
public Collection<ConnectionInfo> getConnectionInfos() {
return Collections.unmodifiableCollection(connectionInfos);
}
}
| 6,433 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/TCCLInterceptor.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.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
/**
* @version $Rev$ $Date$
*/
public class TCCLInterceptor implements ConnectionInterceptor{
private final ConnectionInterceptor next;
private final ClassLoader classLoader;
public TCCLInterceptor(ConnectionInterceptor next, ClassLoader classLoader) {
this.next = next;
this.classLoader = classLoader;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
Thread currentThread = Thread.currentThread();
ClassLoader oldClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(classLoader);
next.getConnection(connectionInfo);
} finally {
currentThread.setContextClassLoader(oldClassLoader);
}
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
Thread currentThread = Thread.currentThread();
ClassLoader oldClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(classLoader);
next.returnConnection(connectionInfo, connectionReturnAction);
} finally {
currentThread.setContextClassLoader(oldClassLoader);
}
}
public void destroy() {
this.next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[classLoader=").append(classLoader).append("]\n");
next.info(s);
}
}
| 6,434 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/SinglePoolConnectionInterceptor.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.geronimo.connector.outbound;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnection;
/**
* SinglePoolConnectionInterceptor chooses a single connection from the pool. If selectOneAssumeMatch
* is true, it simply returns the selected connection.
* THIS SHOULD BE USED ONLY IF MAXIMUM SPEED IS ESSENTIAL AND YOU HAVE THOROUGLY CHECKED THAT
* MATCHING WOULD SUCCEED ON THE SELECTED CONNECTION. (i.e., read the docs on your connector
* to find out how matching works)
* If selectOneAssumeMatch is false, it checks with the ManagedConnectionFactory that the
* selected connection does match before returning it: if not it throws an exception.
*
* @version $Rev$ $Date$
*/
public class SinglePoolConnectionInterceptor extends AbstractSinglePoolConnectionInterceptor {
private static final Logger log = Logger.getLogger(SinglePoolConnectionInterceptor.class.getName());
private boolean selectOneAssumeMatch;
//pool is mutable but only changed when protected by write lock on resizelock in superclass
private final List<ManagedConnectionInfo> pool;
public SinglePoolConnectionInterceptor(final ConnectionInterceptor next,
int maxSize,
int minSize,
int blockingTimeoutMilliseconds,
int idleTimeoutMinutes,
boolean selectOneAssumeMatch) {
super(next, maxSize, minSize, blockingTimeoutMilliseconds, idleTimeoutMinutes);
pool = new ArrayList<ManagedConnectionInfo>(maxSize);
this.selectOneAssumeMatch = selectOneAssumeMatch;
}
protected void internalGetConnection(ConnectionInfo connectionInfo) throws ResourceException {
synchronized (pool) {
if (destroyed) {
throw new ResourceException("ManagedConnection pool has been destroyed");
}
ManagedConnectionInfo newMCI;
if (pool.isEmpty()) {
next.getConnection(connectionInfo);
connectionCount++;
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Supplying new connection MCI: " + connectionInfo.getManagedConnectionInfo() + " MC: " + connectionInfo.getManagedConnectionInfo().getManagedConnection() + " from pool: " + this);
}
return;
} else {
newMCI = pool.remove(pool.size() - 1);
}
if (connectionCount < minSize) {
timer.schedule(new FillTask(connectionInfo), 10);
}
if (selectOneAssumeMatch) {
connectionInfo.setManagedConnectionInfo(newMCI);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Supplying pooled connection without checking matching MCI: " + connectionInfo.getManagedConnectionInfo() + " MC: " + connectionInfo.getManagedConnectionInfo().getManagedConnection() + " from pool: " + this);
}
return;
}
ManagedConnection matchedMC;
try {
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
matchedMC = newMCI.getManagedConnectionFactory().matchManagedConnections(Collections.singleton(newMCI.getManagedConnection()),
mci.getSubject(),
mci.getConnectionRequestInfo());
} catch (ResourceException e) {
//something is wrong: destroy connection, rethrow, release permit
ConnectionInfo returnCI = new ConnectionInfo();
returnCI.setManagedConnectionInfo(newMCI);
returnConnection(returnCI, ConnectionReturnAction.DESTROY);
throw e;
}
if (matchedMC != null) {
connectionInfo.setManagedConnectionInfo(newMCI);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Supplying pooled connection MCI: " + connectionInfo.getManagedConnectionInfo() + " from pool: " + this);
}
} else {
//matching failed.
ConnectionInfo returnCI = new ConnectionInfo();
returnCI.setManagedConnectionInfo(newMCI);
returnConnection(returnCI, ConnectionReturnAction.RETURN_HANDLE);
throw new ResourceException("The pooling strategy does not match the MatchManagedConnections implementation. Please investigate and reconfigure this pool");
}
}
}
protected void internalDestroy() {
synchronized (pool) {
while (!pool.isEmpty()) {
ManagedConnection mc = pool.remove(pool.size() - 1).getManagedConnection();
if (mc != null) {
try {
mc.destroy();
}
catch (ResourceException re) {
//ignore
}
}
}
}
}
protected Object getPool() {
return pool;
}
protected void doAdd(ManagedConnectionInfo mci) {
pool.add(mci);
}
/**
* @param mci managedConnectionInfo to remove from pool
* @return true if mci was not in pool already, false if mci was in pool already.
*/
protected boolean doRemove(ManagedConnectionInfo mci) {
log.info("Removing " + mci + " from pool " + this);
return !pool.remove(mci);
}
protected void transferConnections(int maxSize, int shrinkNow) {
for (int i = 0; i < shrinkNow; i++) {
ConnectionInfo killInfo = new ConnectionInfo(pool.get(0));
internalReturn(killInfo, ConnectionReturnAction.DESTROY);
}
}
public int getIdleConnectionCount() {
return pool.size();
}
protected void getExpiredManagedConnectionInfos(long threshold, List<ManagedConnectionInfo> killList) {
synchronized (pool) {
for (Iterator<ManagedConnectionInfo> mcis = pool.iterator(); mcis.hasNext(); ) {
ManagedConnectionInfo mci = mcis.next();
if (mci.getLastUsed() < threshold) {
mcis.remove();
killList.add(mci);
connectionCount--;
}
}
}
}
public void info(StringBuilder s) {
s.append(getClass().getName());
s.append("[minSize=").append(minSize);
s.append(",maxSize=").append(maxSize);
s.append(",idleTimeoutMilliseconds=").append(idleTimeoutMilliseconds);
s.append(",blockingTimeoutMilliseconds=").append(blockingTimeoutMilliseconds);
s.append(".selectOneAssumeMatch=").append(selectOneAssumeMatch).append("]\n");
next.info(s);
}
}
| 6,435 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/ConnectionReturnAction.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.geronimo.connector.outbound;
/**
* ConnectionReturnAction.java
*
*
* Created: Thu Oct 2 15:11:39 2003
*
* @author <a href="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
* @version 1.0
*/
public class ConnectionReturnAction {
private final String name;
public final static ConnectionReturnAction RETURN_HANDLE =
new ConnectionReturnAction("RETURN_HANDLE");
public final static ConnectionReturnAction DESTROY =
new ConnectionReturnAction("DESTROY");
private ConnectionReturnAction(String name) {
this.name = name;
}
@Override
public String toString() {
return "ConnectionReturnAction{" + name + '}';
}
}
| 6,436 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/GenericConnectionManager.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.geronimo.connector.outbound;
import jakarta.resource.spi.ManagedConnectionFactory;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.LocalTransactions;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.NoTransactions;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PartitionedPool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.TransactionSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.XATransactions;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTracker;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* GenericConnectionManager sets up a connection manager stack according to the
* policies described in the attributes.
*
* @version $Rev$ $Date$
*/
public class GenericConnectionManager extends AbstractConnectionManager {
protected static final Logger log = Logger.getLogger(GenericConnectionManager.class.getName());
//default constructor to support externalizable subclasses
public GenericConnectionManager() {
super();
}
/**
*
* @param transactionSupport configuration of transaction support
* @param pooling configuration of pooling
* @param subjectSource If not null, use container managed security, getting the Subject from the SubjectSource
* @param connectionTracker tracks connections between calls as needed
* @param transactionManager transaction manager
* @param mcf
* @param name name
* @param classLoader classloader this component is running in.
*/
public GenericConnectionManager(TransactionSupport transactionSupport,
PoolingSupport pooling,
SubjectSource subjectSource,
ConnectionTracker connectionTracker,
RecoverableTransactionManager transactionManager,
ManagedConnectionFactory mcf,
String name,
ClassLoader classLoader) {
super(new InterceptorsImpl(transactionSupport, pooling, subjectSource, name, connectionTracker, transactionManager, mcf, classLoader), transactionManager, mcf, name);
}
private static class InterceptorsImpl implements AbstractConnectionManager.Interceptors {
private final ConnectionInterceptor stack;
private final ConnectionInterceptor recoveryStack;
private final PoolingSupport poolingSupport;
/**
* Order of constructed interceptors:
* <p/>
* ConnectionTrackingInterceptor (connectionTracker != null)
* TCCLInterceptor
* ConnectionHandleInterceptor
* TransactionCachingInterceptor (useTransactions & useTransactionCaching)
* TransactionEnlistingInterceptor (useTransactions)
* SubjectInterceptor (realmBridge != null)
* SinglePoolConnectionInterceptor or MultiPoolConnectionInterceptor
* LocalXAResourceInsertionInterceptor or XAResourceInsertionInterceptor (useTransactions (&localTransactions))
* MCFConnectionInterceptor
*/
public InterceptorsImpl(TransactionSupport transactionSupport,
PoolingSupport pooling,
SubjectSource subjectSource,
String name,
ConnectionTracker connectionTracker,
TransactionManager transactionManager,
ManagedConnectionFactory mcf, ClassLoader classLoader) {
//check for consistency between attributes
if (subjectSource == null && pooling instanceof PartitionedPool && ((PartitionedPool) pooling).isPartitionBySubject()) {
throw new IllegalStateException("To use Subject in pooling, you need a SecurityDomain");
}
if (mcf == null) {
throw new NullPointerException("No ManagedConnectionFactory supplied for " + name);
}
if (mcf instanceof jakarta.resource.spi.TransactionSupport) {
jakarta.resource.spi.TransactionSupport txSupport = (jakarta.resource.spi.TransactionSupport)mcf;
jakarta.resource.spi.TransactionSupport.TransactionSupportLevel txSupportLevel = txSupport.getTransactionSupport();
log.info("Runtime TransactionSupport level: " + txSupportLevel);
if (txSupportLevel != null) {
if (txSupportLevel == jakarta.resource.spi.TransactionSupport.TransactionSupportLevel.NoTransaction) {
transactionSupport = NoTransactions.INSTANCE;
} else if (txSupportLevel == jakarta.resource.spi.TransactionSupport.TransactionSupportLevel.LocalTransaction) {
if (transactionSupport != NoTransactions.INSTANCE) {
transactionSupport = LocalTransactions.INSTANCE;
}
} else {
if (transactionSupport != NoTransactions.INSTANCE && transactionSupport != LocalTransactions.INSTANCE) {
transactionSupport = new XATransactions(true, false);
}
}
}
} else {
log.info("No runtime TransactionSupport");
}
//Set up the interceptor stack
MCFConnectionInterceptor tail = new MCFConnectionInterceptor();
ConnectionInterceptor stack = tail;
stack = transactionSupport.addXAResourceInsertionInterceptor(stack, name);
stack = pooling.addPoolingInterceptors(stack);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Connection Manager " + name + " installed pool " + stack);
}
this.poolingSupport = pooling;
stack = transactionSupport.addTransactionInterceptors(stack, transactionManager);
if (subjectSource != null) {
stack = new SubjectInterceptor(stack, subjectSource);
}
if (transactionSupport.isRecoverable()) {
this.recoveryStack = new TCCLInterceptor(stack, classLoader);
} else {
this.recoveryStack = null;
}
stack = new ConnectionHandleInterceptor(stack);
stack = new TCCLInterceptor(stack, classLoader);
if (connectionTracker != null) {
stack = new ConnectionTrackingInterceptor(stack,
name,
connectionTracker);
}
tail.setStack(stack);
this.stack = stack;
if (log.isLoggable(Level.FINE)) {
StringBuilder s = new StringBuilder("ConnectionManager Interceptor stack;\n");
stack.info(s);
log.log(Level.FINE, s.toString());
}
}
public ConnectionInterceptor getStack() {
return stack;
}
public ConnectionInterceptor getRecoveryStack() {
return recoveryStack;
}
public PoolingSupport getPoolingAttributes() {
return poolingSupport;
}
}
}
| 6,437 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/PartitionedPool.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.geronimo.connector.outbound.connectionmanagerconfig;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.MultiPoolConnectionInterceptor;
import org.apache.geronimo.connector.outbound.PoolingAttributes;
/**
* @version $Rev$ $Date$
*/
public class PartitionedPool implements PoolingSupport {
private static final long serialVersionUID = -4843669262711657990L;
private boolean partitionByConnectionRequestInfo;
private boolean partitionBySubject;
private final SinglePool singlePool;
private transient PoolingAttributes poolingAttributes;
public PartitionedPool(int maxSize, int minSize, int blockingTimeoutMilliseconds, int idleTimeoutMinutes, boolean matchOne, boolean matchAll, boolean selectOneAssumeMatch, boolean partitionByConnectionRequestInfo, boolean partitionBySubject) {
singlePool = new SinglePool(maxSize, minSize, blockingTimeoutMilliseconds, idleTimeoutMinutes, matchOne, matchAll, selectOneAssumeMatch);
this.partitionByConnectionRequestInfo = partitionByConnectionRequestInfo;
this.partitionBySubject = partitionBySubject;
}
public boolean isPartitionByConnectionRequestInfo() {
return partitionByConnectionRequestInfo;
}
public void setPartitionByConnectionRequestInfo(boolean partitionByConnectionRequestInfo) {
this.partitionByConnectionRequestInfo = partitionByConnectionRequestInfo;
}
public boolean isPartitionBySubject() {
return partitionBySubject;
}
public void setPartitionBySubject(boolean partitionBySubject) {
this.partitionBySubject = partitionBySubject;
}
public int getMaxSize() {
return singlePool.getMaxSize();
}
public void setMaxSize(int maxSize) {
singlePool.setMaxSize(maxSize);
}
public int getBlockingTimeoutMilliseconds() {
return poolingAttributes.getBlockingTimeoutMilliseconds();
}
public void setBlockingTimeoutMilliseconds(int blockingTimeoutMilliseconds) {
poolingAttributes.setBlockingTimeoutMilliseconds(blockingTimeoutMilliseconds);
}
public int getIdleTimeoutMinutes() {
return poolingAttributes.getIdleTimeoutMinutes();
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
poolingAttributes.setIdleTimeoutMinutes(idleTimeoutMinutes);
}
public boolean isMatchOne() {
return singlePool.isMatchOne();
}
public void setMatchOne(boolean matchOne) {
singlePool.setMatchOne(matchOne);
}
public boolean isMatchAll() {
return singlePool.isMatchAll();
}
public void setMatchAll(boolean matchAll) {
singlePool.setMatchAll(matchAll);
}
public boolean isSelectOneAssumeMatch() {
return singlePool.isSelectOneAssumeMatch();
}
public void setSelectOneAssumeMatch(boolean selectOneAssumeMatch) {
singlePool.setSelectOneAssumeMatch(selectOneAssumeMatch);
}
public ConnectionInterceptor addPoolingInterceptors(ConnectionInterceptor tail) {
MultiPoolConnectionInterceptor pool = new MultiPoolConnectionInterceptor(tail,
singlePool,
isPartitionBySubject(),
isPartitionByConnectionRequestInfo());
this.poolingAttributes = pool;
return pool;
}
public int getPartitionCount() {
return poolingAttributes.getPartitionCount();
}
public int getPartitionMaxSize() {
return poolingAttributes.getPartitionMaxSize();
}
public void setPartitionMaxSize(int maxSize) throws InterruptedException {
poolingAttributes.setPartitionMaxSize(maxSize);
}
public int getPartitionMinSize() {
return poolingAttributes.getPartitionMinSize();
}
public void setPartitionMinSize(int minSize) {
poolingAttributes.setPartitionMinSize(minSize);
}
public int getIdleConnectionCount() {
return poolingAttributes.getIdleConnectionCount();
}
public int getConnectionCount() {
return poolingAttributes.getConnectionCount();
}
}
| 6,438 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/LocalTransactions.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.geronimo.connector.outbound.connectionmanagerconfig;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.LocalXAResourceInsertionInterceptor;
import org.apache.geronimo.connector.outbound.TransactionCachingInterceptor;
import org.apache.geronimo.connector.outbound.TransactionEnlistingInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class LocalTransactions extends TransactionSupport {
public static final TransactionSupport INSTANCE = new LocalTransactions();
private LocalTransactions() {
}
public ConnectionInterceptor addXAResourceInsertionInterceptor(ConnectionInterceptor stack, String name) {
return new LocalXAResourceInsertionInterceptor(stack, name);
}
public ConnectionInterceptor addTransactionInterceptors(ConnectionInterceptor stack, TransactionManager transactionManager) {
stack = new TransactionEnlistingInterceptor(stack, transactionManager);
return new TransactionCachingInterceptor(stack, transactionManager);
}
public boolean isRecoverable() {
return false;
}
}
| 6,439 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/PoolingSupport.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.geronimo.connector.outbound.connectionmanagerconfig;
import java.io.Serializable;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.PoolingAttributes;
/**
* @version $Rev$ $Date$
*/
public interface PoolingSupport extends Serializable, PoolingAttributes {
ConnectionInterceptor addPoolingInterceptors(ConnectionInterceptor tail);
}
| 6,440 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/TransactionLog.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.geronimo.connector.outbound.connectionmanagerconfig;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.TransactionCachingInterceptor;
import org.apache.geronimo.connector.outbound.TransactionEnlistingInterceptor;
import org.apache.geronimo.connector.outbound.transactionlog.LogXAResourceInsertionInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class TransactionLog extends TransactionSupport
{
public static final TransactionSupport INSTANCE = new TransactionLog();
private TransactionLog() {
}
public ConnectionInterceptor addXAResourceInsertionInterceptor(ConnectionInterceptor stack, String name) {
return new LogXAResourceInsertionInterceptor(stack, name);
}
public ConnectionInterceptor addTransactionInterceptors(ConnectionInterceptor stack, TransactionManager transactionManager) {
stack = new TransactionEnlistingInterceptor(stack, transactionManager);
return new TransactionCachingInterceptor(stack, transactionManager);
}
public boolean isRecoverable() {
return false;
}
}
| 6,441 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/XATransactions.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.geronimo.connector.outbound.connectionmanagerconfig;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ThreadLocalCachingConnectionInterceptor;
import org.apache.geronimo.connector.outbound.TransactionCachingInterceptor;
import org.apache.geronimo.connector.outbound.TransactionEnlistingInterceptor;
import org.apache.geronimo.connector.outbound.XAResourceInsertionInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class XATransactions extends TransactionSupport {
private boolean useTransactionCaching;
private boolean useThreadCaching;
public XATransactions(boolean useTransactionCaching, boolean useThreadCaching) {
this.useTransactionCaching = useTransactionCaching;
this.useThreadCaching = useThreadCaching;
}
public boolean isUseTransactionCaching() {
return useTransactionCaching;
}
public void setUseTransactionCaching(boolean useTransactionCaching) {
this.useTransactionCaching = useTransactionCaching;
}
public boolean isUseThreadCaching() {
return useThreadCaching;
}
public void setUseThreadCaching(boolean useThreadCaching) {
this.useThreadCaching = useThreadCaching;
}
public ConnectionInterceptor addXAResourceInsertionInterceptor(ConnectionInterceptor stack, String name) {
return new XAResourceInsertionInterceptor(stack, name);
}
public ConnectionInterceptor addTransactionInterceptors(ConnectionInterceptor stack, TransactionManager transactionManager) {
//experimental thread local caching
if (isUseThreadCaching()) {
//useMatching should be configurable
stack = new ThreadLocalCachingConnectionInterceptor(stack, false);
}
stack = new TransactionEnlistingInterceptor(stack, transactionManager);
if (isUseTransactionCaching()) {
stack = new TransactionCachingInterceptor(stack, transactionManager);
}
return stack;
}
public boolean isRecoverable() {
return true;
}
}
| 6,442 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/SinglePool.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.geronimo.connector.outbound.connectionmanagerconfig;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.PoolingAttributes;
import org.apache.geronimo.connector.outbound.SinglePoolConnectionInterceptor;
import org.apache.geronimo.connector.outbound.SinglePoolMatchAllConnectionInterceptor;
/**
* @version $Rev$ $Date$
*/
public class SinglePool implements PoolingSupport {
private static final long serialVersionUID = -1190636112655036636L;
private int maxSize;
private int minSize;
private int blockingTimeoutMilliseconds;
private int idleTimeoutMinutes;
private boolean matchOne;
private boolean matchAll;
private boolean selectOneAssumeMatch;
private transient PoolingAttributes pool;
public SinglePool(int maxSize, int minSize, int blockingTimeoutMilliseconds, int idleTimeoutMinutes, boolean matchOne, boolean matchAll, boolean selectOneAssumeMatch) {
this.maxSize = maxSize;
this.minSize = minSize;
this.blockingTimeoutMilliseconds = blockingTimeoutMilliseconds;
this.idleTimeoutMinutes = idleTimeoutMinutes;
this.matchOne = matchOne;
this.matchAll = matchAll;
this.selectOneAssumeMatch = selectOneAssumeMatch;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int getMinSize() {
return minSize;
}
public void setMinSize(int minSize) {
this.minSize = minSize;
}
public int getBlockingTimeoutMilliseconds() {
return blockingTimeoutMilliseconds;
}
public void setBlockingTimeoutMilliseconds(int blockingTimeoutMilliseconds) {
this.blockingTimeoutMilliseconds = blockingTimeoutMilliseconds;
if (pool != null) {
pool.setBlockingTimeoutMilliseconds(blockingTimeoutMilliseconds);
}
}
public int getIdleTimeoutMinutes() {
return idleTimeoutMinutes;
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
this.idleTimeoutMinutes = idleTimeoutMinutes;
if (pool != null) {
pool.setIdleTimeoutMinutes(idleTimeoutMinutes);
}
}
public boolean isMatchOne() {
return matchOne;
}
public void setMatchOne(boolean matchOne) {
this.matchOne = matchOne;
}
public boolean isMatchAll() {
return matchAll;
}
public void setMatchAll(boolean matchAll) {
this.matchAll = matchAll;
}
public boolean isSelectOneAssumeMatch() {
return selectOneAssumeMatch;
}
public void setSelectOneAssumeMatch(boolean selectOneAssumeMatch) {
this.selectOneAssumeMatch = selectOneAssumeMatch;
}
public ConnectionInterceptor addPoolingInterceptors(ConnectionInterceptor tail) {
if (isMatchAll()) {
SinglePoolMatchAllConnectionInterceptor pool = new SinglePoolMatchAllConnectionInterceptor(tail,
getMaxSize(),
getMinSize(),
getBlockingTimeoutMilliseconds(),
getIdleTimeoutMinutes());
this.pool = pool;
return pool;
} else {
SinglePoolConnectionInterceptor pool = new SinglePoolConnectionInterceptor(tail,
getMaxSize(),
getMinSize(),
getBlockingTimeoutMilliseconds(),
getIdleTimeoutMinutes(),
isSelectOneAssumeMatch());
this.pool = pool;
return pool;
}
}
public int getPartitionCount() {
return 1;
}
public int getPartitionMaxSize() {
return maxSize;
}
public void setPartitionMaxSize(int maxSize) throws InterruptedException {
if (pool != null) {
pool.setPartitionMaxSize(maxSize);
}
this.maxSize = maxSize;
}
public int getPartitionMinSize() {
return minSize;
}
public void setPartitionMinSize(int minSize) {
if (pool != null) {
pool.setPartitionMinSize(minSize);
}
this.minSize = minSize;
}
public int getIdleConnectionCount() {
return pool == null ? 0 : pool.getIdleConnectionCount();
}
public int getConnectionCount() {
return pool == null ? 0 : pool.getConnectionCount();
}
}
| 6,443 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/TransactionSupport.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.geronimo.connector.outbound.connectionmanagerconfig;
import java.io.Serializable;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public abstract class TransactionSupport implements Serializable {
public abstract ConnectionInterceptor addXAResourceInsertionInterceptor(ConnectionInterceptor stack, String name);
public abstract ConnectionInterceptor addTransactionInterceptors(ConnectionInterceptor stack, TransactionManager transactionManager);
public abstract boolean isRecoverable();
}
| 6,444 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/NoPool.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.geronimo.connector.outbound.connectionmanagerconfig;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class NoPool implements PoolingSupport {
private static final long serialVersionUID = -7871656583080873750L;
public ConnectionInterceptor addPoolingInterceptors(ConnectionInterceptor tail) {
return tail;
}
public int getPartitionCount() {
return 0;
}
public int getIdleConnectionCount() {
return 0;
}
public int getConnectionCount() {
return 0;
}
public int getPartitionMaxSize() {
return 0;
}
public void setPartitionMaxSize(int maxSize) {
}
public int getPartitionMinSize() {
return 0;
}
public void setPartitionMinSize(int minSize) {
}
public int getBlockingTimeoutMilliseconds() {
return 0;
}
public void setBlockingTimeoutMilliseconds(int timeoutMilliseconds) {
}
public int getIdleTimeoutMinutes() {
return 0;
}
public void setIdleTimeoutMinutes(int idleTimeoutMinutes) {
}
}
| 6,445 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectionmanagerconfig/NoTransactions.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.geronimo.connector.outbound.connectionmanagerconfig;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class NoTransactions extends TransactionSupport {
public static final TransactionSupport INSTANCE = new NoTransactions();
private NoTransactions() {
}
public ConnectionInterceptor addXAResourceInsertionInterceptor(ConnectionInterceptor stack, String name) {
return stack;
}
public ConnectionInterceptor addTransactionInterceptors(ConnectionInterceptor stack, TransactionManager transactionManager) {
return stack;
}
public boolean isRecoverable() {
return false;
}
}
| 6,446 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/security/ResourcePrincipal.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.geronimo.connector.outbound.security;
import java.io.Serializable;
import java.security.Principal;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ResourcePrincipal implements Principal, Serializable {
private final String resourcePrincipal;
public ResourcePrincipal(String resourcePrincipal) {
this.resourcePrincipal = resourcePrincipal;
if (resourcePrincipal == null) {
throw new NullPointerException("No resource principal name supplied");
}
}
public String getName() {
return resourcePrincipal;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResourcePrincipal that = (ResourcePrincipal) o;
return resourcePrincipal.equals(that.resourcePrincipal);
}
public int hashCode() {
return resourcePrincipal.hashCode();
}
}
| 6,447 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectionTracker.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.geronimo.connector.outbound.connectiontracking;
import jakarta.resource.ResourceException;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface ConnectionTracker {
void handleObtained(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
boolean reassociate) throws ResourceException;
void handleReleased(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction);
void setEnvironment(ConnectionInfo connectionInfo, String key);
}
| 6,448 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectionTrackingCoordinator.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.geronimo.connector.outbound.connectiontracking;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.DissociatableManagedConnection;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ManagedConnectionInfo;
/**
* ConnectionTrackingCoordinator tracks connections that are in use by
* components such as EJB's. The component must notify the ccm
* when a method enters and exits. On entrance, the ccm will
* notify ConnectionManager stacks so the stack can make sure all
* connection handles left open from previous method calls are
* attached to ManagedConnections of the correct security context, and
* the ManagedConnections are enrolled in any current transaction.
* On exit, the ccm will notify ConnectionManager stacks of the handles
* left open, so they may be disassociated if appropriate.
* In addition, when a UserTransaction is started the ccm will notify
* ConnectionManager stacks so the existing ManagedConnections can be
* enrolled properly.
*
* @version $Rev$ $Date$
*/
public class ConnectionTrackingCoordinator implements TrackedConnectionAssociator, ConnectionTracker {
private static final Logger log = Logger.getLogger(ConnectionTrackingCoordinator.class.getName());
private final boolean lazyConnect;
private final ThreadLocal<ConnectorInstanceContext> currentInstanceContexts = new ThreadLocal<ConnectorInstanceContext>();
private final ConcurrentMap<ConnectionInfo,Object> proxiesByConnectionInfo = new ConcurrentHashMap<ConnectionInfo,Object>();
public ConnectionTrackingCoordinator() {
this(false);
}
public ConnectionTrackingCoordinator(boolean lazyConnect) {
this.lazyConnect = lazyConnect;
}
public boolean isLazyConnect() {
return lazyConnect;
}
public ConnectorInstanceContext enter(ConnectorInstanceContext newContext) throws ResourceException {
ConnectorInstanceContext oldContext = currentInstanceContexts.get();
currentInstanceContexts.set(newContext);
associateConnections(newContext);
return oldContext;
}
private void associateConnections(ConnectorInstanceContext context) throws ResourceException {
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerToManagedConnectionInfoMap = context.getConnectionManagerMap();
for (Map.Entry<ConnectionTrackingInterceptor, Set<ConnectionInfo>> entry : connectionManagerToManagedConnectionInfoMap.entrySet()) {
ConnectionTrackingInterceptor mcci = entry.getKey();
Set<ConnectionInfo> connections = entry.getValue();
mcci.enter(connections);
}
}
public void newTransaction() throws ResourceException {
ConnectorInstanceContext currentContext = currentInstanceContexts.get();
if (currentContext == null) {
return;
}
associateConnections(currentContext);
}
public void exit(ConnectorInstanceContext oldContext) throws ResourceException {
ConnectorInstanceContext currentContext = currentInstanceContexts.get();
try {
// for each connection type opened in this componet
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> resources = currentContext.getConnectionManagerMap();
for (Iterator<Map.Entry<ConnectionTrackingInterceptor, Set<ConnectionInfo>>> iterator = resources.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<ConnectionTrackingInterceptor, Set<ConnectionInfo>> entry = iterator.next();
ConnectionTrackingInterceptor mcci = entry.getKey();
Set<ConnectionInfo> connections = entry.getValue();
// release proxy connections
if (lazyConnect) {
for (ConnectionInfo connectionInfo : connections) {
releaseProxyConnection(connectionInfo);
}
}
// use connection interceptor to dissociate connections that support disassociation
mcci.exit(connections);
// if no connection remain clear context... we could support automatic commit, rollback or exception here
if (connections.isEmpty()) {
iterator.remove();
}
}
} finally {
// when lazy we do not need or want to track open connections... they will automatically reconnect
if (lazyConnect) {
currentContext.getConnectionManagerMap().clear();
}
currentInstanceContexts.set(oldContext);
}
}
/**
* A new connection (handle) has been obtained. If we are within a component context, store the connection handle
* so we can disassociate connections that support disassociation on exit.
* @param connectionTrackingInterceptor our interceptor in the connection manager which is used to disassociate the connections
* @param connectionInfo the connection that was obtained
* @param reassociate
*/
public void handleObtained(ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
boolean reassociate) throws ResourceException {
ConnectorInstanceContext currentContext = currentInstanceContexts.get();
if (currentContext == null) {
return;
}
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> resources = currentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = resources.get(connectionTrackingInterceptor);
if (infos == null) {
infos = new HashSet<ConnectionInfo>();
resources.put(connectionTrackingInterceptor, infos);
}
infos.add(connectionInfo);
// if lazyConnect, we must proxy so we know when to connect the proxy
if (!reassociate && lazyConnect) {
proxyConnection(connectionTrackingInterceptor, connectionInfo);
}
}
/**
* A connection (handle) has been released or destroyed. If we are within a component context, remove the connection
* handle from the context.
* @param connectionTrackingInterceptor our interceptor in the connection manager
* @param connectionInfo the connection that was released
* @param connectionReturnAction
*/
public void handleReleased(ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
ConnectorInstanceContext currentContext = currentInstanceContexts.get();
if (currentContext == null) {
return;
}
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> resources = currentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = resources.get(connectionTrackingInterceptor);
if (infos != null) {
if (connectionInfo.getConnectionHandle() == null) {
//destroy was called as a result of an error
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
Collection<ConnectionInfo> toRemove = mci.getConnectionInfos();
infos.removeAll(toRemove);
} else {
infos.remove(connectionInfo);
}
} else {
if ( log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"No infos found for handle " + connectionInfo.getConnectionHandle() +
" for MCI: " + connectionInfo.getManagedConnectionInfo() +
" for MC: " + connectionInfo.getManagedConnectionInfo().getManagedConnection() +
" for CTI: " + connectionTrackingInterceptor, new Exception("Stack Trace"));
}
}
// NOTE: This method is also called by DissociatableManagedConnection when a connection has been
// dissociated in addition to the normal connection closed notification, but this is not a problem
// because DissociatableManagedConnection are not proied so this method will have no effect
closeProxyConnection(connectionInfo);
}
/**
* If we are within a component context, before a connection is obtained, set the connection unshareable and
* applicationManagedSecurity properties so the correct connection type is obtained.
* @param connectionInfo the connection to be obtained
* @param key the unique id of the connection manager
*/
public void setEnvironment(ConnectionInfo connectionInfo, String key) {
ConnectorInstanceContext currentContext = currentInstanceContexts.get();
if (currentContext != null) {
// is this resource unshareable in this component context
Set<String> unshareableResources = currentContext.getUnshareableResources();
boolean unshareable = unshareableResources.contains(key);
connectionInfo.setUnshareable(unshareable);
// does this resource use application managed security in this component context
Set<String> applicationManagedSecurityResources = currentContext.getApplicationManagedSecurityResources();
boolean applicationManagedSecurity = applicationManagedSecurityResources.contains(key);
connectionInfo.setApplicationManagedSecurity(applicationManagedSecurity);
}
}
private void proxyConnection(ConnectionTrackingInterceptor connectionTrackingInterceptor, ConnectionInfo connectionInfo) throws ResourceException {
// if this connection already has a proxy no need to create another
if (connectionInfo.getConnectionProxy() != null) return;
// DissociatableManagedConnection do not need to be proxied
if (connectionInfo.getManagedConnectionInfo().getManagedConnection() instanceof DissociatableManagedConnection) {
return;
}
try {
Object handle = connectionInfo.getConnectionHandle();
ConnectionInvocationHandler invocationHandler = new ConnectionInvocationHandler(connectionTrackingInterceptor, connectionInfo, handle);
Object proxy = Proxy.newProxyInstance(getClassLoader(handle), handle.getClass().getInterfaces(), invocationHandler);
// add it to our map... if the map already has a proxy for this connection, use the existing one
Object existingProxy = proxiesByConnectionInfo.putIfAbsent(connectionInfo, proxy);
if (existingProxy != null) proxy = existingProxy;
connectionInfo.setConnectionProxy(proxy);
} catch (Throwable e) {
throw new ResourceException("Unable to construct connection proxy", e);
}
}
private void releaseProxyConnection(ConnectionInfo connectionInfo) {
ConnectionInvocationHandler invocationHandler = getConnectionInvocationHandler(connectionInfo);
if (invocationHandler != null) {
invocationHandler.releaseHandle();
}
}
private void closeProxyConnection(ConnectionInfo connectionInfo) {
ConnectionInvocationHandler invocationHandler = getConnectionInvocationHandler(connectionInfo);
if (invocationHandler != null) {
invocationHandler.close();
proxiesByConnectionInfo.remove(connectionInfo);
connectionInfo.setConnectionProxy(null);
}
}
// Favor the thread context class loader for proxy construction
private ClassLoader getClassLoader(Object handle) {
ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
if (threadClassLoader != null) {
return threadClassLoader;
}
return handle.getClass().getClassLoader();
}
private ConnectionInvocationHandler getConnectionInvocationHandler(ConnectionInfo connectionInfo) {
Object proxy = connectionInfo.getConnectionProxy();
if (proxy == null) {
proxy = proxiesByConnectionInfo.get(connectionInfo);
}
// no proxy or proxy already destroyed
if (proxy == null) return null;
if (Proxy.isProxyClass(proxy.getClass())) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy);
if (invocationHandler instanceof ConnectionInvocationHandler) {
return (ConnectionInvocationHandler) invocationHandler;
}
}
return null;
}
public static class ConnectionInvocationHandler implements InvocationHandler {
private ConnectionTrackingInterceptor connectionTrackingInterceptor;
private ConnectionInfo connectionInfo;
private final Object handle;
private boolean released = false;
public ConnectionInvocationHandler(ConnectionTrackingInterceptor connectionTrackingInterceptor, ConnectionInfo connectionInfo, Object handle) {
this.connectionTrackingInterceptor = connectionTrackingInterceptor;
this.connectionInfo = connectionInfo;
this.handle = handle;
}
public Object invoke(Object object, Method method, Object[] args) throws Throwable {
Object handle;
if (method.getDeclaringClass() == Object.class) {
if (method.getName().equals("finalize")) {
// ignore the handle will get called if it implemented the method
return null;
}
if (method.getName().equals("clone")) {
throw new CloneNotSupportedException();
}
// for equals, hashCode and toString don't activate handle
synchronized (this) {
handle = this.handle;
}
} else {
handle = getHandle();
}
try {
Object value = method.invoke(handle, args);
return value;
} catch (InvocationTargetException ite) {
// catch InvocationTargetExceptions and turn them into the target exception (if there is one)
Throwable t = ite.getTargetException();
if (t != null) {
throw t;
}
throw ite;
}
}
public synchronized boolean isReleased() {
return released;
}
public synchronized void releaseHandle() {
released = true;
}
public synchronized void close() {
connectionTrackingInterceptor = null;
connectionInfo = null;
released = true;
}
public synchronized Object getHandle() {
if (connectionTrackingInterceptor == null) {
// connection has been closed... send invocations directly to the handle
// which will throw an exception or in some clases like JDBC connection.close()
// ignore the invocation
return handle;
}
if (released) {
try {
connectionTrackingInterceptor.reassociateConnection(connectionInfo);
} catch (ResourceException e) {
throw (IllegalStateException) new IllegalStateException("Could not obtain a physical connection").initCause(e);
}
released = false;
}
return handle;
}
}
}
| 6,449 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectorInstanceContext.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.geronimo.connector.outbound.connectiontracking;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import java.util.Map;
import java.util.Set;
/**
* @version $Rev$ $Date$
*/
public interface ConnectorInstanceContext {
/**
* IMPORTANT INVARIANT: this should always return a map, never null.
* @return map of ConnectionManager to (list of ) managed connection info objects.
*/
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> getConnectionManagerMap();
Set<String> getUnshareableResources();
Set<String> getApplicationManagedSecurityResources();
}
| 6,450 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/SharedConnectorInstanceContext.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.geronimo.connector.outbound.connectiontracking;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @version $Rev$ $Date$
*/
public class SharedConnectorInstanceContext implements ConnectorInstanceContext {
private Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = new HashMap<ConnectionTrackingInterceptor, Set<ConnectionInfo>>();
private final Set<String> unshareableResources;
private final Set<String> applicationManagedSecurityResources;
private boolean hide = false;
public SharedConnectorInstanceContext(Set<String> unshareableResources, Set<String> applicationManagedSecurityResources, boolean share) {
this.unshareableResources = unshareableResources;
this.applicationManagedSecurityResources = applicationManagedSecurityResources;
if (!share) {
connectionManagerMap = new HashMap<ConnectionTrackingInterceptor, Set<ConnectionInfo>>();
}
}
public void share(ConnectorInstanceContext context) {
connectionManagerMap = context.getConnectionManagerMap();
}
public void hide() {
this.hide = true;
}
public Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> getConnectionManagerMap() {
if (hide) {
return Collections.emptyMap();
}
return connectionManagerMap;
}
public Set<String> getUnshareableResources() {
return unshareableResources;
}
public Set<String> getApplicationManagedSecurityResources() {
return applicationManagedSecurityResources;
}
}
| 6,451 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/GeronimoTransactionListener.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.geronimo.connector.outbound.connectiontracking;
import jakarta.resource.ResourceException;
import jakarta.transaction.Transaction;
import org.apache.geronimo.transaction.manager.TransactionManagerMonitor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @version $Rev$ $Date$
*/
public class GeronimoTransactionListener implements TransactionManagerMonitor {
private static final Logger log = Logger.getLogger(GeronimoTransactionListener.class.getName());
private final TrackedConnectionAssociator trackedConnectionAssociator;
public GeronimoTransactionListener(TrackedConnectionAssociator trackedConnectionAssociator) {
this.trackedConnectionAssociator = trackedConnectionAssociator;
}
public void threadAssociated(Transaction transaction) {
try {
trackedConnectionAssociator.newTransaction();
} catch (ResourceException e) {
log.log(Level.WARNING, "Error notifying connection tranker of transaction association", e);
}
}
public void threadUnassociated(Transaction transaction) {
}
}
| 6,452 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/TrackedConnectionAssociator.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.geronimo.connector.outbound.connectiontracking;
import jakarta.resource.ResourceException;
/**
*
*
* @version $Rev$ $Date$
*
*/
public interface TrackedConnectionAssociator {
/**
* If true, ConnectorInstanceContext instance does not have to be kept on a per component basis; otherwise the
* same instance must be passed to enter each time the specific component instance is entered.
* @return true if connections are proxied and only connect when invoked
*/
boolean isLazyConnect();
ConnectorInstanceContext enter(ConnectorInstanceContext newConnectorInstanceContext) throws ResourceException;
void newTransaction() throws ResourceException;
void exit(ConnectorInstanceContext connectorInstanceContext) throws ResourceException;
}
| 6,453 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectorInstanceContextImpl.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.geronimo.connector.outbound.connectiontracking;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Simple implementation of ComponentContext satisfying invariant.
*
* @version $Rev$ $Date$
*
* */
public class ConnectorInstanceContextImpl implements ConnectorInstanceContext {
private final Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = new HashMap<ConnectionTrackingInterceptor, Set<ConnectionInfo>>();
private final Set<String> unshareableResources;
private final Set<String> applicationManagedSecurityResources;
public ConnectorInstanceContextImpl(Set<String> unshareableResources, Set<String> applicationManagedSecurityResources) {
this.unshareableResources = unshareableResources;
this.applicationManagedSecurityResources = applicationManagedSecurityResources;
}
public Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> getConnectionManagerMap() {
return connectionManagerMap;
}
public Set<String> getUnshareableResources() {
return unshareableResources;
}
public Set<String> getApplicationManagedSecurityResources() {
return applicationManagedSecurityResources;
}
}
| 6,454 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/transactionlog/LogXAResource.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.geronimo.connector.outbound.transactionlog;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.LocalTransaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.manager.NamedXAResource;
/**
* Works with JDBCLog to provide last resource optimization for a single 1-pc database.
* The database work is committed when the log writes its prepare record, not here.
*
* @version $Rev$ $Date$
*
* */
public class LogXAResource implements NamedXAResource {
final String name;
final LocalTransaction localTransaction;
private Xid xid;
public LogXAResource(LocalTransaction localTransaction, String name) {
this.localTransaction = localTransaction;
this.name = name;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
}
public void end(Xid xid, int flags) throws XAException {
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return this == xaResource;
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int flag) throws XAException {
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
if (this.xid == null || !this.xid.equals(xid)) {
throw new XAException("Invalid Xid");
}
try {
localTransaction.rollback();
} catch (ResourceException e) {
throw (XAException)new XAException().initCause(e);
} finally {
this.xid = null;
}
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
public void start(Xid xid, int flag) throws XAException {
if (flag == XAResource.TMNOFLAGS) {
// first time in this transaction
if (this.xid != null) {
throw new XAException("already enlisted");
}
this.xid = xid;
try {
localTransaction.begin();
} catch (ResourceException e) {
throw (XAException) new XAException("could not start local tx").initCause(e);
}
} else if (flag == XAResource.TMRESUME) {
if (xid != this.xid) {
throw new XAException("attempting to resume in different transaction");
}
} else {
throw new XAException("unknown state");
}
}
public String getName() {
return name;
}
}
| 6,455 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/outbound/transactionlog/LogXAResourceInsertionInterceptor.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.geronimo.connector.outbound.transactionlog;
import jakarta.resource.ResourceException;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.ManagedConnectionInfo;
/**
* LocalXAResourceInsertionInterceptor.java
*
*
* @version $Rev$ $Date$
*/
public class LogXAResourceInsertionInterceptor
implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private final String name;
public LogXAResourceInsertionInterceptor(final ConnectionInterceptor next, String name) {
this.next = next;
this.name = name;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
next.getConnection(connectionInfo);
ManagedConnectionInfo mci = connectionInfo.getManagedConnectionInfo();
mci.setXAResource(
new LogXAResource(
mci.getManagedConnection().getLocalTransaction(), name));
}
public void returnConnection(
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("[name=").append(name).append("]\n");
if (next == null) {
s.append("<end>");
} else {
next.info(s);
}
}
}
| 6,456 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/context/GeronimoTransactionManagerTest.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.geronimo.transaction.context;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.util.concurrent.CountDownLatch;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.geronimo.transaction.manager.ImportedTransactionActiveException;
import org.apache.geronimo.transaction.manager.GeronimoTransactionManager;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.apache.geronimo.transaction.manager.XidFactoryImpl;
/**
*
*
* @version $Rev$ $Date$
*
*/
public class GeronimoTransactionManagerTest extends TestCase {
private GeronimoTransactionManager geronimoTransactionManager;
private XidFactory xidFactory = new XidFactoryImpl("geronimo.test.tm".getBytes());
protected void setUp() throws Exception {
super.setUp();
geronimoTransactionManager = new GeronimoTransactionManager();
}
protected void tearDown() throws Exception {
geronimoTransactionManager = null;
super.tearDown();
}
public void testImportedTxLifecycle() throws Exception {
Xid xid = xidFactory.createXid();
geronimoTransactionManager.begin(xid, 1000);
geronimoTransactionManager.end(xid);
geronimoTransactionManager.begin(xid, 1000);
geronimoTransactionManager.end(xid);
int readOnly = geronimoTransactionManager.prepare(xid);
assertEquals(XAResource.XA_RDONLY, readOnly);
// geronimoTransactionManager.commit(xid, false);
}
public void testNoConcurrentWorkSameXid() throws Exception {
final Xid xid = xidFactory.createXid();
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch cleanupSignal = new CountDownLatch(1);
final CountDownLatch endSignal = new CountDownLatch(1);
new Thread() {
public void run() {
try {
try {
try {
geronimoTransactionManager.begin(xid, 1000);
} finally {
startSignal.countDown();
}
cleanupSignal.await();
geronimoTransactionManager.end(xid);
geronimoTransactionManager.rollback(xid);
} finally {
endSignal.countDown();
}
} catch (Exception e) {
throw (AssertionFailedError) new AssertionFailedError().initCause(e);
}
}
}.start();
// wait for thread to begin the tx
startSignal.await();
try {
geronimoTransactionManager.begin(xid, 1000);
fail("should not be able begin same xid twice");
} catch (ImportedTransactionActiveException e) {
//expected
} finally {
// tell thread to start cleanup (e.g., end and rollback the tx)
cleanupSignal.countDown();
// wait for our thread to finish cleanup
endSignal.await();
}
}
public void testOnlyOneImportedTxAtATime() throws Exception {
Xid xid1 = xidFactory.createXid();
Xid xid2 = xidFactory.createXid();
geronimoTransactionManager.begin(xid1, 1000);
try {
geronimoTransactionManager.begin(xid2, 1000);
fail("should not be able to begin a 2nd tx without ending the first");
} catch (IllegalStateException e) {
//expected
} finally {
geronimoTransactionManager.end(xid1);
geronimoTransactionManager.rollback(xid1);
}
}
}
| 6,457 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/TransactionManagerTest.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.geronimo.transaction.manager;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
/**
*
*
* @version $Rev$ $Date$
*/
public class TransactionManagerTest extends TestCase {
TransactionManager tm;
MockResourceManager rm1, rm2, rm3;
public void testNoTransaction() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
}
public void testNoResource() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
tm.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tm.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
}
public void testTxOp() throws Exception {
Transaction tx;
tm.begin();
tx = tm.getTransaction();
tx.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertFalse(tx.equals(tm.getTransaction()));
tm.rollback();
}
public void testSuspend() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
tx = tm.suspend();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
tm.resume(tx);
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
assertEquals(tx, tm.getTransaction());
tm.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
}
public void testOneResource() throws Exception {
Transaction tx;
MockResource res1 = rm1.getResource("rm1");
tm.begin();
tx = tm.getTransaction();
assertNull(res1.getCurrentXid());
assertTrue(tx.enlistResource(res1));
assertNotNull(res1.getCurrentXid());
assertTrue(tx.delistResource(res1, XAResource.TMFAIL));
assertNull(res1.getCurrentXid());
tm.rollback();
tm.begin();
tx = tm.getTransaction();
assertTrue(tx.enlistResource(res1));
tm.rollback();
assertNull(res1.getCurrentXid());
}
protected void setUp() throws Exception {
tm = new TransactionManagerImpl();
rm1 = new MockResourceManager();
rm2 = new MockResourceManager();
rm3 = new MockResourceManager();
}
}
| 6,458 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/XATransactionTester.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.geronimo.transaction.manager;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
*
*
* @version $Rev$ $Date$
*/
public class XATransactionTester {
private TransactionManager manager;
private XADataSource ds;
private Xid xid;
public static void main(String[] args) throws Exception {
new XATransactionTester().run(args);
}
public void run(String[] args) throws Exception {
ds = getDataSource(args);
XAConnection xaConn = ds.getXAConnection("test", "test");
XAResource xaRes = xaConn.getXAResource();
manager = new TransactionManagerImpl(10, new DummyLog());
Connection c = xaConn.getConnection();
Statement s = c.createStatement();
manager.begin();
manager.getTransaction().enlistResource(xaRes);
s.execute("UPDATE XA_TEST SET X=X+1");
manager.getTransaction().delistResource(xaRes, XAResource.TMSUCCESS);
manager.commit();
/*
manager.begin();
manager.getTransaction().enlistResource(xaRes);
xid = new XidImpl(xid, 1);
System.out.println("xid = " + xid);
s.execute("UPDATE XA_TEST SET X=X+1");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes.prepare(xid);
c.close();
*/
/*
Xid[] prepared = xaRes.recover(XAResource.TMNOFLAGS);
for (int i = 0; i < prepared.length; i++) {
Xid xid = prepared[i];
StringBuffer s = new StringBuffer();
s.append(Integer.toHexString(xid.getFormatId())).append('.');
byte[] globalId = xid.getGlobalTransactionId();
for (int j = 0; j < globalId.length; j++) {
s.append(Integer.toHexString(globalId[j]));
}
System.out.println("recovery = " + s);
xaRes.forget(xid);
}
*/
}
/*
* @todo get something that loads this from a file
*/
private XADataSource getDataSource(String[] args) throws Exception {
// oracle.jdbc.xa.client.OracleXADataSource ds = new oracle.jdbc.xa.client.OracleXADataSource();
// ds.setConnectionURL("jdbc:oracle:thin:@localhost:1521:ABU");
// return ds;
return null;
}
private class DummyLog implements TransactionLog {
public void begin(Xid xid) throws LogException {
XATransactionTester.this.xid = xid;
}
public Object prepare(Xid xid, List<? extends TransactionBranchInfo> branches) throws LogException {
return new Object();
}
public void commit(Xid xid, Object logMark) throws LogException {
}
public void rollback(Xid xid, Object logMark) throws LogException {
}
public Collection<Recovery.XidBranchesPair> recover(XidFactory xidFactory) throws LogException {
return new ArrayList<Recovery.XidBranchesPair>();
}
public String getXMLStats() {
return null;
}
public int getAverageForceTime() {
return 0;
}
public int getAverageBytesPerForce() {
return 0;
}
}
}
| 6,459 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/RecoveryTest.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.geronimo.transaction.manager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;
/**
* This is just a unit test for recovery, depending on proper behavior of the log(s) it uses.
*
* @version $Rev$ $Date$
*
* */
public class RecoveryTest extends TestCase {
MockLog mockLog = new MockLog();
protected TransactionManagerImpl txManager;
private final String RM1 = "rm1";
private final String RM2 = "rm2";
private final String RM3 = "rm3";
private int count = 0;
@Override
protected void setUp() throws Exception {
txManager = createTransactionManager();
}
protected TransactionManagerImpl createTransactionManager() throws XAException, InterruptedException {
return new TransactionManagerImpl(1, new XidFactoryImpl("hi".getBytes()), mockLog);
}
protected void prepareForReplay() throws Exception {
Thread.sleep(100);
txManager = createTransactionManager();
}
public void testCommittedRMToBeRecovered() throws Exception {
Xid[] xids = getXidArray(1);
// specifies an empty Xid array such that this XAResource has nothing
// to recover. This means that the presumed abort protocol has failed
// right after the commit of the RM and before the force-write of the
// committed log record.
MockXAResource xares1 = new MockXAResource(RM1);
MockTransactionInfo[] txInfos = makeTxInfos(xids);
addBranch(txInfos, xares1);
prepareLog(mockLog, txInfos);
prepareForReplay();
Recovery recovery = txManager.recovery;
assertTrue(!recovery.hasRecoveryErrors());
assertTrue(recovery.getExternalXids().isEmpty());
assertTrue(!recovery.localRecoveryComplete());
recovery.recoverResourceManager(xares1);
assertEquals(1, xares1.committed.size());
assertTrue(recovery.localRecoveryComplete());
}
public void test2ResOnlineAfterRecoveryStart() throws Exception {
Xid[] xids = getXidArray(3);
MockXAResource xares1 = new MockXAResource(RM1);
MockXAResource xares2 = new MockXAResource(RM2);
MockTransactionInfo[] txInfos = makeTxInfos(xids);
addBranch(txInfos, xares1);
addBranch(txInfos, xares2);
prepareLog(mockLog, txInfos);
prepareForReplay();
Recovery recovery = txManager.recovery;
assertTrue(!recovery.hasRecoveryErrors());
assertTrue(recovery.getExternalXids().isEmpty());
assertTrue(!recovery.localRecoveryComplete());
recovery.recoverResourceManager(xares1);
assertTrue(!recovery.localRecoveryComplete());
assertEquals(3, xares1.committed.size());
recovery.recoverResourceManager(xares2);
assertEquals(3, xares2.committed.size());
assertTrue(txManager.recovery.localRecoveryComplete());
}
public void testInvalidXid() throws Exception {
final Xid[] xids = new Xid[] { new Xid() {
@Override
public int getFormatId() {
return 0;
}
@Override
public byte[] getGlobalTransactionId() {
return null;
}
@Override
public byte[] getBranchQualifier() {
return new byte[0];
}
} };
final NamedXAResource xares = new NamedXAResource() {
@Override
public String getName() {
return RM1;
}
@Override
public void commit(Xid xid, boolean b) throws XAException {
}
@Override
public void end(Xid xid, int i) throws XAException {
}
@Override
public void forget(Xid xid) throws XAException {
}
@Override
public int getTransactionTimeout() throws XAException {
return 0;
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
return false;
}
@Override
public int prepare(Xid xid) throws XAException {
return 0;
}
@Override
public Xid[] recover(int i) throws XAException {
return xids;
}
@Override
public void rollback(Xid xid) throws XAException {
}
@Override
public boolean setTransactionTimeout(int i) throws XAException {
return false;
}
@Override
public void start(Xid xid, int i) throws XAException {
}
};
prepareForReplay();
Recovery recovery = txManager.recovery;
recovery.recoverResourceManager(xares);
}
private void addBranch(MockTransactionInfo[] txInfos, MockXAResource xaRes) throws XAException {
for (int i = 0; i < txInfos.length; i++) {
MockTransactionInfo txInfo = txInfos[i];
Xid xid = txManager.getXidFactory().createBranch(txInfo.globalXid, count++);
xaRes.start(xid, 0);
txInfo.branches.add(new TransactionBranchInfoImpl(xid, xaRes.getName()));
}
}
private MockTransactionInfo[] makeTxInfos(Xid[] xids) {
MockTransactionInfo[] txInfos = new MockTransactionInfo[xids.length];
for (int i = 0; i < xids.length; i++) {
Xid xid = xids[i];
txInfos[i] = new MockTransactionInfo(xid, new ArrayList<TransactionBranchInfo>());
}
return txInfos;
}
public void test3ResOnlineAfterRecoveryStart() throws Exception {
Xid[] xids12 = getXidArray(3);
List xids12List = Arrays.asList(xids12);
Xid[] xids13 = getXidArray(3);
List xids13List = Arrays.asList(xids13);
Xid[] xids23 = getXidArray(3);
List xids23List = Arrays.asList(xids23);
ArrayList tmp = new ArrayList();
tmp.addAll(xids12List);
tmp.addAll(xids13List);
Xid[] xids1 = (Xid[]) tmp.toArray(new Xid[6]);
tmp.clear();
tmp.addAll(xids12List);
tmp.addAll(xids23List);
Xid[] xids2 = (Xid[]) tmp.toArray(new Xid[6]);
tmp.clear();
tmp.addAll(xids13List);
tmp.addAll(xids23List);
Xid[] xids3 = (Xid[]) tmp.toArray(new Xid[6]);
MockXAResource xares1 = new MockXAResource(RM1);
MockXAResource xares2 = new MockXAResource(RM2);
MockXAResource xares3 = new MockXAResource(RM3);
MockTransactionInfo[] txInfos12 = makeTxInfos(xids12);
addBranch(txInfos12, xares1);
addBranch(txInfos12, xares2);
prepareLog(mockLog, txInfos12);
MockTransactionInfo[] txInfos13 = makeTxInfos(xids13);
addBranch(txInfos13, xares1);
addBranch(txInfos13, xares3);
prepareLog(mockLog, txInfos13);
MockTransactionInfo[] txInfos23 = makeTxInfos(xids23);
addBranch(txInfos23, xares2);
addBranch(txInfos23, xares3);
prepareLog(mockLog, txInfos23);
prepareForReplay();
Recovery recovery = txManager.recovery;
assertTrue(!recovery.hasRecoveryErrors());
assertTrue(recovery.getExternalXids().isEmpty());
assertEquals(9, recovery.localUnrecoveredCount());
recovery.recoverResourceManager(xares1);
assertEquals(9, recovery.localUnrecoveredCount());
assertEquals(6, xares1.committed.size());
recovery.recoverResourceManager(xares2);
assertEquals(6, recovery.localUnrecoveredCount());
assertEquals(6, xares2.committed.size());
recovery.recoverResourceManager(xares3);
assertEquals(0, recovery.localUnrecoveredCount());
assertEquals(6, xares3.committed.size());
}
private void prepareLog(TransactionLog txLog, MockTransactionInfo[] txInfos) throws LogException {
for (int i = 0; i < txInfos.length; i++) {
MockTransactionInfo txInfo = txInfos[i];
txLog.prepare(txInfo.globalXid, txInfo.branches);
}
}
private Xid[] getXidArray(int i) {
Xid[] xids = new Xid[i];
for (int j = 0; j < xids.length; j++) {
xids[j] = txManager.getXidFactory().createXid();
}
return xids;
}
private static class MockXAResource implements NamedXAResource {
private final String name;
private final List<Xid> xids = new ArrayList<Xid>();
private final List<Xid> committed = new ArrayList<Xid>();
private final List<Xid> rolledBack = new ArrayList<Xid>();
public MockXAResource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
committed.add(xid);
}
public void end(Xid xid, int flags) throws XAException {
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return false;
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int flag) throws XAException {
return xids.toArray(new Xid[xids.size()]);
}
public void rollback(Xid xid) throws XAException {
rolledBack.add(xid);
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
public void start(Xid xid, int flags) throws XAException {
xids.add(xid);
}
public List getCommitted() {
return committed;
}
public List getRolledBack() {
return rolledBack;
}
}
private static class MockTransactionInfo {
private Xid globalXid;
private List<TransactionBranchInfo> branches;
public MockTransactionInfo(Xid globalXid, List<TransactionBranchInfo> branches) {
this.globalXid = globalXid;
this.branches = branches;
}
}
}
| 6,460 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/MockLogRecoveryTest.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.geronimo.transaction.manager;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockLogRecoveryTest extends AbstractRecoveryTest {
private TransactionLog log;
@Override
public void setUp() throws Exception {
log = new MockLog();
super.setUp();
}
@Override
protected TransactionManagerImpl createTransactionManager() throws Exception {
return new TransactionManagerImpl(1, new XidFactoryImpl("hi".getBytes()), log);
}
protected void prepareForReplay() throws Exception {
Thread.sleep(100);
txManager = createTransactionManager();
}
}
| 6,461 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/HeuristicTest.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.geronimo.transaction.manager;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import javax.transaction.xa.XAException;
import junit.framework.TestCase;
/**
* Test all combinations of heuristic error codes except XA_HEURHAZ
* @version $Rev$ $Date$
*/
public class HeuristicTest extends TestCase {
TransactionLog transactionLog = new MockLog();
TransactionManagerImpl tm;
protected void setUp() throws Exception {
tm = new TransactionManagerImpl(10,
new XidFactoryImpl("WHAT DO WE CALL IT?".getBytes()), transactionLog);
}
protected void tearDown() throws Exception {
tm = null;
}
public void test_C_C() throws Exception {
expectSuccess(0,0);
}
public void test_C_HC() throws Exception {
expectSuccess(0,XAException.XA_HEURCOM);
}
public void test_C_HM() throws Exception {
expectHeuristicMixedException(0, XAException.XA_HEURMIX);
}
public void test_C_HR() throws Exception {
expectHeuristicMixedException(0, XAException.XA_HEURRB);
}
public void test_HC_C() throws Exception {
expectSuccess(XAException.XA_HEURCOM,0);
}
public void test_HC_HC() throws Exception {
expectSuccess(XAException.XA_HEURCOM, XAException.XA_HEURCOM);
}
public void test_HC_HM() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURCOM, XAException.XA_HEURMIX);
}
public void test_HC_HR() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURCOM, XAException.XA_HEURRB);
}
public void test_HM_C() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURMIX, 0);
}
public void test_HM_HC() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURMIX, XAException.XA_HEURCOM);
}
public void test_HM_HM() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURMIX, XAException.XA_HEURMIX);
}
public void test_HM_HR() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURMIX, XAException.XA_HEURRB);
}
public void test_HR_C() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURRB, 0);
}
public void test_HR_HC() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURRB, XAException.XA_HEURCOM);
}
public void test_HR_HM() throws Exception {
expectHeuristicMixedException(XAException.XA_HEURRB, XAException.XA_HEURMIX);
}
public void test_HR_HR() throws Exception {
expectHeuristicRollbackException(XAException.XA_HEURRB, XAException.XA_HEURRB);
}
public void expectSuccess(int first, int second) throws Exception {
tm.begin();
tm.getTransaction().enlistResource(new MockResource("1", first));
tm.getTransaction().enlistResource(new MockResource("2", second));
tm.commit();
}
public void expectHeuristicMixedException(int first, int second) throws Exception {
tm.begin();
tm.getTransaction().enlistResource(new MockResource("1", first));
tm.getTransaction().enlistResource(new MockResource("2", second));
try {
tm.commit();
fail();
} catch (HeuristicMixedException e) {
//expected
}
}
public void expectHeuristicRollbackException(int first, int second) throws Exception {
tm.begin();
tm.getTransaction().enlistResource(new MockResource("1", first));
tm.getTransaction().enlistResource(new MockResource("2", second));
try {
tm.commit();
fail();
} catch (HeuristicRollbackException e) {
//expected
}
}
}
| 6,462 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/AbstractRecoveryTest.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.geronimo.transaction.manager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;
/**
* This is just a unit test for recovery, depending on proper behavior of the log(s) it uses.
*
* @version $Rev$ $Date$
*
* */
public abstract class AbstractRecoveryTest extends TestCase {
protected TransactionManagerImpl txManager;
private static final String RM1 = "rm1";
private static final String RM2 = "rm2";
private static final String RM3 = "rm3";
private static final int XID_COUNT = 3;
private int branchCounter;
@Override
protected void setUp() throws Exception {
txManager = createTransactionManager();
}
protected TransactionManagerImpl createTransactionManager() throws Exception {
return new TransactionManagerImpl(1, new XidFactoryImpl("hi".getBytes()), null);
}
public void test2ResOnlineAfterRecoveryStart() throws Exception {
Xid[] xids = getXidArray(XID_COUNT);
MockXAResource xares1 = new MockXAResource(RM1);
MockXAResource xares2 = new MockXAResource(RM2);
MockTransactionInfo[] txInfos = makeTxInfos(xids);
addBranch(txInfos, xares1);
addBranch(txInfos, xares2);
prepareLog(txManager.getTransactionLog(), txInfos);
prepareForReplay();
Recovery recovery = txManager.recovery;
assertTrue(!recovery.hasRecoveryErrors());
assertTrue(recovery.getExternalXids().isEmpty());
assertTrue(!recovery.localRecoveryComplete());
recovery.recoverResourceManager(xares1);
assertTrue(!recovery.localRecoveryComplete());
assertEquals(XID_COUNT, xares1.committed.size());
recovery.recoverResourceManager(xares2);
assertEquals(XID_COUNT, xares2.committed.size());
assertTrue(recovery.localRecoveryComplete());
}
public void test3ResOnlineAfterRecoveryStart() throws Exception {
Xid[] xids12 = getXidArray(XID_COUNT);
List xids12List = Arrays.asList(xids12);
Xid[] xids13 = getXidArray(XID_COUNT);
List xids13List = Arrays.asList(xids13);
Xid[] xids23 = getXidArray(XID_COUNT);
List xids23List = Arrays.asList(xids23);
ArrayList tmp = new ArrayList();
tmp.addAll(xids12List);
tmp.addAll(xids13List);
Xid[] xids1 = (Xid[]) tmp.toArray(new Xid[6]);
tmp.clear();
tmp.addAll(xids12List);
tmp.addAll(xids23List);
Xid[] xids2 = (Xid[]) tmp.toArray(new Xid[6]);
tmp.clear();
tmp.addAll(xids13List);
tmp.addAll(xids23List);
Xid[] xids3 = (Xid[]) tmp.toArray(new Xid[6]);
MockXAResource xares1 = new MockXAResource(RM1);
MockXAResource xares2 = new MockXAResource(RM2);
MockXAResource xares3 = new MockXAResource(RM3);
MockTransactionInfo[] txInfos12 = makeTxInfos(xids12);
addBranch(txInfos12, xares1);
addBranch(txInfos12, xares2);
prepareLog(txManager.getTransactionLog(), txInfos12);
MockTransactionInfo[] txInfos13 = makeTxInfos(xids13);
addBranch(txInfos13, xares1);
addBranch(txInfos13, xares3);
prepareLog(txManager.getTransactionLog(), txInfos13);
MockTransactionInfo[] txInfos23 = makeTxInfos(xids23);
addBranch(txInfos23, xares2);
addBranch(txInfos23, xares3);
prepareLog(txManager.getTransactionLog(), txInfos23);
prepareForReplay();
Recovery recovery = txManager.recovery;
assertTrue(!recovery.hasRecoveryErrors());
assertTrue(recovery.getExternalXids().isEmpty());
assertEquals(XID_COUNT * 3, recovery.localUnrecoveredCount());
recovery.recoverResourceManager(xares1);
assertEquals(XID_COUNT * 3, recovery.localUnrecoveredCount());
assertEquals(XID_COUNT * 2, xares1.committed.size());
recovery.recoverResourceManager(xares2);
assertEquals(XID_COUNT * 2, recovery.localUnrecoveredCount());
assertEquals(XID_COUNT * 2, xares2.committed.size());
recovery.recoverResourceManager(xares3);
assertEquals(0, recovery.localUnrecoveredCount());
assertEquals(XID_COUNT * 2, xares3.committed.size());
}
protected abstract void prepareForReplay() throws Exception;
private void prepareLog(TransactionLog txLog, MockTransactionInfo[] txInfos) throws LogException {
for (int i = 0; i < txInfos.length; i++) {
MockTransactionInfo txInfo = txInfos[i];
txLog.prepare(txInfo.globalXid, txInfo.branches);
}
}
private Xid[] getXidArray(int i) {
Xid[] xids = new Xid[i];
for (int j = 0; j < xids.length; j++) {
xids[j] = txManager.getXidFactory().createXid();
}
return xids;
}
private void addBranch(MockTransactionInfo[] txInfos, MockXAResource xaRes) throws XAException {
for (int i = 0; i < txInfos.length; i++) {
MockTransactionInfo txInfo = txInfos[i];
Xid globalXid = txInfo.globalXid;
Xid branchXid = txManager.getXidFactory().createBranch(globalXid, branchCounter++);
xaRes.start(branchXid, 0);
txInfo.branches.add(new TransactionBranchInfoImpl(branchXid, xaRes.getName()));
}
}
private MockTransactionInfo[] makeTxInfos(Xid[] xids) {
MockTransactionInfo[] txInfos = new MockTransactionInfo[xids.length];
for (int i = 0; i < xids.length; i++) {
Xid xid = xids[i];
txInfos[i] = new MockTransactionInfo(xid, new ArrayList());
}
return txInfos;
}
private static class MockXAResource implements NamedXAResource {
private final String name;
private final List<Xid> xids = new ArrayList<Xid>();
private final List<Xid> committed = new ArrayList<Xid>();
private final List<Xid> rolledBack = new ArrayList<Xid>();
public MockXAResource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
committed.add(xid);
}
public void end(Xid xid, int flags) throws XAException {
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return false;
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int flag) throws XAException {
return xids.toArray(new Xid[xids.size()]);
}
public void rollback(Xid xid) throws XAException {
rolledBack.add(xid);
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
public void start(Xid xid, int flags) throws XAException {
xids.add(xid);
}
public List getCommitted() {
return committed;
}
public List getRolledBack() {
return rolledBack;
}
}
private static class MockTransactionInfo {
private Xid globalXid;
private List branches;
public MockTransactionInfo(Xid globalXid, List branches) {
this.globalXid = globalXid;
this.branches = branches;
}
}
}
| 6,463 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/ProtocolTest.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.geronimo.transaction.manager;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
/**
*/
public class ProtocolTest extends TestCase {
private TransactionManagerImpl tm;
private MockResourceManager mrm1, mrm2;
private MockResource mr11, mr12, mr21, mr22;
protected void setUp() throws Exception {
tm = new TransactionManagerImpl();
mrm1 = new MockResourceManager();
mrm2 = new MockResourceManager();
mr11 = new MockResource(mrm1, "mr11");
mr12 = new MockResource(mrm1, "mr12");
mr21 = new MockResource(mrm2, "mr21");
mr22 = new MockResource(mrm2, "mr22");
}
public void testOnePhaseCommit() throws Exception {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(mr11);
tx.delistResource(mr11, XAResource.TMSUSPEND);
tm.commit();
}
public void testOnePhaseCommiTwoResources() throws Exception {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(mr11);
tx.delistResource(mr11, XAResource.TMSUSPEND);
tx.enlistResource(mr12);
tx.delistResource(mr12, XAResource.TMSUSPEND);
tm.commit();
}
public void testTwoPhaseCommit() throws Exception {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(mr11);
tx.delistResource(mr11, XAResource.TMSUSPEND);
tx.enlistResource(mr21);
tx.delistResource(mr21, XAResource.TMSUSPEND);
tm.commit();
}
public void testTwoPhaseCommit4Resources() throws Exception {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(mr11);
tx.delistResource(mr11, XAResource.TMSUSPEND);
tx.enlistResource(mr12);
tx.delistResource(mr12, XAResource.TMSUSPEND);
tx.enlistResource(mr21);
tx.delistResource(mr21, XAResource.TMSUSPEND);
tx.enlistResource(mr22);
tx.delistResource(mr22, XAResource.TMSUSPEND);
tm.commit();
}
}
| 6,464 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/XidImporterTest.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.geronimo.transaction.manager;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.XAException;
import jakarta.transaction.Transaction;
import jakarta.transaction.Status;
import junit.framework.TestCase;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class XidImporterTest extends TestCase{
MockResourceManager rm1 = new MockResourceManager();
MockResource r1_1 = new MockResource(rm1, "rm1");
MockResource r1_2 = new MockResource(rm1, "rm1");
MockResourceManager rm2 = new MockResourceManager();
MockResource r2_1 = new MockResource(rm2, "rm2");
MockResource r2_2 = new MockResource(rm2, "rm2");
XidImporter tm;
XidFactory xidFactory = new XidFactoryImpl();
protected void setUp() throws Exception {
tm = new TransactionManagerImpl();
}
public void testImportXid() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
}
public void testNoResourcesCommitOnePhase() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tm.commit(tx, true);
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
}
public void testNoResourcesCommitTwoPhase() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
assertEquals(XAResource.XA_RDONLY, tm.prepare(tx));
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
}
public void testNoResourcesMarkRollback() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tx.setRollbackOnly();
try {
tm.prepare(tx);
fail("should throw rollback exception in an XAException");
} catch (XAException e) {
}
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
}
public void testNoResourcesRollback() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tm.rollback(tx);
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
}
public void testOneResourceOnePhaseCommit() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tm.commit(tx, true);
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
}
public void testOneResourceTwoPhaseCommit() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
assertEquals(XAResource.XA_OK, tm.prepare(tx));
assertTrue(!r1_1.isCommitted());
assertTrue(r1_1.isPrepared());
assertTrue(!r1_1.isRolledback());
tm.commit(tx, false);
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
assertTrue(r1_1.isCommitted());
assertTrue(r1_1.isPrepared());
assertTrue(!r1_1.isRolledback());
}
public void testFourResourceTwoPhaseCommit() throws Exception {
Xid externalXid = xidFactory.createXid();
Transaction tx = tm.importXid(externalXid, 0);
tx.enlistResource(r1_1);
tx.enlistResource(r1_2);
tx.enlistResource(r2_1);
tx.enlistResource(r2_2);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.delistResource(r2_1, XAResource.TMSUCCESS);
tx.delistResource(r2_2, XAResource.TMSUCCESS);
assertEquals(XAResource.XA_OK, tm.prepare(tx));
assertTrue(!r1_1.isCommitted() & !r1_2.isCommitted());
assertTrue(r1_1.isPrepared() ^ r1_2.isPrepared());
assertTrue(!r1_1.isRolledback() & !r1_2.isRolledback());
assertTrue(!r2_1.isCommitted() & !r2_2.isCommitted());
assertTrue(r2_1.isPrepared() ^ r2_2.isPrepared());
assertTrue(!r2_1.isRolledback() & !r2_2.isRolledback());
tm.commit(tx, false);
assertEquals(Status.STATUS_NO_TRANSACTION, tx.getStatus());
assertTrue((r1_1.isCommitted() & r1_1.isPrepared()) ^ (r1_2.isCommitted() & r1_2.isPrepared()));
assertTrue(!r1_1.isRolledback() & !r1_2.isRolledback());
assertTrue((r2_1.isCommitted() & r2_1.isPrepared()) ^ (r2_2.isCommitted() & r2_2.isPrepared()));
assertTrue(!r2_1.isRolledback() & !r2_2.isRolledback());
}
}
| 6,465 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/HOWLLogRecoveryTest.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.geronimo.transaction.manager;
import java.io.File;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.geronimo.transaction.log.HOWLLog;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class HOWLLogRecoveryTest extends AbstractRecoveryTest {
private static final File basedir = new File(System.getProperty("basedir", System.getProperty("user.dir")));
private static final String LOG_FILE_NAME = "howl_test_";
private static final String logFileDir = "txlog";
private static final String targetDir = new File(basedir, "target").getAbsolutePath();
private static final File txlogDir = new File(basedir, "target/" + logFileDir);
@Override
public void setUp() throws Exception {
// Deletes the previous transaction log files.
File[] files = txlogDir.listFiles();
if ( null != files ) {
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
super.setUp();
}
public void test2Again() throws Exception {
test2ResOnlineAfterRecoveryStart();
}
public void test3Again() throws Exception {
test3ResOnlineAfterRecoveryStart();
}
@Override
protected TransactionManagerImpl createTransactionManager() throws Exception {
XidFactory xidFactory = new XidFactoryImpl("hi".getBytes());
HOWLLog howlLog = new HOWLLog(
"org.objectweb.howl.log.BlockLogBuffer", // "bufferClassName",
4, // "bufferSizeKBytes",
true, // "checksumEnabled",
true, // "adler32Checksum",
20, // "flushSleepTime",
logFileDir, // "logFileDir",
"log", // "logFileExt",
LOG_FILE_NAME, // "logFileName",
200, // "maxBlocksPerFile",
10, // "maxBuffers", log
2, // "maxLogFiles",
2, // "minBuffers",
10,// "threadsWaitingForceThreshold"});
xidFactory,
new File(targetDir)
);
howlLog.doStart();
return new TransactionManagerImpl(1, xidFactory, howlLog);
}
protected void tearDown() throws Exception {
((HOWLLog) txManager.getTransactionLog()).doStop();
}
protected void prepareForReplay() throws Exception {
Thread.sleep(100);
tearDown();
txManager = createTransactionManager();
}
public static Test suite() {
return new TestSetup(new TestSuite(HOWLLogRecoveryTest.class)) {
protected void setUp() throws Exception {
File logFile = new File(txlogDir, LOG_FILE_NAME + "_1.log");
if (logFile.exists()) {
logFile.delete();
}
logFile = new File(txlogDir, LOG_FILE_NAME + "_2.log");
if (logFile.exists()) {
logFile.delete();
}
}
};
}
}
| 6,466 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/MockResource.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.geronimo.transaction.manager;
import java.util.Set;
import java.util.HashSet;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* @version $Rev$ $Date$
*/
public class MockResource implements NamedXAResource, NamedXAResourceFactory {
private String xaResourceName = "mockResource";
private Xid currentXid;
private MockResourceManager manager;
private int timeout = 0;
private boolean prepared;
private boolean committed;
private boolean rolledback;
private Set<Xid> preparedXids = new HashSet<Xid>();
private Set<Xid> knownXids = new HashSet<Xid>();
private Set<Xid> finishedXids = new HashSet<Xid>();//end was called with TMSUCCESS or TMFAIL
private int errorStatus;
public MockResource(MockResourceManager manager, String xaResourceName) {
this.manager = manager;
this.xaResourceName = xaResourceName;
}
public MockResource(String xaResourceName, int errorStatus) {
this.manager = new MockResourceManager();
this.xaResourceName = xaResourceName;
this.errorStatus = errorStatus;
}
public int getTransactionTimeout() throws XAException {
return timeout;
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
public Xid getCurrentXid() {
return currentXid;
}
public void start(Xid xid, int flags) throws XAException {
if (this.currentXid != null) {
throw new XAException(XAException.XAER_PROTO);
}
if (flags == XAResource.TMRESUME && !knownXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
if (finishedXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
if ((flags & XAResource.TMJOIN) != 0) {
manager.join(xid, this);
} else {
manager.newTx(xid, this);
}
this.currentXid = xid;
if (!knownXids.contains(xid)) {
knownXids.add(xid);
}
}
public void end(Xid xid, int flags) throws XAException {
if (!knownXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
if (flags == XAResource.TMSUSPEND) {
if (currentXid == null) {
throw new XAException(XAException.XAER_PROTO);
} else if (this.currentXid != xid) {
throw new XAException(XAException.XAER_PROTO);
}
} else if (flags == XAResource.TMFAIL || flags == XAResource.TMSUCCESS) {
if (finishedXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
finishedXids.add(xid);
}
this.currentXid = null;
}
public int prepare(Xid xid) throws XAException {
if (!finishedXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
prepared = true;
preparedXids.add(xid);
return XAResource.XA_OK;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
if (!finishedXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
if (errorStatus != 0) {
throw new XAException(errorStatus);
}
preparedXids.remove(xid);
committed = true;
}
public void rollback(Xid xid) throws XAException {
if (!finishedXids.contains(xid)) {
throw new XAException(XAException.XAER_PROTO);
}
rolledback = true;
preparedXids.remove(xid);
manager.forget(xid, this);
}
public boolean isSameRM(XAResource xaResource) throws XAException {
if (xaResource instanceof MockResource) {
return manager == ((MockResource) xaResource).manager;
}
return false;
}
public void forget(Xid xid) throws XAException {
// throw new UnsupportedOperationException();
}
public Xid[] recover(int flag) throws XAException {
return preparedXids.toArray(new Xid[preparedXids.size()]);
}
public boolean isPrepared() {
return prepared;
}
public boolean isCommitted() {
return committed;
}
public boolean isRolledback() {
return rolledback;
}
public String getName() {
return xaResourceName;
}
public NamedXAResource getNamedXAResource() throws SystemException {
return this;
}
public void returnNamedXAResource(NamedXAResource namedXAResource) {
if (this != namedXAResource) throw new RuntimeException("Wrong NamedXAResource returned: expected: " + this + " actual: " + namedXAResource);
}
}
| 6,467 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/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.geronimo.transaction.manager;
import java.util.concurrent.TimeUnit;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;
public class XidFactoryImplTest extends TestCase {
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);
}
public void testFactory() 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()));
}
}
| 6,468 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/MockResourceManager.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.geronimo.transaction.manager;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*/
public class MockResourceManager {
private Map<Xid, Set<XAResource>> xids = new HashMap<Xid, Set<XAResource>>();
public MockResourceManager() {
}
public MockResource getResource(String xaResourceName) {
return new MockResource(this, xaResourceName);
}
public void join(Xid xid, XAResource xaRes) throws XAException {
Set<XAResource> resSet = xids.get(xid);
if (resSet == null) {
throw new XAException(XAException.XAER_NOTA);
}
resSet.add(xaRes);
}
public void newTx(Xid xid, XAResource xaRes) throws XAException {
if (xids.containsKey(xid)) {
throw new XAException(XAException.XAER_DUPID);
}
Set<XAResource> resSet = new HashSet<XAResource>();
resSet.add(xaRes);
xids.put(xid, resSet);
}
public void forget(Xid xid, XAResource xaRes) throws XAException {
if (xids.remove(xid) == null) {
throw new XAException(XAException.XAER_NOTA);
}
}
}
| 6,469 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/TransactionManagerImplTest.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.geronimo.transaction.manager;
import java.util.Map;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class TransactionManagerImplTest extends TestCase {
MockResourceManager rm1 = new MockResourceManager();
MockResource r1_1 = rm1.getResource("rm1_1");
MockResource r1_2 = rm1.getResource("rm1_2");
MockResourceManager rm2 = new MockResourceManager();
MockResource r2_1 = rm2.getResource("rm2_1");
MockResource r2_2 = rm2.getResource("rm2_2");
TransactionLog transactionLog = new MockLog();
TransactionManagerImpl tm;
long timeDelta;
protected void setUp() throws Exception {
tm = createTransactionManager();
timeDelta = 0;
}
private TransactionManagerImpl createTransactionManager() throws XAException {
return new TransactionManagerImpl(10,
new XidFactoryImpl("WHAT DO WE CALL IT?".getBytes()), transactionLog, new TestTimeProvider());
}
protected void tearDown() throws Exception {
tm = null;
}
public class TestTimeProvider implements CurrentTimeMsProvider {
@Override
public long now() {
return System.currentTimeMillis() + timeDelta;
}
}
public void testNoResourcesCommit() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tm.commit();
assertNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
Transaction tx = tm.getTransaction();
assertNotNull(tx);
tx.commit();
assertNotNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
}
public void testNoResourcesMarkRollbackOnly() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tm.getTransaction().setRollbackOnly();
assertEquals(Status.STATUS_MARKED_ROLLBACK, tm.getStatus());
try {
tm.commit();
fail("tx should not commit");
} catch (RollbackException e) {
//expected
}
assertNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
Transaction tx = tm.getTransaction();
assertNotNull(tx);
tx.setRollbackOnly();
assertEquals(Status.STATUS_MARKED_ROLLBACK, tx.getStatus());
try {
tx.commit();
fail("tx should not commit");
} catch (RollbackException e) {
//expected
}
assertNotNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
}
public void testNoResourcesRollback() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tm.rollback();
assertNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
Transaction tx = tm.getTransaction();
assertNotNull(tx);
tx.rollback();
assertNotNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
//check rollback when marked rollback only
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tm.getTransaction().setRollbackOnly();
assertEquals(Status.STATUS_MARKED_ROLLBACK, tm.getStatus());
tm.rollback();
assertNull(tm.getTransaction());
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
}
public void testOneResourceCommit() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(r1_1.isCommitted());
assertTrue(!r1_1.isPrepared());
assertTrue(!r1_1.isRolledback());
}
public void testOneResourceMarkedRollback() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.setRollbackOnly();
tx.delistResource(r1_1, XAResource.TMSUCCESS);
try {
tx.commit();
fail("tx should roll back");
} catch (RollbackException e) {
//expected
}
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(!r1_1.isCommitted());
assertTrue(!r1_1.isPrepared());
assertTrue(r1_1.isRolledback());
}
public void testOneResourceRollback() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(!r1_1.isCommitted());
assertTrue(!r1_1.isPrepared());
assertTrue(r1_1.isRolledback());
}
public void testTwoResourceOneRMCommit() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.enlistResource(r1_2);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(r1_1.isCommitted() ^ r1_2.isCommitted());
assertTrue(!r1_1.isPrepared() & !r1_2.isPrepared());
assertTrue(!r1_1.isRolledback() & !r1_2.isRolledback());
}
public void testTwoResourceOneRMMarkRollback() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.enlistResource(r1_2);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.setRollbackOnly();
try {
tx.commit();
fail("tx should roll back");
} catch (RollbackException e) {
//expected
}
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(!r1_1.isCommitted() & !r1_2.isCommitted());
assertTrue(!r1_1.isPrepared() & !r1_2.isPrepared());
assertTrue(r1_1.isRolledback() ^ r1_2.isRolledback());
}
public void testTwoResourcesOneRMRollback() throws Exception {
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.enlistResource(r1_2);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.setRollbackOnly();
tx.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue(!r1_1.isCommitted() & !r1_2.isCommitted());
assertTrue(!r1_1.isPrepared() & !r1_2.isPrepared());
assertTrue(r1_1.isRolledback() ^ r1_2.isRolledback());
}
public void testFourResourceTwoRMCommit() throws Exception {
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
Transaction tx = tm.getTransaction();
tx.enlistResource(r1_1);
tx.enlistResource(r1_2);
tx.enlistResource(r2_1);
tx.enlistResource(r2_2);
tx.delistResource(r1_1, XAResource.TMSUCCESS);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.delistResource(r2_1, XAResource.TMSUCCESS);
tx.delistResource(r2_2, XAResource.TMSUCCESS);
tx.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertTrue((r1_1.isCommitted() & r1_1.isPrepared()) ^ (r1_2.isCommitted() & r1_2.isPrepared()));
assertTrue(!r1_1.isRolledback() & !r1_2.isRolledback());
assertTrue((r2_1.isCommitted() & r2_1.isPrepared()) ^ (r2_2.isCommitted() & r2_2.isPrepared()));
assertTrue(!r2_1.isRolledback() & !r2_2.isRolledback());
}
//BE VERY CAREFUL!! the ResourceManager only "recovers" the LAST resource it creates.
//This test depends on using the resource that will be recovered by the resource manager.
public void testSimpleRecovery() throws Exception {
//create a transaction in our own transaction manager
Xid xid = tm.getXidFactory().createXid();
Transaction tx = tm.importXid(xid, 0);
tm.resume(tx);
assertSame(tx, tm.getTransaction());
tx.enlistResource(r1_2);
tx.enlistResource(r2_2);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.delistResource(r2_2, XAResource.TMSUCCESS);
tm.suspend();
tm.prepare(tx);
//recover
Thread.sleep(100); // Wait a bit for new XidFactoryImpl
tm = createTransactionManager();
recover(r1_1);
recover(r1_2);
assertTrue(r1_2.isCommitted());
assertTrue(!r2_2.isCommitted());
recover(r2_1);
recover(r2_2);
assertTrue(r2_2.isCommitted());
assertTrue(tm.recovery.localRecoveryComplete());
}
private void recover(MockResource mr) {
tm.registerNamedXAResourceFactory(mr);
tm.unregisterNamedXAResourceFactory(mr.getName());
}
public void testImportedXidRecovery() throws Exception {
//create a transaction from an external transaction manager.
XidFactory xidFactory2 = new XidFactoryImpl("tm2".getBytes());
Xid xid = xidFactory2.createXid();
Transaction tx = tm.importXid(xid, 0);
tm.resume(tx);
assertSame(tx, tm.getTransaction());
tx.enlistResource(r1_2);
tx.enlistResource(r2_2);
tx.delistResource(r1_2, XAResource.TMSUCCESS);
tx.delistResource(r2_2, XAResource.TMSUCCESS);
tm.suspend();
tm.prepare(tx);
//recover
Thread.sleep(100); // Wait a bit for new XidFactoryImpl
tm = createTransactionManager();
recover(r1_1);
recover(r1_2);
assertTrue(!r1_2.isCommitted());
assertTrue(!r2_2.isCommitted());
recover(r2_1);
recover(r2_2);
assertTrue(!r2_2.isCommitted());
//there are no transactions started here, so local recovery is complete
assertTrue(tm.recovery.localRecoveryComplete());
Map recovered = tm.getExternalXids();
assertEquals(1, recovered.size());
assertEquals(xid, recovered.keySet().iterator().next());
}
public void testTimeout() throws Exception
{
long timeout = tm.getTransactionTimeoutMilliseconds(0L);
tm.setTransactionTimeout((int)timeout/4000);
tm.begin();
timeDelta += timeout;
try
{
tm.commit();
fail("Tx Should get Rollback exception");
}catch(RollbackException rex)
{
// Caught expected exception
}
// Now test if the default timeout is active
tm.begin();
timeDelta += timeout/2;
tm.commit();
// Its a failure if exception occurs.
}
// resume throws InvalidTransactionException on completed tx (via commit)
public void testResume1() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
tm.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
try {
tm.resume(tx);
fail();
} catch (InvalidTransactionException e) {
// expected
}
}
// resume throws InvalidTransactionException on completed tx (via rollback)
public void testResume2() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
tx = tm.suspend();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
tm.resume(tx);
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
assertEquals(tx, tm.getTransaction());
tm.rollback();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
try {
tm.resume(tx);
fail();
} catch (InvalidTransactionException e) {
// expected
}
}
// resume work on null tx
public void testResume3() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
tm.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
// tx should be null
tx = tm.suspend();
assertNull(tx);
try {
tm.resume(tx);
} catch (InvalidTransactionException e) {
// null is considered valid so we don't expect InvalidTransactionException here
e.printStackTrace();
fail();
}
}
// resume works on any valid tx
public void testResume4() throws Exception {
Transaction tx;
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
tm.begin();
assertEquals(Status.STATUS_ACTIVE, tm.getStatus());
tx = tm.getTransaction();
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
try {
tm.resume(tx);
assertNotNull(tx);
assertEquals(Status.STATUS_ACTIVE, tx.getStatus());
} catch (InvalidTransactionException e) {
// tx is considered valid so we don't expect InvalidTransactionException here
e.printStackTrace();
fail();
}
tm.commit();
assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
assertNull(tm.getTransaction());
}
}
| 6,470 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/MockLog.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.geronimo.transaction.manager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockLog implements TransactionLog {
final Map<Xid, Recovery.XidBranchesPair> prepared = new HashMap<Xid, Recovery.XidBranchesPair>();
final List<Xid> committed = new ArrayList<Xid>();
final List<Xid> rolledBack = new ArrayList<Xid>();
public void begin(Xid xid) throws LogException {
}
public Object prepare(Xid xid, List<? extends TransactionBranchInfo> branches) throws LogException {
Object mark = new Object();
Recovery.XidBranchesPair xidBranchesPair = new Recovery.XidBranchesPair(xid, mark);
xidBranchesPair.getBranches().addAll(branches);
prepared.put(xid, xidBranchesPair);
return mark;
}
public void commit(Xid xid, Object logMark) throws LogException {
committed.add(xid);
}
public void rollback(Xid xid, Object logMark) throws LogException {
rolledBack.add(xid);
}
public Collection<Recovery.XidBranchesPair> recover(XidFactory xidFactory) throws LogException {
Map<Xid, Recovery.XidBranchesPair> copy = new HashMap<Xid, Recovery.XidBranchesPair>(prepared);
copy.keySet().removeAll(committed);
copy.keySet().removeAll(rolledBack);
return copy.values();
}
public String getXMLStats() {
return null;
}
public int getAverageForceTime() {
return 0;
}
public int getAverageBytesPerForce() {
return 0;
}
}
| 6,471 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/manager/TransactionSynchronizationRegistryTest.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.geronimo.transaction.manager;
import jakarta.transaction.Synchronization;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.NotSupportedException;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class TransactionSynchronizationRegistryTest extends TestCase {
private static int beforeCounter = 0;
private static int afterCounter = 0;
private GeronimoTransactionManager tm;
private CountingSync interposedSync;
private CountingSync normalSync;
protected void setUp() throws Exception {
tm = new GeronimoTransactionManager();
}
private void setUpInterposedSync() throws NotSupportedException, SystemException {
interposedSync = new CountingSync();
tm.begin();
tm.registerInterposedSynchronization(interposedSync);
}
private void setUpSyncs() throws Exception {
normalSync = new CountingSync();
setUpInterposedSync();
tm.getTransaction().registerSynchronization(normalSync);
}
public void testTransactionKey() throws Exception {
normalSync = new CountingSync();
assertNull(tm.getTransactionKey());
setUpInterposedSync();
tm.getTransaction().registerSynchronization(normalSync);
assertNotNull(tm.getTransactionKey());
tm.commit();
assertNull(tm.getTransactionKey());
}
public void testInterposedSynchIsCalledOnCommit() throws Exception {
setUpInterposedSync();
tm.commit();
checkInterposedSyncCalled();
}
private void checkInterposedSyncCalled() {
assertTrue("interposedSync beforeCompletion was not called", interposedSync.getBeforeCount() != -1);
assertTrue("interposedSync afterCompletion was not called", interposedSync.getAfterCount() != -1);
}
private void checkInterposedSyncCalledOnRollback() {
assertTrue("interposedSync afterCompletion was not called", interposedSync.getAfterCount() != -1);
}
public void testInterposedSynchIsCalledOnRollback() throws Exception {
setUpInterposedSync();
tm.rollback();
checkInterposedSyncCalledOnRollback();
}
// check normal synch before completion is not called on rollback
public void testNormalSynchBeforeCompletion() throws Exception {
normalSync = new CountingSync();
tm.begin();
tm.getTransaction().registerSynchronization(normalSync);
tm.rollback();
assertFalse(normalSync.beforeCompletionCalled());
assertTrue(normalSync.afterCompletionCalled());
}
public void testInterposedSynchIsCalledOnMarkRollback() throws Exception {
setUpInterposedSync();
tm.setRollbackOnly();
try {
tm.commit();
fail("expected a RollbackException");
} catch (HeuristicMixedException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (HeuristicRollbackException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (IllegalStateException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (RollbackException e) {
} catch (SecurityException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (SystemException e) {
fail("expected a RollbackException not " + e.getClass());
}
checkInterposedSyncCalled();
}
public void testSynchCallOrderOnCommit() throws Exception {
setUpSyncs();
tm.commit();
checkSyncCallOrder();
}
private void checkSyncCallOrder() {
checkInterposedSyncCalled();
assertTrue("interposedSync beforeCompletion was not called after normalSync beforeCompletion", interposedSync.getBeforeCount() > normalSync.getBeforeCount());
assertTrue("interposedSync afterCompletion was not called before normalSync beforeCompletion", interposedSync.getAfterCount() < normalSync.getAfterCount());
}
private void checkSyncCallOrderOnRollback() {
checkInterposedSyncCalledOnRollback();
assertTrue("interposedSync afterCompletion was not called before normalSync beforeCompletion", interposedSync.getAfterCount() < normalSync.getAfterCount());
}
public void testSynchCallOrderOnRollback() throws Exception {
setUpSyncs();
tm.rollback();
checkSyncCallOrderOnRollback();
}
public void testSynchCallOrderOnMarkRollback() throws Exception {
setUpSyncs();
tm.setRollbackOnly();
try {
tm.commit();
fail("expected a RollbackException");
} catch (HeuristicMixedException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (HeuristicRollbackException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (IllegalStateException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (RollbackException e) {
} catch (SecurityException e) {
fail("expected a RollbackException not " + e.getClass());
} catch (SystemException e) {
fail("expected a RollbackException not " + e.getClass());
}
checkSyncCallOrder();
}
private class CountingSync implements Synchronization {
private int beforeCount = -1;
private int afterCount = -1;
private boolean beforeCalled = false;
private boolean afterCalled = false;
public void beforeCompletion() {
beforeCalled = true;
beforeCount = beforeCounter++;
}
public void afterCompletion(int i) {
afterCalled = true;
afterCount = afterCounter++;
}
public int getBeforeCount() {
return beforeCount;
}
public int getAfterCount() {
return afterCount;
}
public boolean beforeCompletionCalled() {
return beforeCalled;
}
public boolean afterCompletionCalled() {
return afterCalled;
}
}
}
| 6,472 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/log/AbstractLogTest.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.geronimo.transaction.log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;
import org.apache.geronimo.transaction.manager.TransactionLog;
/**
*
*
* @version $Rev$ $Date$
*
* */
public abstract class AbstractLogTest extends TestCase {
private Object startBarrier = new Object();
private Object stopBarrier = new Object();
private int startedThreads = 0;
private int stoppedThreads = 0;
long totalDuration = 0;
private Xid xid;
private List names;
final Object mutex = new Object();
long totalXidCount = 0;
private Writer resultsXML;
private Writer resultsCSV;
public void testDummy() throws Exception {}
public void testTransactionLog() throws Exception {
File resultFileXML = new File(getResultFileName() + ".xml");
resultsXML = new FileWriter(resultFileXML);
resultsXML.write("<log-test>\n");
File resultFileCSV = new File(getResultFileName() + ".csv");
resultsCSV = new FileWriter(resultFileCSV);
resultsCSV.write("workerCount,xidCount,TotalXids,missingXids,DurationMilliseconds,XidsPerSecond,AverageForceTime,AverageBytesPerForce,AverageLatency\n");
int xidCount = Integer.getInteger("xa.log.test.xid.count", 50).intValue();
int minWorkerCount = Integer.getInteger("xa.log.test.worker.count.min", 20).intValue();
int maxWorkerCount = Integer.getInteger("xa.log.test.worker.count.max", 40).intValue();
int workerCountStep = Integer.getInteger("xa.log.test.worker.count.step", 20).intValue();
int repCount = Integer.getInteger("xa.log.test.repetition.count", 1).intValue();
long maxTime = Long.getLong("xa.log.test.max.time.seconds", 30).longValue() * 1000;
int overtime = 0;
try {
for (int workers = minWorkerCount; workers <= maxWorkerCount; workers += workerCountStep) {
for (int reps = 0; reps < repCount; reps++) {
if (testTransactionLog(workers, xidCount) > maxTime) {
overtime++;
if (overtime > 1) {
return;
}
}
resultsCSV.flush();
resultsXML.flush();
}
}
} finally {
resultsXML.write("</log-test>\n");
resultsXML.flush();
resultsXML.close();
resultsCSV.flush();
resultsCSV.close();
}
}
protected abstract String getResultFileName();
public long testTransactionLog(int workers, int xidCount) throws Exception {
TransactionLog transactionLog = createTransactionLog();
xid = new XidImpl2(new byte[Xid.MAXGTRIDSIZE]);
//TODO Supply an actual list
names = Collections.EMPTY_LIST;
long startTime = journalTest(transactionLog, workers, xidCount);
long stopTime = System.currentTimeMillis();
printSpeedReport(transactionLog, startTime, stopTime, workers, xidCount);
closeTransactionLog(transactionLog);
return stopTime - startTime;
}
protected abstract void closeTransactionLog(TransactionLog transactionLog) throws Exception ;
protected abstract TransactionLog createTransactionLog() throws Exception;
private long journalTest(final TransactionLog logger, final int workers, final int xidCount)
throws Exception {
totalXidCount = 0;
startedThreads = 0;
stoppedThreads = 0;
totalDuration = 0;
for (int i = 0; i < workers; i++) {
new Thread() {
public void run() {
long localXidCount = 0;
boolean exception = false;
long localDuration = 0;
try {
synchronized (startBarrier) {
++startedThreads;
startBarrier.notifyAll();
while (startedThreads < (workers + 1)) startBarrier.wait();
}
long localStartTime = System.currentTimeMillis();
for (int i = 0; i < xidCount; i++) {
// journalize COMMITTING record
Object logMark = logger.prepare(xid, names);
//localXidCount++;
// journalize FORGET record
logger.commit(xid, logMark);
localXidCount++;
}
localDuration = System.currentTimeMillis() - localStartTime;
} catch (Exception e) {
//
// FIXME: Remove System.err usage
//
System.err.println(Thread.currentThread().getName());
e.printStackTrace(System.err);
exception = true;
} finally {
synchronized (mutex) {
totalXidCount += localXidCount;
totalDuration += localDuration;
}
synchronized (stopBarrier) {
++stoppedThreads;
stopBarrier.notifyAll();
}
}
}
}
.start();
}
// Wait for all the workers to be ready..
long startTime = 0;
synchronized (startBarrier) {
while (startedThreads < workers) startBarrier.wait();
++startedThreads;
startBarrier.notifyAll();
startTime = System.currentTimeMillis();
}
// Wait for all the workers to finish.
synchronized (stopBarrier) {
while (stoppedThreads < workers) stopBarrier.wait();
}
return startTime;
}
void printSpeedReport(TransactionLog logger, long startTime, long stopTime, int workers, int xidCount) throws IOException {
long mc = ((long) xidCount) * workers;
long duration = (stopTime - startTime);
long xidsPerSecond = (totalXidCount * 1000 / (duration));
int averageForceTime = logger.getAverageForceTime();
int averageBytesPerForce = logger.getAverageBytesPerForce();
long averageLatency = totalDuration/totalXidCount;
resultsXML.write("<run><workers>" + workers + "</workers><xids-per-thread>" + xidCount + "</xids-per-thread><expected-total-xids>" + mc + "</expected-total-xids><missing-xids>" + (mc - totalXidCount) + "</missing-xids><totalDuration-milliseconds>" + duration + "</totalDuration-milliseconds><xids-per-second>" + xidsPerSecond + "</xids-per-second></run>\n");
resultsXML.write(logger.getXMLStats() + "\n");
resultsCSV.write("" + workers + "," + xidCount + "," + mc + "," + (mc - totalXidCount) + "," + duration + "," + xidsPerSecond + "," + averageForceTime + "," + averageBytesPerForce + "," + averageLatency + "\n");
}
}
| 6,473 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/test/java/org/apache/geronimo/transaction/log/HOWLLogTest.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.geronimo.transaction.log;
import java.io.File;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.geronimo.transaction.manager.TransactionLog;
import org.apache.geronimo.transaction.manager.XidFactory;
import org.apache.geronimo.transaction.manager.XidFactoryImpl;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class HOWLLogTest extends AbstractLogTest {
private static final File basedir = new File(System.getProperty("basedir", System.getProperty("user.dir")));
private static final String LOG_FILE_NAME = "howl_test";
protected String getResultFileName() {
return "howllog";
}
protected void closeTransactionLog(TransactionLog transactionLog) throws Exception {
((HOWLLog) transactionLog).doStop();
}
protected TransactionLog createTransactionLog() throws Exception {
XidFactory xidFactory = new XidFactoryImpl("hi".getBytes());
HOWLLog howlLog = new HOWLLog(
"org.objectweb.howl.log.BlockLogBuffer", // "bufferClassName",
4, // "bufferSizeKBytes",
true, // "checksumEnabled",
true, // "adler32Checksum",
20, // "flushSleepTime",
"txlog", // "logFileDir",
"log", // "logFileExt",
LOG_FILE_NAME, // "logFileName",
200, // "maxBlocksPerFile",
10, // "maxBuffers",
2, // "maxLogFiles",
2, // "minBuffers",
10,// "threadsWaitingForceThreshold"});
xidFactory,
new File(basedir, "target")
);
howlLog.doStart();
return howlLog;
}
public static Test suite() {
return new TestSetup(new TestSuite(HOWLLogTest.class)) {
protected void setUp() throws Exception {
File logFile = new File(basedir, "target/" + LOG_FILE_NAME + "_1.log");
if (logFile.exists()) {
logFile.delete();
}
logFile = new File(basedir, "target/" + LOG_FILE_NAME + "_2.log");
if (logFile.exists()) {
logFile.delete();
}
}
};
}
}
| 6,474 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/GeronimoUserTransaction.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.geronimo.transaction;
import java.io.Serializable;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.UserTransaction;
public final class GeronimoUserTransaction implements UserTransaction, Serializable {
private static final long serialVersionUID = -7524804683512228998L;
private transient TransactionManager transactionManager;
public GeronimoUserTransaction(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
boolean isActive() {
return transactionManager != null;
}
public void setTransactionManager(TransactionManager transactionManager) {
if (this.transactionManager == null) {
this.transactionManager = transactionManager;
} else if (this.transactionManager != transactionManager) {
throw new IllegalStateException("This user transaction is already associated with another transaction manager");
}
}
public int getStatus() throws SystemException {
return transactionManager.getStatus();
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
transactionManager.setRollbackOnly();
}
public void setTransactionTimeout(int seconds) throws SystemException {
if (seconds < 0) {
throw new SystemException("transaction timeout must be positive or 0, not " + seconds);
}
transactionManager.setTransactionTimeout(seconds);
}
public void begin() throws NotSupportedException, SystemException {
transactionManager.begin();
}
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
transactionManager.commit();
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
transactionManager.rollback();
}
}
| 6,475 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/MonitorableTransactionManager.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.geronimo.transaction.manager;
import java.util.EventListener;
/**
* @version $Rev$ $Date$
*/
public interface MonitorableTransactionManager extends EventListener {
// todo add notifications for begin, syspend, resume, commit, rollback and exceptions
void addTransactionAssociationListener(TransactionManagerMonitor listener);
void removeTransactionAssociationListener(TransactionManagerMonitor listener);
}
| 6,476 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/SetRollbackOnlyException.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.geronimo.transaction.manager;
/**
* @version $Rev$ $Date$
*/
public class SetRollbackOnlyException extends Exception {
public SetRollbackOnlyException() {
super("setRollbackOnly() called. See stacktrace for origin");
}
}
| 6,477 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/LogException.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.geronimo.transaction.manager;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class LogException extends Exception {
public LogException() {
super();
}
public LogException(String message) {
super(message);
}
public LogException(String message, Throwable cause) {
super(message, cause);
}
public LogException(Throwable cause) {
super(cause);
}
}
| 6,478 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/SystemCurrentTime.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.geronimo.transaction.manager;
/**
* A time provider returning the standard {@link System#currentTimeMillis()}.
*/
public class SystemCurrentTime implements CurrentTimeMsProvider {
/**
* A time provider returning the standard {@link System#currentTimeMillis()}.
*/
public static final CurrentTimeMsProvider INSTANCE = new SystemCurrentTime();
private SystemCurrentTime() {
// singleton
}
@Override
public long now() {
return System.currentTimeMillis();
}
}
| 6,479 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/Recovery.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.geronimo.transaction.manager;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface Recovery {
void recoverLog() throws XAException;
void recoverResourceManager(NamedXAResource xaResource) throws XAException;
boolean hasRecoveryErrors();
List getRecoveryErrors();
boolean localRecoveryComplete();
int localUnrecoveredCount();
//hard to implement.. needs ExternalTransaction to have a reference to externalXids.
// boolean remoteRecoveryComplete();
Map<Xid, TransactionImpl> getExternalXids();
public static class XidBranchesPair {
private final Xid xid;
//set of TransactionBranchInfo
private final Set<TransactionBranchInfo> branches = new HashSet<TransactionBranchInfo>();
private final Object mark;
public XidBranchesPair(Xid xid, Object mark) {
this.xid = xid;
this.mark = mark;
}
public Xid getXid() {
return xid;
}
public Set<TransactionBranchInfo> getBranches() {
return branches;
}
public Object getMark() {
return mark;
}
public void addBranch(TransactionBranchInfo branchInfo) {
branches.add(branchInfo);
}
}
}
| 6,480 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/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.geronimo.transaction.manager;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
import javax.transaction.xa.Xid;
/**
* Factory for transaction ids.
* The Xid is constructed of three parts:
* <ol><li>8 byte count (LSB first)</li>
* <li>4 byte system id</li>
* <li>2 byte entropy</li>
* <li>4 or 16 byte IP address of host</li>
* <ol>
* @version $Rev$ $Date$
* todo Should have a way of setting baseId
*/
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 XidFactoryImpl() {
byte[] hostid;
try {
hostid = InetAddress.getLocalHost().getAddress();
} catch (UnknownHostException e) {
hostid = new byte[]{127, 0, 0, 1};
}
int uid = System.identityHashCode(this);
baseId[8] = (byte) uid;
baseId[9] = (byte) (uid >>> 8);
baseId[10] = (byte) (uid >>> 16);
baseId[11] = (byte) (uid >>> 24);
byte[] entropy = new byte[2];
new Random().nextBytes(entropy);
baseId[12] = entropy[0];
baseId[13] = entropy[1];
System.arraycopy(hostid, 0, baseId, 14, hostid.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);
}
}
| 6,481 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/TransactionManagerImpl.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.geronimo.transaction.manager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.geronimo.transaction.log.UnrecoverableLog;
/**
* Simple implementation of a transaction manager.
*
* @version $Rev$ $Date$
*/
public class TransactionManagerImpl implements TransactionManager, UserTransaction, TransactionSynchronizationRegistry, XidImporter, MonitorableTransactionManager, RecoverableTransactionManager {
private static final Logger log = Logger.getLogger(TransactionManagerImpl.class.getName());
private static final Logger recoveryLog = Logger.getLogger("RecoveryController");
protected static final int DEFAULT_TIMEOUT = 600;
protected static final byte[] DEFAULT_TM_ID = new byte[] {71,84,77,73,68};
private final TransactionLog transactionLog;
private final XidFactory xidFactory;
private final int defaultTransactionTimeoutMilliseconds;
private final CurrentTimeMsProvider timeProvider;
private final ThreadLocal<Long> transactionTimeoutMilliseconds = new ThreadLocal<Long>();
private final ThreadLocal<Transaction> threadTx = new ThreadLocal<Transaction>();
private final ConcurrentHashMap<Transaction, Thread> associatedTransactions = new ConcurrentHashMap<Transaction, Thread>();
final Recovery recovery;
private final Map<String, NamedXAResourceFactory> namedXAResourceFactories = new ConcurrentHashMap<String, NamedXAResourceFactory>();
private final CopyOnWriteArrayList<TransactionManagerMonitor> transactionAssociationListeners = new CopyOnWriteArrayList<TransactionManagerMonitor>();
private final List<Exception> recoveryErrors = new ArrayList<Exception>();
private final RetryScheduler retryScheduler = new ExponentialtIntervalRetryScheduler();
// statistics
private AtomicLong totalCommits = new AtomicLong(0);
private AtomicLong totalRollBacks = new AtomicLong(0);
private AtomicLong activeCount = new AtomicLong(0);
public TransactionManagerImpl() throws XAException {
this(DEFAULT_TIMEOUT,
null,
null
);
}
public TransactionManagerImpl(int defaultTransactionTimeoutSeconds) throws XAException {
this(defaultTransactionTimeoutSeconds,
null,
null
);
}
public TransactionManagerImpl(int defaultTransactionTimeoutSeconds, TransactionLog transactionLog) throws XAException {
this(defaultTransactionTimeoutSeconds,
null,
transactionLog
);
}
public TransactionManagerImpl(int defaultTransactionTimeoutSeconds, XidFactory xidFactory, TransactionLog transactionLog) throws XAException {
this(defaultTransactionTimeoutSeconds, xidFactory, transactionLog, null);
}
public TransactionManagerImpl(int defaultTransactionTimeoutSeconds, XidFactory xidFactory,
TransactionLog transactionLog, CurrentTimeMsProvider timeProvider) throws XAException {
if (defaultTransactionTimeoutSeconds <= 0) {
throw new IllegalArgumentException("defaultTransactionTimeoutSeconds must be positive: attempted value: " + defaultTransactionTimeoutSeconds);
}
this.defaultTransactionTimeoutMilliseconds = defaultTransactionTimeoutSeconds * 1000;
this.timeProvider = timeProvider;
if (transactionLog == null) {
this.transactionLog = new UnrecoverableLog();
} else {
this.transactionLog = transactionLog;
}
if (xidFactory != null) {
this.xidFactory = xidFactory;
} else {
this.xidFactory = new XidFactoryImpl(DEFAULT_TM_ID);
}
recovery = new RecoveryImpl(this);
recovery.recoverLog();
}
public Transaction getTransaction() {
return threadTx.get();
}
private void associate(TransactionImpl tx) throws InvalidTransactionException {
if (tx.getStatus() == Status.STATUS_NO_TRANSACTION) {
throw new InvalidTransactionException("Cannot resume invalid transaction: " + tx);
} else {
Object existingAssociation = associatedTransactions.putIfAbsent(tx, Thread.currentThread());
if (existingAssociation != null) {
throw new InvalidTransactionException("Specified transaction is already associated with another thread");
}
threadTx.set(tx);
fireThreadAssociated(tx);
activeCount.getAndIncrement();
}
}
private void unassociate() {
Transaction tx = getTransaction();
if (tx != null) {
associatedTransactions.remove(tx);
threadTx.set(null);
fireThreadUnassociated(tx);
activeCount.getAndDecrement();
}
}
public void setTransactionTimeout(int seconds) throws SystemException {
if (seconds < 0) {
throw new SystemException("transaction timeout must be positive or 0 to reset to default");
}
if (seconds == 0) {
transactionTimeoutMilliseconds.set(null);
} else {
transactionTimeoutMilliseconds.set((long) seconds * 1000);
}
}
public int getStatus() throws SystemException {
Transaction tx = getTransaction();
return (tx != null) ? tx.getStatus() : Status.STATUS_NO_TRANSACTION;
}
public void begin() throws NotSupportedException, SystemException {
begin(getTransactionTimeoutMilliseconds(0L));
}
public Transaction begin(long transactionTimeoutMilliseconds) throws NotSupportedException, SystemException {
if (getStatus() != Status.STATUS_NO_TRANSACTION) {
throw new NotSupportedException("Nested Transactions are not supported");
}
TransactionImpl tx = new TransactionImpl(this, getTransactionTimeoutMilliseconds(transactionTimeoutMilliseconds), timeProvider);
// timeoutTimer.schedule(tx, getTransactionTimeoutMilliseconds(transactionTimeoutMilliseconds));
try {
associate(tx);
} catch (InvalidTransactionException e) {
// should not be possible since we just created that transaction and no one has a reference yet
throw (SystemException)new SystemException("Internal error: associate threw an InvalidTransactionException for a newly created transaction").initCause(e);
}
// Todo: Verify if this is correct thing to do. Use default timeout for next transaction.
this.transactionTimeoutMilliseconds.set(null);
return tx;
}
public Transaction suspend() throws SystemException {
Transaction tx = getTransaction();
if (tx != null) {
unassociate();
}
return tx;
}
public void resume(Transaction tx) throws IllegalStateException, InvalidTransactionException, SystemException {
if (getTransaction() != null && tx != getTransaction()) {
throw new IllegalStateException("Thread already associated with another transaction");
}
if (tx != null && tx != getTransaction()) {
if (!(tx instanceof TransactionImpl)) {
throw new InvalidTransactionException("Cannot resume foreign transaction: " + tx);
}
associate((TransactionImpl) tx);
}
}
public Object getResource(Object key) {
TransactionImpl tx = getActiveTransactionImpl();
return tx.getResource(key);
}
private TransactionImpl getActiveTransactionImpl() {
TransactionImpl tx = (TransactionImpl)threadTx.get();
if (tx == null) {
throw new IllegalStateException("No tx on thread");
}
if (tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
throw new IllegalStateException("Transaction " + tx + " is not active");
}
return tx;
}
public boolean getRollbackOnly() {
TransactionImpl tx = getActiveTransactionImpl();
return tx.getRollbackOnly();
}
public Object getTransactionKey() {
TransactionImpl tx = (TransactionImpl) getTransaction();
return tx == null ? null: tx.getTransactionKey();
}
public int getTransactionStatus() {
TransactionImpl tx = (TransactionImpl) getTransaction();
return tx == null? Status.STATUS_NO_TRANSACTION: tx.getTransactionStatus();
}
public void putResource(Object key, Object value) {
TransactionImpl tx = getActiveTransactionImpl();
tx.putResource(key, value);
}
/**
* jta 1.1 method so the jpa implementations can be told to flush their caches.
* @param synchronization interposed synchronization
*/
public void registerInterposedSynchronization(Synchronization synchronization) {
TransactionImpl tx = getActiveTransactionImpl();
tx.registerInterposedSynchronization(synchronization);
}
public void setRollbackOnly() throws IllegalStateException {
TransactionImpl tx = (TransactionImpl) threadTx.get();
if (tx == null) {
throw new IllegalStateException("No transaction associated with current thread");
}
tx.setRollbackOnly();
}
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
Transaction tx = getTransaction();
if (tx == null) {
throw new IllegalStateException("No transaction associated with current thread");
}
try {
tx.commit();
} finally {
unassociate();
}
totalCommits.getAndIncrement();
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
Transaction tx = getTransaction();
if (tx == null) {
throw new IllegalStateException("No transaction associated with current thread");
}
try {
tx.rollback();
} finally {
unassociate();
}
totalRollBacks.getAndIncrement();
}
//XidImporter implementation
public Transaction importXid(Xid xid, long transactionTimeoutMilliseconds) throws XAException, SystemException {
if (transactionTimeoutMilliseconds < 0) {
throw new SystemException("transaction timeout must be positive or 0 to reset to default");
}
return new TransactionImpl(xid, this, getTransactionTimeoutMilliseconds(transactionTimeoutMilliseconds), timeProvider);
}
public void commit(Transaction tx, boolean onePhase) throws XAException {
if (onePhase) {
try {
tx.commit();
} catch (HeuristicMixedException e) {
throw (XAException) new XAException().initCause(e);
} catch (HeuristicRollbackException e) {
throw (XAException) new XAException().initCause(e);
} catch (RollbackException e) {
throw (XAException) new XAException().initCause(e);
} catch (SecurityException e) {
throw (XAException) new XAException().initCause(e);
} catch (SystemException e) {
throw (XAException) new XAException().initCause(e);
}
} else {
try {
((TransactionImpl) tx).preparedCommit();
} catch (HeuristicMixedException e) {
throw (XAException) new XAException().initCause(e);
} catch (HeuristicRollbackException e) {
throw (XAException) new XAException().initCause(e);
} catch (SystemException e) {
throw (XAException) new XAException().initCause(e);
}
}
totalCommits.getAndIncrement();
}
public void forget(Transaction tx) throws XAException {
//TODO implement this!
}
public int prepare(Transaction tx) throws XAException {
try {
return ((TransactionImpl) tx).prepare();
} catch (SystemException e) {
throw (XAException) new XAException().initCause(e);
} catch (RollbackException e) {
throw (XAException) new XAException().initCause(e);
}
}
public void rollback(Transaction tx) throws XAException {
try {
tx.rollback();
} catch (IllegalStateException e) {
throw (XAException) new XAException().initCause(e);
} catch (SystemException e) {
throw (XAException) new XAException().initCause(e);
}
totalRollBacks.getAndIncrement();
}
long getTransactionTimeoutMilliseconds(long transactionTimeoutMilliseconds) {
if (transactionTimeoutMilliseconds != 0) {
return transactionTimeoutMilliseconds;
}
Long timeout = this.transactionTimeoutMilliseconds.get();
if (timeout != null) {
return timeout;
}
return defaultTransactionTimeoutMilliseconds;
}
//Recovery
public void recoveryError(Exception e) {
recoveryLog.log(Level.SEVERE, "Recovery error: {}", e.getMessage());
recoveryErrors.add(e);
}
public void registerNamedXAResourceFactory(NamedXAResourceFactory namedXAResourceFactory) {
namedXAResourceFactories.put(namedXAResourceFactory.getName(), namedXAResourceFactory);
new RecoverTask(retryScheduler, namedXAResourceFactory, recovery, this).run();
}
public void unregisterNamedXAResourceFactory(String namedXAResourceFactoryName) {
namedXAResourceFactories.remove(namedXAResourceFactoryName);
}
NamedXAResourceFactory getNamedXAResourceFactory(String xaResourceName) {
return namedXAResourceFactories.get(xaResourceName);
}
XidFactory getXidFactory() {
return xidFactory;
}
TransactionLog getTransactionLog() {
return transactionLog;
}
RetryScheduler getRetryScheduler() {
return retryScheduler;
}
public Map<Xid, TransactionImpl> getExternalXids() {
return new HashMap<Xid, TransactionImpl>(recovery.getExternalXids());
}
public void addTransactionAssociationListener(TransactionManagerMonitor listener) {
transactionAssociationListeners.addIfAbsent(listener);
}
public void removeTransactionAssociationListener(TransactionManagerMonitor listener) {
transactionAssociationListeners.remove(listener);
}
protected void fireThreadAssociated(Transaction tx) {
for (TransactionManagerMonitor listener : transactionAssociationListeners) {
try {
listener.threadAssociated(tx);
} catch (Exception e) {
log.log(Level.WARNING, "Error calling transaction association listener", e);
}
}
}
protected void fireThreadUnassociated(Transaction tx) {
for (TransactionManagerMonitor listener : transactionAssociationListeners) {
try {
listener.threadUnassociated(tx);
} catch (Exception e) {
log.log(Level.WARNING, "Error calling transaction association listener", e);
}
}
}
/**
* Returns the number of active transactions.
* @return the count of active transactions
*/
public long getActiveCount() {
return activeCount.longValue();
}
/**
* Return the number of total commits
* @return the number of commits since statistics were reset
*/
public long getTotalCommits() {
return totalCommits.longValue();
}
/**
* Returns the number of total rollbacks
* @return the number of rollbacks since statistics were reset
*/
public long getTotalRollbacks() {
return totalRollBacks.longValue();
}
/**
* Reset statistics
*/
public void resetStatistics() {
totalCommits.getAndSet(0);
totalRollBacks.getAndSet(0);
}
}
| 6,482 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/XidImporter.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.geronimo.transaction.manager;
import java.util.Map;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAException;
import jakarta.transaction.Transaction;
import jakarta.transaction.SystemException;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface XidImporter {
Transaction importXid(Xid xid, long transactionTimeoutMillis) throws XAException, SystemException;
void commit(Transaction tx, boolean onePhase) throws XAException;
void forget(Transaction tx) throws XAException;
int prepare(Transaction tx) throws XAException;
void rollback(Transaction tx) throws XAException;
Map<Xid, TransactionImpl> getExternalXids();
}
| 6,483 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoveryImpl.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.geronimo.transaction.manager;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class RecoveryImpl implements Recovery {
private static final Logger log = Logger.getLogger("Recovery");
private final TransactionManagerImpl txManager;
private final Map<Xid, TransactionImpl> externalXids = new HashMap<Xid, TransactionImpl>();
private final Map<ByteArrayWrapper, XidBranchesPair> ourXids = new HashMap<ByteArrayWrapper, XidBranchesPair>();
private final Map<String, Set<XidBranchesPair>> nameToOurTxMap = new HashMap<String, Set<XidBranchesPair>>();
private final Map<byte[], TransactionImpl> externalGlobalIdMap = new HashMap<byte[], TransactionImpl>();
private final List<Exception> recoveryErrors = new ArrayList<Exception>();
public RecoveryImpl(TransactionManagerImpl txManager) {
this.txManager = txManager;
}
public synchronized void recoverLog() throws XAException {
Collection<XidBranchesPair> preparedXids;
try {
preparedXids = txManager.getTransactionLog().recover(txManager.getXidFactory());
} catch (LogException e) {
throw (XAException) new XAException(XAException.XAER_RMERR).initCause(e);
}
for (XidBranchesPair xidBranchesPair : preparedXids) {
Xid xid = xidBranchesPair.getXid();
log.log(Level.FINEST,"read prepared global xid from log: " + toString(xid));
if (txManager.getXidFactory().matchesGlobalId(xid.getGlobalTransactionId())) {
ourXids.put(new ByteArrayWrapper(xid.getGlobalTransactionId()), xidBranchesPair);
for (TransactionBranchInfo transactionBranchInfo : xidBranchesPair.getBranches()) {
log.log(Level.FINEST,"read branch from log: " + transactionBranchInfo.toString());
String name = transactionBranchInfo.getResourceName();
Set<XidBranchesPair> transactionsForName = nameToOurTxMap.get(name);
if (transactionsForName == null) {
transactionsForName = new HashSet<XidBranchesPair>();
nameToOurTxMap.put(name, transactionsForName);
}
transactionsForName.add(xidBranchesPair);
}
} else {
log.log(Level.FINEST,"read external prepared xid from log: " + toString(xid));
TransactionImpl externalTx = new ExternalTransaction(xid, txManager, xidBranchesPair.getBranches());
externalXids.put(xid, externalTx);
externalGlobalIdMap.put(xid.getGlobalTransactionId(), externalTx);
}
}
}
public synchronized void recoverResourceManager(NamedXAResource xaResource) throws XAException {
String name = xaResource.getName();
Xid[] prepared = xaResource.recover(XAResource.TMSTARTRSCAN + XAResource.TMENDRSCAN);
for (int i = 0; prepared != null && i < prepared.length; i++) {
Xid xid = prepared[i];
if (xid.getGlobalTransactionId() == null || xid.getBranchQualifier() == null) {
log.log(Level.WARNING, "Ignoring bad xid from\n name: " + xaResource.getName() + "\n " + toString(xid));
continue;
}
log.log(Level.FINEST,"Considering recovered xid from\n name: " + xaResource.getName() + "\n " + toString(xid));
ByteArrayWrapper globalIdWrapper = new ByteArrayWrapper(xid.getGlobalTransactionId());
XidBranchesPair xidNamesPair = ourXids.get(globalIdWrapper);
if (xidNamesPair != null) {
// Only commit if this NamedXAResource was the XAResource for the transaction.
// Otherwise, wait for recoverResourceManager to be called for the actual XAResource
// This is a bit wasteful, but given our management of XAResources by "name", is about the best we can do.
if (isNameInTransaction(xidNamesPair, name, xid)) {
log.log(Level.FINEST,"This xid was prepared from this XAResource: committing");
commit(xaResource, xid);
removeNameFromTransaction(xidNamesPair, name, true);
} else {
log.log(Level.FINEST,"This xid was prepared from another XAResource, ignoring");
}
} else if (txManager.getXidFactory().matchesGlobalId(xid.getGlobalTransactionId())) {
//ours, but prepare not logged
log.log(Level.FINEST,"this xid was initiated from this tm but not prepared: rolling back");
rollback(xaResource, xid);
} else if (txManager.getXidFactory().matchesBranchId(xid.getBranchQualifier())) {
//our branch, but we did not start this tx.
TransactionImpl externalTx = externalGlobalIdMap.get(xid.getGlobalTransactionId());
if (externalTx == null) {
//we did not prepare this branch, rollback.
log.log(Level.FINEST,"this xid is from an external transaction and was not prepared: rolling back");
rollback(xaResource, xid);
} else {
log.log(Level.FINEST,"this xid is from an external transaction and was prepared in this tm. Waiting for instructions from transaction originator");
//we prepared this branch, must wait for commit/rollback command.
externalTx.addBranchXid(xaResource, xid);
}
}
//else we had nothing to do with this xid.
}
Set<XidBranchesPair> transactionsForName = nameToOurTxMap.get(name);
if (transactionsForName != null) {
for (XidBranchesPair xidBranchesPair : transactionsForName) {
removeNameFromTransaction(xidBranchesPair, name, false);
}
}
}
private void commit(NamedXAResource xaResource, Xid xid) {
doCommitOrRollback(xaResource, xid, true);
}
private void rollback(NamedXAResource xaResource, Xid xid) {
doCommitOrRollback(xaResource, xid, false);
}
private void doCommitOrRollback(NamedXAResource xaResource, Xid xid, boolean commit) {
try {
if (commit) {
xaResource.commit(xid, false);
} else {
xaResource.rollback(xid);
}
} catch (XAException e) {
try {
if (e.errorCode == XAException.XA_HEURRB) {
log.info("Transaction has been heuristically rolled back");
xaResource.forget(xid);
} else if (e.errorCode == XAException.XA_HEURMIX) {
log.info("Transaction has been heuristically committed and rolled back");
xaResource.forget(xid);
} else if (e.errorCode == XAException.XA_HEURCOM) {
log.info("Transaction has been heuristically committed");
xaResource.forget(xid);
} else {
recoveryErrors.add(e);
log.log(Level.SEVERE, "Could not roll back", e);
}
} catch (XAException e2) {
if (e2.errorCode == XAException.XAER_NOTA) {
// NOTA in response to forget, means the resource already forgot the transaction
// ignore
} else {
recoveryErrors.add(e);
log.log(Level.SEVERE, "Could not roll back", e);
}
}
}
}
private boolean isNameInTransaction(XidBranchesPair xidBranchesPair, String name, Xid xid) {
for (TransactionBranchInfo transactionBranchInfo : xidBranchesPair.getBranches()) {
if (name.equals(transactionBranchInfo.getResourceName()) && equals(xid, transactionBranchInfo.getBranchXid())) {
return true;
}
}
return false;
}
private boolean equals(Xid xid1, Xid xid2) {
return xid1.getFormatId() == xid1.getFormatId()
&& Arrays.equals(xid1.getBranchQualifier(), xid2.getBranchQualifier())
&& Arrays.equals(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
}
private void removeNameFromTransaction(XidBranchesPair xidBranchesPair, String name, boolean warn) {
int removed = 0;
for (Iterator branches = xidBranchesPair.getBranches().iterator(); branches.hasNext();) {
TransactionBranchInfo transactionBranchInfo = (TransactionBranchInfo) branches.next();
if (name.equals(transactionBranchInfo.getResourceName())) {
branches.remove();
removed++;
}
}
if (warn && removed == 0) {
log.log(Level.SEVERE, "XAResource named: " + name + " returned branch xid for xid: " + xidBranchesPair.getXid() + " but was not registered with that transaction!");
}
if (xidBranchesPair.getBranches().isEmpty() && 0 != removed ) {
try {
ourXids.remove(new ByteArrayWrapper(xidBranchesPair.getXid().getGlobalTransactionId()));
txManager.getTransactionLog().commit(xidBranchesPair.getXid(), xidBranchesPair.getMark());
} catch (LogException e) {
recoveryErrors.add(e);
log.log(Level.SEVERE, "Could not commit", e);
}
}
}
public synchronized boolean hasRecoveryErrors() {
return !recoveryErrors.isEmpty();
}
public synchronized List<Exception> getRecoveryErrors() {
return Collections.unmodifiableList(recoveryErrors);
}
public synchronized boolean localRecoveryComplete() {
return ourXids.isEmpty();
}
public synchronized int localUnrecoveredCount() {
return ourXids.size();
}
//hard to implement.. needs ExternalTransaction to have a reference to externalXids.
// public boolean remoteRecoveryComplete() {
// }
public synchronized Map<Xid, TransactionImpl> getExternalXids() {
return new HashMap<Xid, TransactionImpl>(externalXids);
}
private static String toString(Xid xid) {
if (xid instanceof XidImpl) {
return xid.toString();
}
StringBuilder s = new StringBuilder();
s.append("[Xid:class=").append(xid.getClass().getSimpleName()).append(":globalId=");
byte[] globalId = xid.getGlobalTransactionId();
if (globalId == null) {
s.append("null");
} else {
for (int i = 0; i < globalId.length; i++) {
s.append(Integer.toHexString(globalId[i]));
}
s.append(",length=").append(globalId.length);
}
s.append(",branchId=");
byte[] branchId = xid.getBranchQualifier();
if (branchId == null) {
s.append("null");
} else {
for (int i = 0; i < branchId.length; i++) {
s.append(Integer.toHexString(branchId[i]));
}
s.append(",length=").append(branchId.length);
}
s.append("]");
return s.toString();
}
private static class ByteArrayWrapper {
private final byte[] bytes;
private final int hashCode;
public ByteArrayWrapper(final byte[] bytes) {
assert bytes != null;
this.bytes = bytes;
int hash = 0;
for (byte aByte : bytes) {
hash += 37 * aByte;
}
hashCode = hash;
}
public boolean equals(Object other) {
if (other instanceof ByteArrayWrapper) {
return Arrays.equals(bytes, ((ByteArrayWrapper)other).bytes);
}
return false;
}
public int hashCode() {
return hashCode;
}
}
private static class ExternalTransaction extends TransactionImpl {
private final Set<String> resourceNames = new HashSet<String>();
public ExternalTransaction(Xid xid, TransactionManagerImpl txManager, Set<TransactionBranchInfo> resourceNames) {
super(xid, txManager);
for (TransactionBranchInfo info: resourceNames) {
this.resourceNames.add(info.getResourceName());
}
}
public boolean hasName(String name) {
return resourceNames.contains(name);
}
public void removeName(String name) {
resourceNames.remove(name);
}
public void preparedCommit() throws HeuristicRollbackException, HeuristicMixedException, SystemException {
if (!resourceNames.isEmpty()) {
throw new SystemException("This tx does not have all resource managers online, commit not allowed yet");
}
super.preparedCommit();
}
public void rollback() throws SystemException {
if (!resourceNames.isEmpty()) {
throw new SystemException("This tx does not have all resource managers online, rollback not allowed yet");
}
super.rollback();
}
}
}
| 6,484 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/TransactionLog.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.geronimo.transaction.manager;
import java.util.Collection;
import java.util.List;
import javax.transaction.xa.Xid;
/**
* Interface used to notify a logging subsystem of transaction events.
*
* @version $Rev$ $Date$
*/
public interface TransactionLog {
void begin(Xid xid) throws LogException;
/**
* log prepare for the global xid xid and the list of TransactionBranchInfo branches
* @param xid global xid for the transactions
* @param branches List of TransactionBranchInfo
* @return log mark to use in commit/rollback calls.
* @throws LogException on error
*/
Object prepare(Xid xid, List<? extends TransactionBranchInfo> branches) throws LogException;
void commit(Xid xid, Object logMark) throws LogException;
void rollback(Xid xid, Object logMark) throws LogException;
/**
* Recovers the log, returning a map of (top level) xid to List of TransactionBranchInfo for the branches.
* Uses the XidFactory to reconstruct the xids.
*
* @param xidFactory Xid factory
* @return Map of recovered xid to List of TransactionBranchInfo representing the branches.
* @throws LogException on error
*/
Collection<Recovery.XidBranchesPair> recover(XidFactory xidFactory) throws LogException;
String getXMLStats();
int getAverageForceTime();
int getAverageBytesPerForce();
}
| 6,485 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/GeronimoTransactionManager.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.geronimo.transaction.manager;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import jakarta.resource.spi.XATerminator;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* Adds implementations of XATerminator and XAWork interfaces to basic TransactionManagerImpl
*
* @version $Rev$ $Date$
*/
public class GeronimoTransactionManager extends TransactionManagerImpl implements XATerminator, XAWork {
private final Map importedTransactions = new HashMap();
private boolean isInRecovery = false;
public GeronimoTransactionManager() throws XAException {
}
public GeronimoTransactionManager(int defaultTransactionTimeoutSeconds) throws XAException {
super(defaultTransactionTimeoutSeconds);
}
public GeronimoTransactionManager(int defaultTransactionTimeoutSeconds, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, transactionLog);
}
public GeronimoTransactionManager(int defaultTransactionTimeoutSeconds, XidFactory xidFactory, TransactionLog transactionLog) throws XAException {
super(defaultTransactionTimeoutSeconds, xidFactory, transactionLog);
}
/**
* @see jakarta.resource.spi.XATerminator#commit(javax.transaction.xa.Xid, boolean)
*/
public void commit(Xid xid, boolean onePhase) throws XAException {
Transaction importedTransaction;
synchronized (importedTransactions) {
importedTransaction = (Transaction) importedTransactions.remove(xid);
}
if (importedTransaction == null) {
throw new XAException("No imported transaction for xid: " + xid);
}
try {
int status = importedTransaction.getStatus();
assert status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARED: "invalid status: " + status;
} catch (SystemException e) {
throw (XAException)new XAException().initCause(e);
}
commit(importedTransaction, onePhase);
}
/**
* @see jakarta.resource.spi.XATerminator#forget(javax.transaction.xa.Xid)
*/
public void forget(Xid xid) throws XAException {
Transaction importedTransaction;
synchronized (importedTransactions) {
importedTransaction = (Transaction) importedTransactions.remove(xid);
}
if (importedTransaction == null) {
throw new XAException("No imported transaction for xid: " + xid);
}
//todo is there a correct status test here?
// try {
// int status = tx.getStatus();
// assert status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARED;
// } catch (SystemException e) {
// throw new XAException();
// }
forget(importedTransaction);
}
/**
* @see jakarta.resource.spi.XATerminator#prepare(javax.transaction.xa.Xid)
*/
public int prepare(Xid xid) throws XAException {
Transaction importedTransaction;
synchronized (importedTransactions) {
importedTransaction = (Transaction) importedTransactions.get(xid);
}
if (importedTransaction == null) {
throw new XAException("No imported transaction for xid: " + xid);
}
try {
int status = importedTransaction.getStatus();
assert status == Status.STATUS_ACTIVE;
} catch (SystemException e) {
throw (XAException)new XAException().initCause(e);
}
return prepare(importedTransaction);
}
/**
* @see jakarta.resource.spi.XATerminator#recover(int)
*/
public Xid[] recover(int flag) throws XAException {
if (!isInRecovery) {
if ((flag & XAResource.TMSTARTRSCAN) == 0) {
throw new XAException(XAException.XAER_PROTO);
}
isInRecovery = true;
}
if ((flag & XAResource.TMENDRSCAN) != 0) {
isInRecovery = false;
}
//we always return all xids in first call.
//calling "startrscan" repeatedly starts at beginning of list again.
if ((flag & XAResource.TMSTARTRSCAN) != 0) {
Map recoveredXidMap = getExternalXids();
Xid[] recoveredXids = new Xid[recoveredXidMap.size()];
int i = 0;
synchronized (importedTransactions) {
for (Iterator iterator = recoveredXidMap.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
Xid xid = (Xid) entry.getKey();
recoveredXids[i++] = xid;
Transaction transaction = (Transaction) entry.getValue();
importedTransactions.put(xid, transaction);
}
}
return recoveredXids;
} else {
return new Xid[0];
}
}
/**
* @see jakarta.resource.spi.XATerminator#rollback(javax.transaction.xa.Xid)
*/
public void rollback(Xid xid) throws XAException {
Transaction importedTransaction;
synchronized (importedTransactions) {
importedTransaction = (Transaction) importedTransactions.remove(xid);
}
if (importedTransaction == null) {
throw new XAException("No imported transaction for xid: " + xid);
}
try {
int status = importedTransaction.getStatus();
assert status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARED;
} catch (SystemException e) {
throw (XAException)new XAException().initCause(e);
}
rollback(importedTransaction);
}
//XAWork implementation
public void begin(Xid xid, long txTimeoutMillis) throws XAException, InvalidTransactionException, SystemException, ImportedTransactionActiveException {
Transaction importedTransaction;
synchronized (importedTransactions) {
importedTransaction = (Transaction) importedTransactions.get(xid);
if (importedTransaction == null) {
// this does not associate tx with current thread.
importedTransaction = importXid(xid, txTimeoutMillis);
importedTransactions.put(xid, importedTransaction);
}
// associate the the imported transaction with the current thread
try {
resume(importedTransaction);
} catch (InvalidTransactionException e) {
// this occures if our transaciton is associated with another thread
throw (ImportedTransactionActiveException)new ImportedTransactionActiveException(xid).initCause(e);
}
}
}
public void end(Xid xid) throws XAException, SystemException {
synchronized (importedTransactions) {
Transaction importedTransaction = (Transaction) importedTransactions.get(xid);
if (importedTransaction == null) {
throw new XAException("No imported transaction for xid: " + xid);
}
if (importedTransaction != getTransaction()) {
throw new XAException("Imported transaction is not associated with the current thread xid: " + xid);
}
suspend();
}
}
}
| 6,486 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/TransactionImpl.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.geronimo.transaction.manager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* Basic local transaction with support for multiple resources.
*
* @version $Rev$ $Date$
*/
public class TransactionImpl implements Transaction {
private static final Logger log = Logger.getLogger("Transaction");
private final TransactionManagerImpl txManager;
private final Xid xid;
private final CurrentTimeMsProvider timeProvider;
private final long timeout;
private final List<Synchronization> syncList = new ArrayList<Synchronization>(5);
private final List<Synchronization> interposedSyncList = new ArrayList<Synchronization>(3);
private final LinkedList<TransactionBranch> resourceManagers = new LinkedList<TransactionBranch>();
private final IdentityHashMap<XAResource, TransactionBranch> activeXaResources = new IdentityHashMap<XAResource, TransactionBranch>(3);
private final IdentityHashMap<XAResource, TransactionBranch> suspendedXaResources = new IdentityHashMap<XAResource, TransactionBranch>(3);
private int status = Status.STATUS_NO_TRANSACTION;
private Throwable markRollbackCause;
private Object logMark;
private final Map<Object, Object> resources = new HashMap<Object, Object>();
TransactionImpl(TransactionManagerImpl txManager, long transactionTimeoutMilliseconds) throws SystemException {
this(txManager.getXidFactory().createXid(), txManager, transactionTimeoutMilliseconds);
}
TransactionImpl(TransactionManagerImpl txManager, long transactionTimeoutMilliseconds, CurrentTimeMsProvider timeProvider) throws SystemException {
this(txManager.getXidFactory().createXid(), txManager, transactionTimeoutMilliseconds, timeProvider);
}
TransactionImpl(Xid xid, TransactionManagerImpl txManager, long transactionTimeoutMilliseconds) throws SystemException {
this(xid, txManager, transactionTimeoutMilliseconds, null);
}
TransactionImpl(Xid xid, TransactionManagerImpl txManager, long transactionTimeoutMilliseconds, CurrentTimeMsProvider timeProvider) throws SystemException {
this.txManager = txManager;
this.xid = xid;
this.timeProvider = timeProvider == null ? SystemCurrentTime.INSTANCE : timeProvider;
this.timeout = transactionTimeoutMilliseconds + this.timeProvider.now();
try {
txManager.getTransactionLog().begin(xid);
} catch (LogException e) {
markRollbackCause(e);
status = Status.STATUS_MARKED_ROLLBACK;
SystemException ex = new SystemException("Error logging begin; transaction marked for roll back)");
ex.initCause(e);
throw ex;
}
status = Status.STATUS_ACTIVE;
}
//reconstruct a tx for an external tx found in recovery
public TransactionImpl(Xid xid, TransactionManagerImpl txManager) {
this.txManager = txManager;
this.xid = xid;
status = Status.STATUS_PREPARED;
timeProvider = SystemCurrentTime.INSTANCE;
//TODO is this a good idea?
this.timeout = Long.MAX_VALUE;
}
public synchronized int getStatus() {
return status;
}
public Object getResource(Object key) {
return resources.get(key);
}
public boolean getRollbackOnly() {
return status == Status.STATUS_MARKED_ROLLBACK;
}
public Object getTransactionKey() {
return xid;
}
public int getTransactionStatus() {
return status;
}
public void putResource(Object key, Object value) {
if (key == null) {
throw new NullPointerException("You must supply a non-null key for putResource");
}
resources.put(key, value);
}
public void registerInterposedSynchronization(Synchronization synchronization) {
interposedSyncList.add(synchronization);
}
public synchronized void setRollbackOnly() throws IllegalStateException {
setRollbackOnly(new SetRollbackOnlyException());
}
public synchronized void setRollbackOnly(Throwable reason) {
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_PREPARING:
status = Status.STATUS_MARKED_ROLLBACK;
markRollbackCause(reason);
break;
case Status.STATUS_MARKED_ROLLBACK:
case Status.STATUS_ROLLING_BACK:
// nothing to do
break;
default:
throw new IllegalStateException("Cannot set rollback only, status is " + getStateString(status));
}
}
public synchronized void registerSynchronization(Synchronization synch) throws IllegalStateException, RollbackException, SystemException {
if (synch == null) {
throw new IllegalArgumentException("Synchronization is null");
}
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_PREPARING:
break;
case Status.STATUS_MARKED_ROLLBACK:
throw new RollbackException("Transaction is marked for rollback");
default:
throw new IllegalStateException("Status is " + getStateString(status));
}
syncList.add(synch);
}
public synchronized boolean enlistResource(XAResource xaRes) throws IllegalStateException, RollbackException, SystemException {
if (xaRes == null) {
throw new IllegalArgumentException("XAResource is null");
}
switch (status) {
case Status.STATUS_ACTIVE:
break;
case Status.STATUS_MARKED_ROLLBACK:
break;
default:
throw new IllegalStateException("Status is " + getStateString(status));
}
if (activeXaResources.containsKey(xaRes)) {
throw new IllegalStateException("xaresource: " + xaRes + " is already enlisted!");
}
try {
TransactionBranch manager = suspendedXaResources.remove(xaRes);
if (manager != null) {
//we know about this one, it was suspended
xaRes.start(manager.getBranchId(), XAResource.TMRESUME);
activeXaResources.put(xaRes, manager);
return true;
}
//it is not suspended.
for (Iterator i = resourceManagers.iterator(); i.hasNext();) {
manager = (TransactionBranch) i.next();
boolean sameRM;
//if the xares is already known, we must be resuming after a suspend.
if (xaRes == manager.getCommitter()) {
throw new IllegalStateException("xaRes " + xaRes + " is a committer but is not active or suspended");
}
//Otherwise, see if this is a new xares for the same resource manager
try {
sameRM = xaRes.isSameRM(manager.getCommitter());
} catch (XAException e) {
log.log(Level.WARNING, "Unexpected error checking for same RM", e);
continue;
}
if (sameRM) {
xaRes.start(manager.getBranchId(), XAResource.TMJOIN);
activeXaResources.put(xaRes, manager);
return true;
}
}
//we know nothing about this XAResource or resource manager
Xid branchId = txManager.getXidFactory().createBranch(xid, resourceManagers.size() + 1);
xaRes.start(branchId, XAResource.TMNOFLAGS);
//Set the xaresource timeout in seconds to match the time left in this tx.
xaRes.setTransactionTimeout((int)(timeout - timeProvider.now())/1000);
activeXaResources.put(xaRes, addBranchXid(xaRes, branchId));
return true;
} catch (XAException e) {
log.log(Level.WARNING, "Unable to enlist XAResource " + xaRes + ", errorCode: " + e.errorCode, e);
// mark status as rollback only because enlist resource failed
setRollbackOnly(e);
return false;
}
}
public synchronized boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException {
if (!(flag == XAResource.TMFAIL || flag == XAResource.TMSUCCESS || flag == XAResource.TMSUSPEND)) {
throw new IllegalStateException("invalid flag for delistResource: " + flag);
}
if (xaRes == null) {
throw new IllegalArgumentException("XAResource is null");
}
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_MARKED_ROLLBACK:
break;
default:
throw new IllegalStateException("Status is " + getStateString(status));
}
TransactionBranch manager = activeXaResources.remove(xaRes);
if (manager == null) {
if (flag == XAResource.TMSUSPEND) {
throw new IllegalStateException("trying to suspend an inactive xaresource: " + xaRes);
}
//not active, and we are not trying to suspend. We must be ending tx.
manager = suspendedXaResources.remove(xaRes);
if (manager == null) {
throw new IllegalStateException("Resource not known to transaction: " + xaRes);
}
}
try {
xaRes.end(manager.getBranchId(), flag);
if (flag == XAResource.TMSUSPEND) {
suspendedXaResources.put(xaRes, manager);
}
return true;
} catch (XAException e) {
log.log(Level.WARNING, "Unable to delist XAResource " + xaRes + ", error code: " + e.errorCode, e);
return false;
}
}
//Transaction method, does 2pc
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
beforePrepare();
try {
if (timeProvider.now() > timeout) {
markRollbackCause(new Exception("Transaction has timed out"));
status = Status.STATUS_MARKED_ROLLBACK;
}
if (status == Status.STATUS_MARKED_ROLLBACK) {
rollbackResources(resourceManagers, false);
RollbackException rollbackException = new RollbackException("Unable to commit: transaction marked for rollback");
if (markRollbackCause != null) {
rollbackException.initCause(markRollbackCause);
}
throw rollbackException;
}
synchronized (this) {
if (status == Status.STATUS_ACTIVE) {
if (this.resourceManagers.size() == 0) {
// nothing to commit
status = Status.STATUS_COMMITTED;
} else if (this.resourceManagers.size() == 1) {
// one-phase commit decision
status = Status.STATUS_COMMITTING;
} else {
// start prepare part of two-phase
status = Status.STATUS_PREPARING;
}
}
// resourceManagers is now immutable
}
// no-phase
if (resourceManagers.size() == 0) {
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
return;
}
// one-phase
if (resourceManagers.size() == 1) {
TransactionBranch manager = resourceManagers.getFirst();
commitResource(manager);
return;
}
boolean willCommit = false;
try {
// two-phase
willCommit = internalPrepare();
} catch (SystemException e) {
rollbackResources(resourceManagers, false);
throw e;
}
// notify the RMs
if (willCommit) {
//Re-check whether there are still left resourceMangers, as we might remove those Read-Only Resource in the voting process
if (resourceManagers.size() == 0) {
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
return;
}
commitResources(resourceManagers);
} else {
// set everRollback to true here because the rollback here is caused by
// XAException during the above internalPrepare
rollbackResources(resourceManagers, true);
throw new RollbackException("transaction rolled back due to problems in prepare");
}
} finally {
afterCompletion();
synchronized (this) {
status = Status.STATUS_NO_TRANSACTION;
}
}
}
//Used from XATerminator for first phase in a remotely controlled tx.
int prepare() throws SystemException, RollbackException {
beforePrepare();
int result = XAResource.XA_RDONLY;
try {
LinkedList rms;
synchronized (this) {
if (status == Status.STATUS_ACTIVE) {
if (resourceManagers.size() == 0) {
// nothing to commit
status = Status.STATUS_COMMITTED;
return result;
} else {
// start prepare part of two-phase
status = Status.STATUS_PREPARING;
}
}
// resourceManagers is now immutable
rms = resourceManagers;
}
boolean willCommit = internalPrepare();
// notify the RMs
if (willCommit) {
if (!rms.isEmpty()) {
result = XAResource.XA_OK;
}
} else {
try {
rollbackResources(rms, false);
} catch (HeuristicMixedException e) {
throw (SystemException)new SystemException("Unable to commit and heuristic exception during rollback").initCause(e);
}
throw new RollbackException("Unable to commit");
}
} finally {
if (result == XAResource.XA_RDONLY) {
afterCompletion();
synchronized (this) {
status = Status.STATUS_NO_TRANSACTION;
}
}
}
return result;
}
//used from XATerminator for commit phase of non-readonly remotely controlled tx.
void preparedCommit() throws HeuristicRollbackException, HeuristicMixedException, SystemException {
try {
commitResources(resourceManagers);
} finally {
afterCompletion();
synchronized (this) {
status = Status.STATUS_NO_TRANSACTION;
}
}
}
//helper method used by Transaction.commit and XATerminator prepare.
private void beforePrepare() {
synchronized (this) {
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_MARKED_ROLLBACK:
break;
default:
throw new IllegalStateException("Status is " + getStateString(status));
}
}
beforeCompletion();
endResources();
}
//helper method used by Transaction.commit and XATerminator prepare.
private boolean internalPrepare() throws SystemException {
for (Iterator rms = resourceManagers.iterator(); rms.hasNext();) {
synchronized (this) {
if (status != Status.STATUS_PREPARING) {
// we were marked for rollback
break;
}
}
TransactionBranch manager = (TransactionBranch) rms.next();
try {
int vote = manager.getCommitter().prepare(manager.getBranchId());
if (vote == XAResource.XA_RDONLY) {
// we don't need to consider this RM any more
rms.remove();
}
} catch (XAException e) {
if (e.errorCode == XAException.XAER_RMERR
|| e.errorCode == XAException.XAER_PROTO
|| e.errorCode == XAException.XAER_INVAL) {
throw (SystemException) new SystemException("Error during prepare; transaction was rolled back").initCause(e);
}
synchronized (this) {
markRollbackCause(e);
status = Status.STATUS_MARKED_ROLLBACK;
/* Per JTA spec, If the resource manager wants to roll back the transaction,
it should do so by throwing an appropriate XAException in the prepare method.
Also per OTS spec:
The resource can return VoteRollback under any circumstances, including not having
any knowledge about the transaction (which might happen after a crash). If this
response is returned, the transaction must be rolled back. Furthermore, the Transaction
Service is not required to perform any additional operations on this resource.*/
//rms.remove();
break;
}
}
}
// decision time...
boolean willCommit;
synchronized (this) {
willCommit = (status != Status.STATUS_MARKED_ROLLBACK);
if (willCommit) {
status = Status.STATUS_PREPARED;
}
}
// log our decision
if (willCommit && !resourceManagers.isEmpty()) {
try {
logMark = txManager.getTransactionLog().prepare(xid, resourceManagers);
} catch (LogException e) {
try {
rollbackResources(resourceManagers, false);
} catch (Exception se) {
log.log(Level.SEVERE, "Unable to rollback after failure to log prepare", se.getCause());
}
throw (SystemException) new SystemException("Error logging prepare; transaction was rolled back)").initCause(e);
}
}
return willCommit;
}
public void rollback() throws IllegalStateException, SystemException {
List rms;
synchronized (this) {
switch (status) {
case Status.STATUS_ACTIVE:
status = Status.STATUS_MARKED_ROLLBACK;
break;
case Status.STATUS_MARKED_ROLLBACK:
break;
default:
throw new IllegalStateException("Status is " + getStateString(status));
}
rms = resourceManagers;
}
endResources();
try {
try {
rollbackResources(rms, false);
} catch (HeuristicMixedException e) {
throw (SystemException)new SystemException("Unable to roll back due to heuristics").initCause(e);
}
} finally {
afterCompletion();
synchronized (this) {
status = Status.STATUS_NO_TRANSACTION;
}
}
}
private void beforeCompletion() {
beforeCompletion(syncList);
beforeCompletion(interposedSyncList);
}
private void beforeCompletion(List syncs) {
int i = 0;
while (true) {
Synchronization synch;
synchronized (this) {
if (i == syncs.size()) {
return;
} else {
synch = (Synchronization) syncs.get(i++);
}
}
try {
synch.beforeCompletion();
} catch (Exception e) {
log.log(Level.WARNING,"Unexpected exception from beforeCompletion; transaction will roll back", e);
synchronized (this) {
markRollbackCause(e);
status = Status.STATUS_MARKED_ROLLBACK;
}
}
}
}
private void markRollbackCause(Throwable e) {
if (markRollbackCause == null) {
markRollbackCause = e;
} else if (markRollbackCause instanceof SetRollbackOnlyException) {
Throwable cause = markRollbackCause.getCause();
if (cause == null) {
markRollbackCause.initCause(e);
}
}
}
private void afterCompletion() {
// this does not synchronize because nothing can modify our state at this time
afterCompletion(interposedSyncList);
afterCompletion(syncList);
}
private void afterCompletion(List syncs) {
for (Iterator i = syncs.iterator(); i.hasNext();) {
Synchronization synch = (Synchronization) i.next();
try {
synch.afterCompletion(status);
} catch (Exception e) {
log.log(Level.WARNING,"Unexpected exception from afterCompletion; continuing", e);
}
}
}
private void endResources() {
endResources(activeXaResources);
endResources(suspendedXaResources);
}
private void endResources(IdentityHashMap<XAResource, TransactionBranch> resourceMap) {
while (true) {
XAResource xaRes;
TransactionBranch manager;
int flags;
synchronized (this) {
Set entrySet = resourceMap.entrySet();
if (entrySet.isEmpty()) {
return;
}
Map.Entry entry = (Map.Entry) entrySet.iterator().next();
xaRes = (XAResource) entry.getKey();
manager = (TransactionBranch) entry.getValue();
flags = (status == Status.STATUS_MARKED_ROLLBACK) ? XAResource.TMFAIL : XAResource.TMSUCCESS;
resourceMap.remove(xaRes);
}
try {
xaRes.end(manager.getBranchId(), flags);
} catch (XAException e) {
log.log(Level.WARNING,"Error ending association for XAResource " + xaRes + "; transaction will roll back. XA error code: " + e.errorCode, e);
synchronized (this) {
markRollbackCause(e);
status = Status.STATUS_MARKED_ROLLBACK;
}
}
}
}
private void rollbackResources(List<TransactionBranch> rms, boolean everRb) throws HeuristicMixedException, SystemException {
RollbackTask rollbackTask = new RollbackTask(xid, rms, logMark, txManager);
synchronized (this) {
status = Status.STATUS_ROLLING_BACK;
}
rollbackTask.run();
synchronized (this) {
status = rollbackTask.getStatus();
}
XAException cause = rollbackTask.getCause();
boolean everRolledback = everRb || rollbackTask.isEverRolledBack();
if (cause != null) {
if (cause.errorCode == XAException.XA_HEURCOM && everRolledback) {
throw (HeuristicMixedException) new HeuristicMixedException("HeuristicMixed error during commit/rolling back").initCause(cause);
} else if (cause.errorCode == XAException.XA_HEURMIX) {
throw (HeuristicMixedException) new HeuristicMixedException("HeuristicMixed error during commit/rolling back").initCause(cause);
} else {
throw (SystemException) new SystemException("System Error during commit/rolling back").initCause(cause);
}
}
}
private void commitResource(TransactionBranch manager) throws RollbackException, HeuristicRollbackException, HeuristicMixedException, SystemException{
XAException cause = null;
try {
try {
manager.getCommitter().commit(manager.getBranchId(), true);
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
return;
} catch (XAException e) {
synchronized (this) {
status = Status.STATUS_ROLLEDBACK;
}
if (e.errorCode == XAException.XA_HEURRB) {
cause = e;
manager.getCommitter().forget(manager.getBranchId());
//throw (HeuristicRollbackException) new HeuristicRollbackException("Error during one-phase commit").initCause(e);
} else if (e.errorCode == XAException.XA_HEURMIX) {
cause = e;
manager.getCommitter().forget(manager.getBranchId());
throw (HeuristicMixedException) new HeuristicMixedException("Error during one-phase commit").initCause(e);
} else if (e.errorCode == XAException.XA_HEURCOM) {
// let's not throw an exception as the transaction has been committed
log.info("Transaction has been heuristically committed");
manager.getCommitter().forget(manager.getBranchId());
} else if (e.errorCode == XAException.XA_RBROLLBACK
|| e.errorCode == XAException.XAER_RMERR
|| e.errorCode == XAException.XAER_NOTA) {
// Per XA spec, XAException.XAER_RMERR from commit means An error occurred in
// committing the work performed on behalf of the transaction branch
// and the branch's work has been rolled back.
// XAException.XAER_NOTA: assume the DB took a unilateral rollback decision and forgot the transaction
log.info("Transaction has been rolled back");
cause = e;
// throw (RollbackException) new RollbackException("Error during one-phase commit").initCause(e);
} else {
cause = e;
//throw (SystemException) new SystemException("Error during one-phase commit").initCause(e);
}
}
} catch (XAException e) {
if (e.errorCode == XAException.XAER_NOTA) {
// NOTA in response to forget, means the resource already forgot the transaction
// ignore
} else {
throw (SystemException) new SystemException("Error during one phase commit").initCause(e);
}
}
if (cause != null) {
if (cause.errorCode == XAException.XA_HEURRB) {
throw (HeuristicRollbackException) new HeuristicRollbackException("Error during two phase commit").initCause(cause);
} else if (cause.errorCode == XAException.XA_HEURMIX) {
throw (HeuristicMixedException) new HeuristicMixedException("Error during two phase commit").initCause(cause);
} else if (cause.errorCode == XAException.XA_RBROLLBACK
|| cause.errorCode == XAException.XAER_RMERR
|| cause.errorCode == XAException.XAER_NOTA) {
throw (RollbackException) new RollbackException("Error during two phase commit").initCause(cause);
} else {
throw (SystemException) new SystemException("Error during two phase commit").initCause(cause);
}
}
}
private void commitResources(List<TransactionBranch> rms) throws HeuristicRollbackException, HeuristicMixedException, SystemException {
CommitTask commitTask = new CommitTask(xid, rms, logMark, txManager);
synchronized (this) {
status = Status.STATUS_COMMITTING;
}
commitTask.run();
synchronized (this) {
status = commitTask.getStatus();
}
XAException cause = commitTask.getCause();
boolean evercommit = commitTask.isEvercommit();
if (cause != null) {
if (cause.errorCode == XAException.XA_HEURRB && !evercommit) {
throw (HeuristicRollbackException) new HeuristicRollbackException("Error during two phase commit").initCause(cause);
} else if (cause.errorCode == XAException.XA_HEURRB && evercommit) {
throw (HeuristicMixedException) new HeuristicMixedException("Error during two phase commit").initCause(cause);
} else if (cause.errorCode == XAException.XA_HEURMIX) {
throw (HeuristicMixedException) new HeuristicMixedException("Error during two phase commit").initCause(cause);
} else {
throw (SystemException) new SystemException("Error during two phase commit").initCause(cause);
}
}
}
private static String getStateString(int status) {
switch (status) {
case Status.STATUS_ACTIVE:
return "STATUS_ACTIVE";
case Status.STATUS_PREPARING:
return "STATUS_PREPARING";
case Status.STATUS_PREPARED:
return "STATUS_PREPARED";
case Status.STATUS_MARKED_ROLLBACK:
return "STATUS_MARKED_ROLLBACK";
case Status.STATUS_ROLLING_BACK:
return "STATUS_ROLLING_BACK";
case Status.STATUS_COMMITTING:
return "STATUS_COMMITTING";
case Status.STATUS_COMMITTED:
return "STATUS_COMMITTED";
case Status.STATUS_ROLLEDBACK:
return "STATUS_ROLLEDBACK";
case Status.STATUS_NO_TRANSACTION:
return "STATUS_NO_TRANSACTION";
case Status.STATUS_UNKNOWN:
return "STATUS_UNKNOWN";
default:
throw new AssertionError();
}
}
public boolean equals(Object obj) {
if (obj instanceof TransactionImpl) {
TransactionImpl other = (TransactionImpl) obj;
return xid.equals(other.xid);
} else {
return false;
}
}
//when used from recovery, do not add manager to active or suspended resource maps.
// The xaresources have already been ended with TMSUCCESS.
public TransactionBranch addBranchXid(XAResource xaRes, Xid branchId) {
TransactionBranch manager = new TransactionBranch(xaRes, branchId);
resourceManagers.add(manager);
return manager;
}
static class TransactionBranch implements TransactionBranchInfo {
private final XAResource committer;
private final Xid branchId;
public TransactionBranch(XAResource xaRes, Xid branchId) {
committer = xaRes;
this.branchId = branchId;
}
public XAResource getCommitter() {
return committer;
}
public Xid getBranchId() {
return branchId;
}
public String getResourceName() {
if (committer instanceof NamedXAResource) {
return ((NamedXAResource) committer).getName();
} else {
// if it isn't a named resource should we really stop all processing here!
// Maybe this would be better to handle else where and do we really want to prevent all processing of transactions?
log.log(Level.SEVERE, "Please correct the integration and supply a NamedXAResource", new IllegalStateException("Cannot log transactions as " + committer + " is not a NamedXAResource."));
return committer.toString();
}
}
public Xid getBranchXid() {
return branchId;
}
}
static class ReturnableTransactionBranch extends TransactionBranch {
private final NamedXAResourceFactory namedXAResourceFactory;
ReturnableTransactionBranch(Xid branchId, NamedXAResourceFactory namedXAResourceFactory) throws SystemException {
super(namedXAResourceFactory.getNamedXAResource(), branchId);
this.namedXAResourceFactory = namedXAResourceFactory;
}
public void returnXAResource() {
namedXAResourceFactory.returnNamedXAResource((NamedXAResource) getCommitter());
}
}
}
| 6,487 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/CommitTask.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.geronimo.transaction.manager;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import org.apache.geronimo.transaction.manager.TransactionImpl.ReturnableTransactionBranch;
import org.apache.geronimo.transaction.manager.TransactionImpl.TransactionBranch;
/**
* @version $Rev$ $Date$
*/
public class CommitTask implements Runnable {
private static final Logger log = Logger.getLogger(CommitTask.class.getName());
private final Xid xid;
private final List<TransactionBranch> rms;
private final Object logMark;
private final TransactionManagerImpl txManager;
private int count = 0;
private int status;
private XAException cause;
private boolean evercommit;
public CommitTask(Xid xid, List<TransactionBranch> rms, Object logMark, TransactionManagerImpl txManager) {
this.xid = xid;
this.rms = rms;
this.logMark = logMark;
this.txManager = txManager;
}
@Override
public void run() {
synchronized (this) {
status = Status.STATUS_COMMITTING;
}
for (int index = 0; index < rms.size(); ) {
TransactionBranch manager = rms.get(index);
try {
try {
manager.getCommitter().commit(manager.getBranchId(), false);
remove(index);
evercommit = true;
} catch (XAException e) {
log.log(Level.SEVERE, "Unexpected exception committing " + manager.getCommitter() + "; continuing to commit other RMs", e);
if (e.errorCode == XAException.XA_HEURRB) {
remove(index);
log.info("Transaction has been heuristically rolled back");
cause = e;
manager.getCommitter().forget(manager.getBranchId());
} else if (e.errorCode == XAException.XA_HEURMIX) {
remove(index);
log.info("Transaction has been heuristically committed and rolled back");
cause = e;
evercommit = true;
manager.getCommitter().forget(manager.getBranchId());
} else if (e.errorCode == XAException.XA_HEURCOM) {
remove(index);
// let's not throw an exception as the transaction has been committed
log.info("Transaction has been heuristically committed");
evercommit = true;
manager.getCommitter().forget(manager.getBranchId());
} else if (e.errorCode == XAException.XA_RETRY) {
// do nothing, retry later
index++;
} else if (e.errorCode == XAException.XAER_RMFAIL) {
//refresh the xa resource from the NamedXAResourceFactory
if (manager.getCommitter() instanceof NamedXAResource) {
String xaResourceName = manager.getResourceName();
NamedXAResourceFactory namedXAResourceFactory = txManager.getNamedXAResourceFactory(xaResourceName);
if (namedXAResourceFactory != null) {
try {
TransactionBranch newManager = new ReturnableTransactionBranch(manager.getBranchXid(), namedXAResourceFactory);
remove(index);
rms.add(index, newManager);
//loop will try this one again immediately.
} catch (SystemException e1) {
//try again later
index++;
}
} else {
//else hope NamedXAResourceFactory reappears soon.
index++;
}
} else {
//no hope
remove(index);
cause = e;
}
} else {
//at least RMERR, which we can do nothing about
//nothing we can do about it.... keep trying
remove(index);
cause = e;
}
}
} catch (XAException e) {
if (e.errorCode == XAException.XAER_NOTA) {
// NOTA in response to forget, means the resource already forgot the transaction
// ignore
} else {
cause = e;
}
}
}
//if all resources were read only, we didn't write a prepare record.
if (rms.isEmpty()) {
try {
txManager.getTransactionLog().commit(xid, logMark);
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
} catch (LogException e) {
log.log(Level.SEVERE, "Unexpected exception logging commit completion for xid " + xid, e);
cause = (XAException) new XAException("Unexpected error logging commit completion for xid " + xid).initCause(e);
}
} else {
synchronized (this) {
status = Status.STATUS_UNKNOWN;
}
txManager.getRetryScheduler().retry(this, count++);
}
}
private void remove(int index) {
TransactionBranch manager = rms.remove(index);
if (manager instanceof ReturnableTransactionBranch) {
((ReturnableTransactionBranch)manager).returnXAResource();
}
}
public XAException getCause() {
return cause;
}
public boolean isEvercommit() {
return evercommit;
}
public int getStatus() {
return status;
}
}
| 6,488 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RetryScheduler.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.geronimo.transaction.manager;
import java.util.TimerTask;
/**
* @version $Rev$ $Date$
*/
public interface RetryScheduler {
void retry(Runnable task, int count);
}
| 6,489 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/Closeable.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.geronimo.transaction.manager;
/**
* @version $Rev$ $Date$
*/
public interface Closeable {
void close();
}
| 6,490 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverableTransactionManager.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.geronimo.transaction.manager;
import jakarta.transaction.TransactionManager;
/**
* @version $Rev$ $Date$
*/
public interface RecoverableTransactionManager extends TransactionManager {
void recoveryError(Exception e);
void registerNamedXAResourceFactory(NamedXAResourceFactory namedXAResourceFactory);
void unregisterNamedXAResourceFactory(String namedXAResourceFactoryName);
}
| 6,491 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/ImportedTransactionActiveException.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.geronimo.transaction.manager;
import javax.transaction.xa.Xid;
/**
*/
public class ImportedTransactionActiveException extends Exception {
private final Xid xid;
public ImportedTransactionActiveException(Xid xid) {
this.xid = xid;
}
public Xid getXid() {
return xid;
}
}
| 6,492 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/ExponentialtIntervalRetryScheduler.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.geronimo.transaction.manager;
import java.util.Timer;
import java.util.TimerTask;
/**
* @version $Rev$ $Date$
*/
public class ExponentialtIntervalRetryScheduler implements RetryScheduler{
private final Timer timer = new Timer("RetryTimer", true);
private final int base = 2;
public void retry(Runnable task, int count) {
long interval = Math.round(Math.pow(base, count)) * 1000;
timer.schedule(new TaskWrapper(task), interval);
}
private static class TaskWrapper extends TimerTask {
private final Runnable delegate;
private TaskWrapper(Runnable delegate) {
this.delegate = delegate;
}
@Override
public void run() {
delegate.run();
}
}
}
| 6,493 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/WrapperNamedXAResource.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.geronimo.transaction.manager;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class WrapperNamedXAResource implements NamedXAResource {
protected static Logger log = Logger.getLogger(WrapperNamedXAResource.class.getName());
private final XAResource xaResource;
private final String name;
public WrapperNamedXAResource(XAResource xaResource, String name) {
if (xaResource == null) throw new NullPointerException("No XAResource supplied. XA support may not be configured properly");
if (name == null) throw new NullPointerException("No name supplied. Resource adapter not properly configured");
this.xaResource = xaResource;
this.name = name;
}
public String getName() {
return name;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Commit called on XAResource " + getName() + "\n Xid: " + xid + "\n onePhase:" + onePhase);
}
xaResource.commit(xid, onePhase);
}
public void end(Xid xid, int flags) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"End called on XAResource " + getName() + "\n Xid: " + xid + "\n flags:" + decodeFlags(flags));
}
xaResource.end(xid, flags);
}
public void forget(Xid xid) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Forget called on XAResource " + getName() + "\n Xid: " + xid);
}
xaResource.forget(xid);
}
public int getTransactionTimeout() throws XAException {
return xaResource.getTransactionTimeout();
}
public boolean isSameRM(XAResource other) throws XAException {
if (other instanceof WrapperNamedXAResource) {
return xaResource.isSameRM(((WrapperNamedXAResource)other).xaResource);
}
return false;
}
public int prepare(Xid xid) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Prepare called on XAResource " + getName() + "\n Xid: " + xid);
}
return xaResource.prepare(xid);
}
public Xid[] recover(int flag) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Recover called on XAResource " + getName() + "\n flags: " + decodeFlags(flag));
}
return xaResource.recover(flag);
}
public void rollback(Xid xid) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Rollback called on XAResource " + getName() + "\n Xid: " + xid);
}
xaResource.rollback(xid);
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return xaResource.setTransactionTimeout(seconds);
}
public void start(Xid xid, int flags) throws XAException {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,"Start called on XAResource " + getName() + "\n Xid: " + xid + "\n flags:" + decodeFlags(flags));
}
xaResource.start(xid, flags);
}
private String decodeFlags(int flags) {
if (flags == 0) {
return " TMNOFLAGS";
}
StringBuilder b = new StringBuilder();
decodeFlag(flags, b, TMENDRSCAN, " TMENDRSCAN");
decodeFlag(flags, b, TMFAIL, " TMFAIL");
decodeFlag(flags, b, TMJOIN, " TMJOIN");
decodeFlag(flags, b, TMONEPHASE, " TMONEPHASE");
decodeFlag(flags, b, TMRESUME, " TMRESUME");
decodeFlag(flags, b, TMSTARTRSCAN, " TMSTARTRSCAN");
decodeFlag(flags, b, TMSUCCESS, " TMSUCCESS");
decodeFlag(flags, b, TMSUSPEND, " TMSUSPEND");
if (flags != 0) {
b.append(" remaining: ").append(flags);
}
return b.toString();
}
private void decodeFlag(int flags, StringBuilder b, int flag, String flagName) {
if ((flags & flag) == flag) {
b.append(flagName);
flags = flags ^ flag;
}
}
}
| 6,494 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/CurrentTimeMsProvider.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.geronimo.transaction.manager;
/**
* An abstraction of a time provider with millisecond resolution.
*/
@FunctionalInterface
public interface CurrentTimeMsProvider {
/**
* Returns the current time, in milliseconds.
*
* @return the current time, in milliseconds
*/
long now();
}
| 6,495 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverTask.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.geronimo.transaction.manager;
import java.util.TimerTask;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
/**
* @version $Rev$ $Date$
*/
public class RecoverTask implements Runnable {
private final RetryScheduler retryScheduler;
private final NamedXAResourceFactory namedXAResourceFactory;
private final Recovery recovery;
private final RecoverableTransactionManager recoverableTransactionManager;
private int count = 0;
public RecoverTask(RetryScheduler retryScheduler, NamedXAResourceFactory namedXAResourceFactory, Recovery recovery, RecoverableTransactionManager recoverableTransactionManager) {
this.retryScheduler = retryScheduler;
this.namedXAResourceFactory = namedXAResourceFactory;
this.recovery = recovery;
this.recoverableTransactionManager = recoverableTransactionManager;
}
// @Override
public void run() {
try {
NamedXAResource namedXAResource = namedXAResourceFactory.getNamedXAResource();
if (namedXAResource != null) {
try {
recovery.recoverResourceManager(namedXAResource);
} finally {
namedXAResourceFactory.returnNamedXAResource(namedXAResource);
}
}
return;
} catch (XAException e) {
recoverableTransactionManager.recoveryError(e);
} catch (SystemException e) {
recoverableTransactionManager.recoveryError(e);
}
retryScheduler.retry(this, count++);
}
}
| 6,496 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/XidFactory.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.geronimo.transaction.manager;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface XidFactory {
Xid createXid();
Xid createBranch(Xid globalId, int branch);
boolean matchesGlobalId(byte[] globalTransactionId);
boolean matchesBranchId(byte[] branchQualifier);
Xid recover(int formatId, byte[] globalTransactionid, byte[] branchQualifier);
}
| 6,497 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/TransactionBranchInfo.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.geronimo.transaction.manager;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface TransactionBranchInfo {
String getResourceName();
Xid getBranchXid();
}
| 6,498 |
0 | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction | Create_ds/geronimo-txmanager/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/XAWork.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.geronimo.transaction.manager;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAException;
import jakarta.transaction.SystemException;
import jakarta.transaction.InvalidTransactionException;
import org.apache.geronimo.transaction.manager.ImportedTransactionActiveException;
/**
* primarily an interface between the WorkManager/ExecutionContext and the tm.
*
* @version $Rev$ $Date$
*
* */
public interface XAWork {
void begin(Xid xid, long txTimeout) throws XAException, InvalidTransactionException, SystemException, ImportedTransactionActiveException;
void end(Xid xid) throws XAException, SystemException;
}
| 6,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.