javax.naming.Noinitialcontextexception:

Asked

Viewed 67 times

-3

I am trying to do a university job with messageria, but my chat is not starting and presenting the following problem:

  javax.naming.NoInitialContextException: Cannot instantiate class: org.apache.activemq.jndi.ActiveMQInitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.apache.activemq.jndi.ActiveMQInitialContextFactory]
    C:\Users\Gabriel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: -1

Why does this problem happen?

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package autoinstrucionalclientprj;

import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.jms.Message;
import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.swing.JOptionPane;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
 *
 * @author Gabriel
 */
public class Client extends javax.swing.JFrame {

    /**
     * Creates new form Server
     */
    public Client() {
        initComponents();
    }
   private String usuario;
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        btnEnviar = new javax.swing.JButton();
        txtMensagem = new javax.swing.JTextField();
        txtDestinatario = new javax.swing.JTextField();
        txtMensagens = new javax.swing.JScrollPane();
        txtMensagensRecebidas = new javax.swing.JTextArea();
        lblCodigoDestinatario = new javax.swing.JLabel();
        lblMensagem = new javax.swing.JLabel();
        txtCodigoUsuario = new javax.swing.JTextField();
        lblCodigoUsuario = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnEnviar.setIcon(new javax.swing.ImageIcon("C:\\Users\\Gabriel\\Documents\\NetBeansProjects\\AutoInstrucionalClientPrj\\icons\\email-send-icon.png")); // NOI18N
        btnEnviar.setText("Enviar");
        btnEnviar.setName("btnEnviar"); // NOI18N
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        txtMensagem.setName("txtMensagem"); // NOI18N
        txtMensagem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtMensagemKeyPressed(evt);
            }
        });

        txtDestinatario.setName(""); // NOI18N

        txtMensagensRecebidas.setEditable(false);
        txtMensagensRecebidas.setColumns(20);
        txtMensagensRecebidas.setRows(5);
        txtMensagensRecebidas.setEnabled(false);
        txtMensagens.setViewportView(txtMensagensRecebidas);

        lblCodigoDestinatario.setText("Código do Destinatário: ");

        lblMensagem.setText("Mensagem: ");

        txtCodigoUsuario.setEditable(false);
        txtCodigoUsuario.setEnabled(false);

        lblCodigoUsuario.setText("O seu código é :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtMensagens)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblCodigoDestinatario)
                            .addComponent(lblMensagem))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtDestinatario, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(txtMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnEnviar)
                                .addGap(19, 19, 19))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCodigoUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCodigoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCodigoUsuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtMensagens, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDestinatario, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                    .addComponent(lblCodigoDestinatario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblMensagem)))
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        String palavra;

        final Calendar c = Calendar.getInstance();

        //gera uma palavra randomica
        palavra = PalavraRandomica.nomeAleatorio(10);

        //concatena o ano, mes e dia com a palavra a randomica para gerar o nome de um usuario
        txtCodigoUsuario.setText(String.valueOf(c.get(Calendar.YEAR)) + String.valueOf(c.get(Calendar.MONTH)) + String.valueOf(c.get(Calendar.DAY_OF_MONTH))  + palavra);

        usuario = txtCodigoUsuario.getText();
        if(usuario != null && !usuario.equals("")){
            topicos();
            filas();
        }else{
            System.exit(0);
        }




    }                                 

    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        enviarMensagem();
    }                                         

    private void txtMensagemKeyPressed(java.awt.event.KeyEvent evt) {                                       
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            JOptionPane.showInputDialog(KeyEvent.VK_ENTER);
        }
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Client().setVisible(true);
            }
        });
    }


    private void topicos(){
        Context context = initContext();
        TopicConnectionFactory connectionFactory = null;
        Topic topic = null;
        try{
            connectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            topic = (Topic) context.lookup("TesteTopic");
        }catch(NamingException nex){
            alertDialog("Impossível se conectar!" );
            alertDialog("Exceção gerada: " + nex);
            System.exit(-1);
        }

        TopicConnection connection = null; //Criando a conexão e a sessão
        try{
            connection = connectionFactory.createTopicConnection();
            TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            TopicSubscriber subscriber = session.createSubscriber(topic);
            subscriber.setMessageListener(new Mensagens());
            connection.start();
        }catch(JMSException jex){
            alertDialog("Impossível de se conectar");
            System.out.println("Exceção gerada" + jex);
        }
    }


     private void filas(){

        Context context = initContext();       

        QueueConnectionFactory connectionFactory = null;  // Cconexões da fábrica e da fila de destino
        Queue queue = null;
        try {
            connectionFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");//pesquisa conexão
            queue = (Queue) context.lookup("TesteQueue");//pesquisa o serviço
        } catch (NamingException e) {
            System.exit(-1);
        }

        QueueConnection connection = null;
        try {// Criando a conexão e da sessão
            connection = connectionFactory.createQueueConnection();

            //false => não utiliza transação)
            QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            String codigoUsuariio = "KEY='" + usuario + "'";

            QueueReceiver receiver = session.createReceiver(queue, usuario); //passa a fila e a "senha" - nome do usuario        

            receiver.setMessageListener(new Mensagens());
            connection.start();

        } catch (JMSException e) {
                e.printStackTrace();
        }
    }
     private void alertDialog(String message){
        JOptionPane.showMessageDialog(null, message, "Bate Papo", JOptionPane.INFORMATION_MESSAGE);
    }

    //init context
    private Context initContext(){
        Context initContext = null;
        try{
            initContext = new InitialContext();
        }catch(NamingException nex)
        {
            System.err.println("Impossível de receber contexto: " + nex);
            System.exit(-1);
        }
        return initContext;
    }

    //envia a mensagem
    private void enviarMensagem(){
        String usuarioEspecifico = txtCodigoUsuario.getText().trim();
        String mensagem = txtMensagem.getText().trim();
        SendMessage sendMessage = new SendMessage();
        if(usuarioEspecifico.equals("")){

            sendMessage.sendMessage(initContext(),usuarioEspecifico, mensagem);
        }
        else{
            txtMensagensRecebidas.setText(txtMensagensRecebidas.getText() + usuarioEspecifico + ": " + mensagem + "\n");
            sendMessage.sendMessage(initContext(),usuario, mensagem, usuarioEspecifico);
        }

        txtMensagem.setText("");
    }
    private void inserirMensagem(String messageObj){
        String[] messageInfos = messageObj.split(";");

        String nomeUsuario = messageInfos[0];
        String mensagem = messageInfos[1];

        String previousMessage = txtMensagensRecebidas.getText();  
        txtMensagensRecebidas.setText(previousMessage + nomeUsuario + ": " + mensagem + "\n\n"); // aparece ex.: Tata: Oi!

        txtMensagem.setText("");//esvazia a caixa de texto
    }
    private class Mensagens implements MessageListener {
        @Override
        public void onMessage(Message message){
            try{
                if(message == null){
                    alertDialog("Falha no recebimento de mensagem!");
                }
                else if(message instanceof TextMessage){
                    TextMessage textMessage = (TextMessage)message;
                    String msg = textMessage.getText();
                    inserirMensagem(msg);
                }
                else{
                    alertDialog("Erro ao receber mensagens!");
                }
            }catch(JMSException jmex){
                alertDialog(jmex.getMessage());
            }
        }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnEnviar;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel lblCodigoDestinatario;
    private javax.swing.JLabel lblCodigoUsuario;
    private javax.swing.JLabel lblMensagem;
    private javax.swing.JTextField txtCodigoUsuario;
    private javax.swing.JTextField txtDestinatario;
    private javax.swing.JTextField txtMensagem;
    private javax.swing.JScrollPane txtMensagens;
    private javax.swing.JTextArea txtMensagensRecebidas;
    // End of variables declaration                   
}
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to embed a broker inside this JVM
#useEmbeddedBroker = true

# use the following property to specify a class path resource or URL
# used to configure an embedded broker using the XML configuration file
#brokerXmlConfig = file:src/conf/sample-conf/default.xml

# use the following property to configure the default connector
brokerURL = tcp://localhost:61616 

# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.TesteQueue = TesteQueue

# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.TesteTopic = TesteTopic

1 answer

1

java.lang.ClassNotFoundException: org.apache.activemq.jndi.ActiveMQInitialContextFactory]

At first it looks like you are without the lib of this class in your classpath. Add the dependencies below in your pom.xml:

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.15.3</version>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-core</artifactId>
    <version>5.7.0</version>
</dependency>
<dependency>
     <groupId>javax.jms</groupId>
     <artifactId>jms</artifactId>
     <version>1.1</version>
</dependency>

Moves your properties file to the folder src/main/Resources. That should do it.

  • Buddy, I’m going to test this from what you told me Is this folder inside the netbeans project? I couldn’t find it

  • @gabrielfalieri if you are using Maven, this folder is automatically created by Netbeans when you create the project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.