Jms

2 respostas
P
Estou tentando seguir o exemplo do Capítulo 2 do livro Java Message Service, mas estou recebendo o seguinte erro:
C:\>java Chat TopicCF topic1 Joao
Exception in thread "main" java.lang.NoClassDefFoundError: Chat (wrong name: ch0
2/Chat)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
1)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: Chat.  Program will exit.
O pior é que, aparentemente, está tudo bem! :shock:

Estou usando o JDK 1.6.0.25, Eclipse Indigo e ActiveMQ 5.5.0. Defini uma variável de ambiente ACTIVEMQ_HOME com o valor até \apache-activemq-5.5.0 e adicionei à variável CLASSPATH o valor %ACTIVEMQ_HOME%\activemq-all-5.5.0.jar.

Mantive a entrada [color=red].;[/color] junto com o restante do CLASSPATH.

A listagem - "copiada e colada" do livro - é esta:
package ch02;

import java.io.*;
import javax.jms.*;
import javax.naming.*;

public class Chat implements javax.jms.MessageListener{
    private TopicSession pubSession;
    private TopicPublisher publisher;
    private TopicConnection connection;
    private String username;

    /* Constructor used to Initialize Chat */
    public Chat(String topicFactory, String topicName, String username) 
        throws Exception {
    	
    	// Obtain a JNDI connection using the jndi.properties file
        InitialContext ctx = new InitialContext();

        // Look up a JMS connection factory
        TopicConnectionFactory conFactory = 
        	(TopicConnectionFactory)ctx.lookup(topicFactory);

        // Create a JMS connection
        TopicConnection connection = conFactory.createTopicConnection();

        // Create two JMS session objects
        TopicSession pubSession = connection.createTopicSession(
        	false, Session.AUTO_ACKNOWLEDGE);        
        TopicSession subSession = connection.createTopicSession(
        	false, Session.AUTO_ACKNOWLEDGE);

        // Look up a JMS topic
        Topic chatTopic = (Topic)ctx.lookup(topicName);

        // Create a JMS publisher and subscriber
        TopicPublisher publisher = 
            pubSession.createPublisher(chatTopic);
        TopicSubscriber subscriber = 
            subSession.createSubscriber(chatTopic, null, true);

        // Set a JMS message listener
        subscriber.setMessageListener(this);

        // Intialize the Chat application variables
        this.connection = connection;
        this.pubSession = pubSession;
        this.publisher = publisher;
        this.username = username;

        // Start the JMS connection; allows messages to be delivered
        connection.start( );
    }

    /* Receive Messages From Topic Subscriber */
    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText( );
            System.out.println(text);
        } catch (JMSException jmse){ jmse.printStackTrace( ); }
    }

    /* Create and Send Message Using Publisher */
    protected void writeMessage(String text) throws JMSException {
        TextMessage message = pubSession.createTextMessage( );
        message.setText(username+": "+text);
        publisher.publish(message);
    }

    /* Close the JMS Connection */
    public void close( ) throws JMSException {
        connection.close( );
    }

    /* Run the Chat Client */
    public static void main(String [] args){
        try{
            if (args.length!=3)
                System.out.println("Factory, Topic, or username missing");

            // args[0]=topicFactory; args[1]=topicName; args[2]=username
            Chat chat = new Chat(args[0],args[1],args[2]);

            // Read from command line
            BufferedReader commandLine = new 
              java.io.BufferedReader(new InputStreamReader(System.in));

            // Loop until the word "exit" is typed
            while(true){
                String s = commandLine.readLine( );
                if (s.equalsIgnoreCase("exit")){
                    chat.close( ); // close down connection
                    System.exit(0);// exit program
                } else 
                    chat.writeMessage(s);
            }
        } catch (Exception e){ e.printStackTrace( ); }
    }
}
O arquivo jndi.properties, também "copiado e colado" do livro, é este:
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
java.naming.provider.url = tcp://localhost:61616
java.naming.security.principal = system
java.naming.security.credentials = manager
connectionFactoryNames = TopicCF
topic.topic1 = jms.topic1
E o arquivo activemq.xml, onde adicionei apenas a tag <destinations>, é este:
&lt;beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:amq="http://activemq.apache.org/schema/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd"&gt;

    &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
        &lt;property name="locations"&gt;
            &lt;value&gt;file:${activemq.base}/conf/credentials.properties&lt;/value&gt;
        &lt;/property&gt;      
    &lt;/bean&gt;

	&lt;destinations&gt;
		&lt;topic name = "topic1" physicalName = "jms.topic1" /&gt;
	&lt;/destinations&gt;
	
    &lt;broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data" destroyApplicationContextOnStop="true"&gt;
 
        &lt;destinationPolicy&gt;
            &lt;policyMap&gt;
              &lt;policyEntries&gt;
                &lt;policyEntry topic="&gt;" producerFlowControl="true" memoryLimit="1mb"&gt;
                  &lt;pendingSubscriberPolicy&gt;
                    &lt;vmCursor /&gt;
                  &lt;/pendingSubscriberPolicy&gt;
                &lt;/policyEntry&gt;
                &lt;policyEntry queue="&gt;" producerFlowControl="true" memoryLimit="1mb"&gt;
                &lt;/policyEntry&gt;
              &lt;/policyEntries&gt;
            &lt;/policyMap&gt;
        &lt;/destinationPolicy&gt; 
 
        &lt;managementContext&gt;
            &lt;managementContext createConnector="false"/&gt;
        &lt;/managementContext&gt;

        &lt;persistenceAdapter&gt;
            &lt;kahaDB directory="${activemq.base}/data/kahadb"/&gt;
        &lt;/persistenceAdapter&gt;
        
    &lt;/broker&gt;

    &lt;import resource="jetty.xml"/&gt;
    
&lt;/beans&gt;
Ao rodar o comando %ACTIVEMQ_HOME%\bin\activemq.bat, consigo "subir" o servidor numa boa! Inclusive, quando aponto o navegador para http://localhost:8161/admin/, consigo carregar o Console Administrativo!

A única coisa que não consigo é rodar o exemplo! :shock:

Alguém faz ideia do que eu devo fazer para conseguir rodar este exemplo?

2 Respostas

romarcio

O problema é esse:Could not find the main class: Chat. Program will exit.
O local onde você está executando a classe não contém a classe Chat. A classe foi criada dentro do pacote “ch02” e você está executando direto do “C:”

P

num é isso não! eu só evitei colar aqui o caminho todo, até a classe… :roll:

Criado 9 de outubro de 2011
Ultima resposta 9 de out. de 2011
Respostas 2
Participantes 2