Package org.codehaus.activemq.ra

Source Code of org.codehaus.activemq.ra.ActiveMQResourceAdapter

/**
*
* Copyright 2004 Hiram Chirino
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**/
package org.codehaus.activemq.ra;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.ActiveMQRAConnectionFactory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.XAConnection;
import javax.jms.XASession;
import javax.resource.NotSupportedException;
import javax.resource.ResourceException;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterInternalException;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.transaction.xa.XAResource;
import java.util.HashMap;


/**
* Knows how to connect to one ActiveMQ server.  It can then activate endpoints and deliver
* messages to those enpoints using the connection configure in the resource adapter.
* <p/>
* Must override equals and hashCode (JCA spec 16.4)
*
* @version $Revision: 1.9 $
*/
public class ActiveMQResourceAdapter implements ResourceAdapter {
    private static final Log log = LogFactory.getLog(ActiveMQResourceAdapter.class);

    private static final String ASF_ENDPOINT_WORKER_TYPE = "asf";
    private static final String POLLING_ENDPOINT_WORKER_TYPE = "polling";

    private BootstrapContext bootstrapContext;
    private HashMap endpointWorkers = new HashMap();
    final private ActiveMQConnectionRequestInfo info = new ActiveMQConnectionRequestInfo();
    private String endpointWorkerType = ASF_ENDPOINT_WORKER_TYPE;
    private Connection physicalConnection;
    private ConnectionFactory connectionFactory;

    public ActiveMQResourceAdapter() {
        this(null);
    }

