Package org.codehaus.activemq.sampler

Source Code of org.codehaus.activemq.sampler.Consumer

/**
*
* Copyright 2004 Protique Ltd
*
* 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.sampler;

import org.apache.log.Logger;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Entry;
import org.codehaus.activemq.util.connection.ServerConnectionFactory;
import org.codehaus.activemq.util.IdGenerator;

import javax.jms.*;

import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Consumer extends Sampler implements MessageListener {

    public static int counter;

    private static final Logger log = LoggingManager.getLoggerForClass();

    // Otherwise, the response is scanned for these strings
    private static final String STATUS_PREFIX = JMeterUtils.getPropDefault("tcp.status.prefix", "");
    private static final String STATUS_SUFFIX = JMeterUtils.getPropDefault("tcp.status.suffix", "");

    private static final String STATUS_PROPERTIES = JMeterUtils.getPropDefault("tcp.status.properties", "");
    private static final Properties statusProps = new Properties();

    private int batchCounter = 0;

    static {
        log.info("Protocol Handler name=" + getClassname());
        log.info("Status prefix=" + STATUS_PREFIX);
        log.info("Status suffix=" + STATUS_SUFFIX);
        log.info("Status properties=" + STATUS_PROPERTIES);

        if (STATUS_PROPERTIES.length() > 0) {
            File f = new File(STATUS_PROPERTIES);

            try {
                statusProps.load(new FileInputStream(f));
                log.info("Successfully loaded properties");
            } catch (FileNotFoundException e) {
                log.error("Property file not found");
            } catch (IOException e) {
                log.error("Property file error " + e.toString());
            }
        }
    }

    /**
     * Constructor for ConsumerSampler object.
     */
    public Consumer() {
        log.debug("Created " + this);
        protocolHandler = getProtocol();
        log.debug("Using Protocol Handler: " + protocolHandler.getClass().getName());
    }

    /**
     * Increments the int variable.
     *
     * @param count - variable incremented.
     */
    private synchronized void count(int count) {
        counter += count;
    }

    /**
     * @return the current number of messages sent.
     */
    public static synchronized int resetCount() {
        int answer = counter;
        counter = 0;
        return answer;
    }


    /**
     * Subscribes the subject.
     *
     * @throws JMSException
     */
    protected void subscribe() throws JMSException {
        for (int i = 0; i < getNoConsumer(); i++) {
            String subject = subjects[i % getNoSubject()];
            subscribe(subject);
        }
    }

    /**
     * Subscribes the message.
     *
     * @param subject - subject to be subscribed.
     * @throws JMSException
     */
    protected void subscribe(String subject) throws JMSException {

        Connection connection = ServerConnectionFactory.createConnectionFactory(this.getURL(),
                                                                                this.getMQServer(),
                                                                                this.getTopic(),
                                                                                this.getEmbeddedBroker());
        if (this.getDurable()) {
            IdGenerator idGenerator = new IdGenerator();
            connection.setClientID(idGenerator.generateId());
        }
        //start connection before receiving messages.
        connection.start();

        Session session = ServerConnectionFactory.createSession(connection, this.getTransacted());
        Destination destination = ServerConnectionFactory.createDestination(session,
                                                                            subject,
                                                                            this.getURL(),
                                                                            this.getMQServer(),
                                                                            this.getTopic());
        MessageConsumer consumer = null;

        if (this.getDurable() && this.getTopic()) {
            consumer = session.createDurableSubscriber((Topic) destination, getClass().getName());
        } else {
            consumer = session.createConsumer(destination);
        }

        this.setSession(session);
        consumer.setMessageListener(this);
        addResource(consumer);
    }

    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            Session session;

            // lets force the content to be deserialized
            String text = textMessage.getText();
            count(1);

            if (this.getTransacted()) {
                batchCounter++;
                if (batchCounter == this.getBatchSize()) {
                    batchCounter = 0;
                    session = this.getSession();
                    session.commit();
                }
            }

        } catch (JMSException e) {
            log.error("Unable to force deserialize the content ", e);
        }
    }

    /**
     * Runs and subscribes to messages.
     *
     * @throws JMSException
     */
    public void run() throws JMSException {
        start();
        subscribe();
    }

    /**
     * Retrieves the sample as SampleResult object. There are times that this
     * is ignored.
     *
     * @param e - Entry object.
     * @return Returns the sample result.
     */
    public SampleResult sample(Entry e) {// Entry tends to be ignored ...
        SampleResult res = new SampleResult();
        res.setSampleLabel(getName());
        res.setSamplerData(getURL());
        res.sampleStart();

        try {
            this.run();
        } catch (JMSException ex) {
            log.error("Error running consumer ", ex);
            res.setResponseCode("500");
            res.setResponseMessage(ex.toString());
        }

        //Calculate response time
        res.sampleEnd();

        // Set if we were successful or not
        res.setSuccessful(true);

        return res;
    }
}
TOP

Related Classes of org.codehaus.activemq.sampler.Consumer

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.