    public ActiveMQResourceAdapter(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    /**
     * @see javax.resource.spi.ResourceAdapter#start(javax.resource.spi.BootstrapContext)
     */
    public void start(BootstrapContext bootstrapContext)
            throws ResourceAdapterInternalException {
        this.bootstrapContext = bootstrapContext;
    }

    public Connection makeConnection(boolean transacted) throws JMSException {
        return makeConnection(connectionFactory, info, transacted);
    }

    /**
     * A helper method to create a new JMS connection from the connection request info.
     * If no specific connection factory instance is passed in then the default ActiveMQ
     * implementation is used
     *
     * @param connectionFactory an optional connection factory to use or null to use the default
     * @param info              the connection request info
     * @param transacted
     * @return a newly created connection
     * @throws JMSException
     */
    public static Connection makeConnection(ConnectionFactory connectionFactory, ActiveMQConnectionRequestInfo info, boolean transacted) throws JMSException {
        if (connectionFactory == null) {
            if (transacted) {
              connectionFactory = new ActiveMQRAConnectionFactory(info.getServerUrl());
              ((ActiveMQRAConnectionFactory)connectionFactory).setUseAsyncSend(false);
            }
            else {
              connectionFactory = new org.codehaus.activemq.ActiveMQConnectionFactory(info.getServerUrl());
            }
        }
        Connection physicalConnection = connectionFactory.createConnection(info.getUserName(), info.getPassword());
        if (info.getClientid() != null) {
            physicalConnection.setClientID(info.getClientid());
        }
        return physicalConnection;
    }


    /**
     * @return Returns the physicalConnection.
     * @throws ResourceAdapterInternalException
     *
     * @throws JMSException
     */
    public Connection getPhysicalConnection(boolean transacted) throws JMSException {
        if (physicalConnection == null) {
            physicalConnection = makeConnection(connectionFactory, info, transacted);
            physicalConnection.start();
        }
        return physicalConnection;
    }

    /**
     * @see javax.resource.spi.ResourceAdapter#stop()
     */
    public void stop() {
        this.bootstrapContext = null;
        if (physicalConnection != null) {
            try {
                physicalConnection.close();
                physicalConnection = null;
            }
            catch (JMSException e) {
                log.debug("Error occured during ResourceAdapter stop: ", e);
            }
        }
    }

    /**
     * @return
     */
    public BootstrapContext getBootstrapContext() {
        return bootstrapContext;
    }

    /**
     * @see javax.resource.spi.ResourceAdapter#endpointActivation(javax.resource.spi.endpoint.MessageEndpointFactory,
            *      javax.resource.spi.ActivationSpec)
     */
    public void endpointActivation(MessageEndpointFactory endpointFactory,
                                   ActivationSpec activationSpec) throws ResourceException {

        //spec section 5.3.3
        if (activationSpec.getResourceAdapter() != this) {
            throw new ResourceException("Activation spec not initialized with this ResourceAdapter instance");
        }

        if (activationSpec.getClass().equals(ActiveMQActivationSpec.class)) {

            ActiveMQEndpointActivationKey key = new ActiveMQEndpointActivationKey(endpointFactory, (ActiveMQActivationSpec) activationSpec);
            // This is weird.. the same endpoint activated twice.. must be a container error.
            if (endpointWorkers.containsKey(key)) {
                throw new IllegalStateException("Endpoint previously activated");
            }

            ActiveMQBaseEndpointWorker worker;
            if (POLLING_ENDPOINT_WORKER_TYPE.equals(getEndpointWorkerType())) {
                worker = new ActiveMQPollingEndpointWorker(this, key);
            }
            else if (ASF_ENDPOINT_WORKER_TYPE.equals(getEndpointWorkerType())) {
                worker = new ActiveMQAsfEndpointWorker(this, key);
            }
            else {
                throw new NotSupportedException("That type of EndpointWorkerType is not supported: " + getEndpointWorkerType());
            }

            endpointWorkers.put(key, worker);
            worker.start();

        }
        else {
            throw new NotSupportedException("That type of ActicationSpec not supported: " + activationSpec.getClass());
        }

    }

    /**
     * @see javax.resource.spi.ResourceAdapter#endpointDeactivation(javax.resource.spi.endpoint.MessageEndpointFactory,
            *      javax.resource.spi.ActivationSpec)
     */
    public void endpointDeactivation(MessageEndpointFactory endpointFactory,
                                     ActivationSpec activationSpec) {

        if (activationSpec.getClass().equals(ActiveMQActivationSpec.class)) {
            ActiveMQEndpointActivationKey key = new ActiveMQEndpointActivationKey(endpointFactory, (ActiveMQActivationSpec) activationSpec);
            ActiveMQBaseEndpointWorker worker = (ActiveMQBaseEndpointWorker) endpointWorkers.get(key);
            if (worker == null) {
                // This is weird.. that endpoint was not activated..  oh well.. this method
                // does not throw exceptions so just return.
                return;
            }
            try {
                worker.stop();
            }
            catch (InterruptedException e) {
                // We interrupted.. we won't throw an exception but will stop waiting for the worker
                // to stop..  we tried our best.  Keep trying to interrupt the thread.
                Thread.currentThread().interrupt();
            }

        }

    }

    /**
     * We only connect to one resource manager per ResourceAdapter instance, so any ActivationSpec
     * will return the same XAResource.
     *
     * @see javax.resource.spi.ResourceAdapter#getXAResources(javax.resource.spi.ActivationSpec[])
     */
    public XAResource[] getXAResources(ActivationSpec[] activationSpecs) throws ResourceException {
        try {
            Connection connection = getPhysicalConnection(true);
            if (connection instanceof XAConnection) {
                XASession session = ((XAConnection) connection).createXASession();
                XAResource xaResource = session.getXAResource();
                return new XAResource[]{xaResource};
            }
            else {
                return new XAResource[]{};
            }
        }
        catch (JMSException e) {
            throw new ResourceException(e);
        }
    }

    /////////////////////////////////////////////////////////////////////////
    //
    // Java Bean getters and setters for this ResourceAdapter class.
    //
    /////////////////////////////////////////////////////////////////////////

    /**
     * @return
     */
    public String getClientid() {
        return info.getClientid();
    }

    /**
     * @return
     */
    public String getPassword() {
        return info.getPassword();
    }

    /**
     * @return
     */
    public String getServerUrl() {
        return info.getServerUrl();
    }

    /**
     * @return
     */
    public String getUserName() {
        return info.getUserName();
    }

    /**
     * @param clientid
     */
    public void setClientid(String clientid) {
        info.setClientid(clientid);
    }

    /**
     * @param password
     */
    public void setPassword(String password) {
        info.setPassword(password);
    }

    /**
     * @param url
     */
    public void setServerUrl(String url) {
        info.setServerUrl(url);
    }

    /**
     * @param userid
     */
    public void setUserName(String userid) {
        info.setUserName(userid);
    }

    /**
     * @return Returns the endpointWorkerType.
     */
    public String getEndpointWorkerType() {
        return endpointWorkerType;
    }

    /**
     * @param endpointWorkerType The endpointWorkerType to set.
     */
    public void setEndpointWorkerType(String endpointWorkerType) {
        this.endpointWorkerType = endpointWorkerType.toLowerCase();
    }

    /**
     * @return Returns the info.
     */
    public ActiveMQConnectionRequestInfo getInfo() {
        return info;
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ActiveMQResourceAdapter)) {
            return false;
        }

        final ActiveMQResourceAdapter activeMQResourceAdapter = (ActiveMQResourceAdapter) o;

        if (!endpointWorkerType.equals(activeMQResourceAdapter.endpointWorkerType)) {
            return false;
        }
        if (!info.equals(activeMQResourceAdapter.info)) {
            return false;
        }

        return true;
    }

    public int hashCode() {
        int result;
        result = info.hashCode();
        result = 29 * result + endpointWorkerType.hashCode();
        return result;
    }
}
TOP

Related Classes of org.codehaus.activemq.ra.ActiveMQResourceAdapter

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.