tutorial jms

37
Trabalho de Sistemas Distribuídos Implementação de um Chat utilizando JMS Eduardo Rigamonte e Pietro Christ INTRODUÇÃO Neste roteiro iremos explicar a criação de um chat utilizando a tecnologia Java Message Service (JMS). A arquitetura JMS disponibiliza dois tipos de troca de mensagens, o Queue (modelo ponto a ponto ou modelo de filas) e o modelo Topic ou Publish/Subscribe. Com o modelo de troca de mensagens por filas, poderíamos ter um ou vários produtores enviando mensagens para uma mesma fila, mas teríamos apenas um único consumidor. Neste modelo, cada vez que uma mensagem é consumida, ela deixa de existir na fila, por isso, podemos ter apenas um único consumidor. O modelo Topic, permite uma situação em que teríamos de um a vários consumidores para o mesmo tópico. Funciona como um sistema de assinaturas, cada cliente assina um tópico e a mensagem fica armazenada no servidor até todos assinantes a tenham consumido. Este será o modelo usado neste tutorial. Arquitetura utilizando Queue (filas) e Topic (tópicos) ROTEIRO 1 Instalação dos artefatos e ferramentas necessárias: 1.1 Fazer o download do Apache ActiveMQ 5.4.2 http://www.4shared.com/zip/ksBEB_FW/apache-activemq-542-bin.html 1.2 Descompactar o arquivo baixado no diretório C:. 1.3 Para iniciá-lo basta executar o arquivo activemq.bat no caminho: C:\apache-activemq-5.4.2\bin\win32

Upload: eduardo-rigamonte-costa

Post on 07-Jul-2015

503 views

Category:

Technology


3 download

DESCRIPTION

Tutorial sobre como fazer um chat ussando JMS e ActiveMQ

TRANSCRIPT

Page 1: Tutorial jms

Trabalho de Sistemas Distribuídos Implementação de um Chat utilizando JMS

Eduardo Rigamonte e Pietro Christ

INTRODUÇÃO

Neste roteiro iremos explicar a criação de um chat utilizando a tecnologia Java Message

Service (JMS). A arquitetura JMS disponibiliza dois tipos de troca de mensagens, o Queue (modelo

ponto a ponto ou modelo de filas) e o modelo Topic ou Publish/Subscribe.

Com o modelo de troca de mensagens por filas, poderíamos ter um ou vários produtores

enviando mensagens para uma mesma fila, mas teríamos apenas um único consumidor. Neste

modelo, cada vez que uma mensagem é consumida, ela deixa de existir na fila, por isso, podemos

ter apenas um único consumidor.

O modelo Topic, permite uma situação em que teríamos de um a vários consumidores para o

mesmo tópico. Funciona como um sistema de assinaturas, cada cliente assina um tópico e a

mensagem fica armazenada no servidor até todos assinantes a tenham consumido. Este será o

modelo usado neste tutorial.

Arquitetura utilizando Queue (filas) e Topic (tópicos)

ROTEIRO

1 Instalação dos artefatos e ferramentas necessárias:

1.1 Fazer o download do Apache ActiveMQ 5.4.2

http://www.4shared.com/zip/ksBEB_FW/apache-activemq-542-bin.html

1.2 Descompactar o arquivo baixado no diretório C:.

1.3 Para iniciá-lo basta executar o arquivo activemq.bat no caminho:

C:\apache-activemq-5.4.2\bin\win32

Page 2: Tutorial jms

1.4 O FrontEnd do Apache ActiveMQ estará disponivel em http://localhost:8161/admin

FrontEnd Apache ActiveMQ

1.5 É necessário que o JDK e um IDE estejam instalados para funcionamento da

construção do chat. Neste tutorial utilizamos o Netbeans 7.1.1

2 Etapas para a construção do CHAT (passos a serem realizados pelo estudante):

2.1 Abra o Netbeans e crie um projeto Java.

2.2 A criação da interface será abstraída. Iremos disponibilizar o código completo no fim

do documento.

2.3 Adicione a biblioteca activemq-all-5.4.2.jar, que se encontra no diretório raiz do

activeMQ, ao projeto.

2.4 Criar uma classe JmsSubscriber.java, esta classe tem a finalidade de preparar a

conexão para poder assinar um tópico e consequentemente poder receber as mensagens

que serão publicadas.

import chat.ctrl.CtrlChat;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

public class JmsSubscriber implements MessageListener {

private TopicConnection connect;

public JmsSubscriber(String factoryName, String topicName) throws

JMSException, NamingException {

//Obtém os dados da conexão JNDI através do arquivo jndi.properties

Page 3: Tutorial jms

Context jndiContext = new

InitialContext(CtrlChat.getInstance().getProperties());

//O cliente utiliza o TopicConnectionFactory para criar um objeto do tipo

//TopicConnection com o provedor JMS

TopicConnectionFactory factory = (TopicConnectionFactory)

jndiContext.lookup(factoryName);

//Pesquisa o destino do tópico via JNDI

Topic topic = (Topic) jndiContext.lookup(topicName);

//Utiliza o TopicConnectionFactory para criar a conexão com o provedor JMS

this.connect = factory.createTopicConnection();

//Utiliza o TopicConnection para criar a sessão para o consumidor

//Atributo false -> uso ou não de transações(tratar uma série de

//envios/recebimentos como unidade atômica e controlá-la via commit e

//rollback)

//Atributo AUTO_ACKNOWLEDGE -> Exige confirmação automática após

//recebimento correto

TopicSession session = connect.createTopicSession(false,

Session.AUTO_ACKNOWLEDGE);

//Cria(Assina) o tópico JMS do consumidor das mensagens através da sessão e o

//nome do tópico

TopicSubscriber subscriber = session.createSubscriber(topic);

//Escuta o tópico para receber as mensagens através do método onMessage()

subscriber.setMessageListener(this);

//Inicia a conexão JMS, permite que mensagens sejam entregues

connect.start();

}

// Recebe as mensagens do tópico assinado

public void onMessage(Message message) {

try {

//As mensagens criadas como TextMessage devem ser recebidas como

//TextMessage

TextMessage textMsg = (TextMessage) message;

String text = textMsg.getText();

CtrlChat.getInstance().printtTela(text);

Page 4: Tutorial jms

}

catch (JMSException ex) {

ex.printStackTrace();

}

}

// Fecha a conexão JMS

public void close() throws JMSException {

this.connect.close();

}

}

2.5 Criar uma classe JmsPublisher.java, esta classe tem a finalidade de preparar a conexão

para poder publicar mensagens em um tópico.

import chat.ctrl.CtrlChat;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

public class JmsPublisher {

private TopicPublisher publisher;

private TopicSession session;

private TopicConnection connect;

public JmsPublisher(String factoryName, String topicName) throws JMSException,

NamingException {

//Obtém os dados da conexão JNDI através do método getProperties

Context jndiContext = new InitialContext(CtrlChat.getInstance().getProperties());

// O cliente utiliza o TopicConnectionFactory para criar um objeto do tipo

//TopicConnection com o provedor JMS

TopicConnectionFactory factory = (TopicConnectionFactory)

jndiContext.lookup(factoryName);

// Pesquisa o destino do tópico via JNDI

Topic topic = (Topic) jndiContext.lookup(topicName);

// Utiliza o TopicConnectionFactory para criar a conexão com o provedor JMS

Page 5: Tutorial jms

this.connect = factory.createTopicConnection();

//Utiliza o TopicConnection para criar a sessão para o produtor

//Atributo false -> uso ou não de transações(tratar uma série de

//envios/recebimentos como unidade atômica e controlá-la via commit e rollback)

//Atributo AUTO_ACKNOWLEDGE -> Exige confirmação automática após

//recebimento correto

this.session = connect.createTopicSession(false,

Session.AUTO_ACKNOWLEDGE);

//Cria o tópico JMS do produtor das mensagens através da sessão e o nome do

//tópico

this.publisher = session.createPublisher(topic);

}

//Cria a mensagem de texto e a publica no tópico. Evento referente ao produtor

public void publish(String message) throws JMSException {

//Recebe um objeto da sessao para criar uma mensagem do tipo TextMessage

TextMessage textMsg = this.session.createTextMessage();

//Seta no objeto a mensagem que será enviada

textMsg.setText(message);

//Publica a mensagem no tópico

this.publisher.publish(textMsg, DeliveryMode.PERSISTENT, 1, 0);

}

//Fecha a conexão JMS

public void close() throws JMSException {

this.connect.close();

}

}

2.6 Criar uma classe CtrlChat.java , esta classe contém um métodos getProperties que

retorno o arquivo java.util.properties no qual possui as configurações do servidor (ip do

servidor, topic etc). Os métodos referente a configuração do JMS está abaixo, o restante

não será mostrado aqui, porém estará disponibilizado no fim do documento.

private JmsPublisher publisher = null;

private JmsSubscriber subscriber = null;

private String nome = "Anonimo";

Page 6: Tutorial jms

private String ipServ = "";

private Properties prop = null;

private String topicName = "topicChat";

private String factoryName = "TopicCF";

public Properties getProperties() {

if (prop == null) {

prop = new Properties();

//classe jndi para o ActiveMQ

prop.put("java.naming.factory.initial",

"org.apache.activemq.jndi.ActiveMQInitialContextFactory");

//url para conexão com o provedor

prop.put("java.naming.provider.url", "tcp://" + ipServ + ":61616");

//nome da conexão

prop.put("connectionFactoryNames", factoryName);

//nome do tópico jms

prop.put("topic.topicChat", topicName);

}

return prop;

}

public void iniciarJMS() {

try {

subscriber = new JmsSubscriber(factoryName, topicName);

publisher = new JmsPublisher(factoryName, topicName);

publisher.publish(this.nome + " entrou na sala ..\n");

//habilita os componentes da janela como enable true/false

janChat.setComponentesEnable(true);

}

catch (JMSException ex) {

JOptionPane.showMessageDialog(janChat, "Servidor não Encontrado!",

"ERROR", JOptionPane.OK_OPTION);

Page 7: Tutorial jms

ipServ = "";

Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex);

}

catch (NamingException ex) {

Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex);

}

}

2.7 Existe uma persistência das mensagens no banco de dados SQLITE, utilizando

JPA/Hibernate.

2.7.1 Para a persistência foram utilizados os padrões de projeto fábrica abstrata e

método fábrica. Classes criadas: DAO (interface), DAOJPA (implementação dos

métodos utilizando JPA), ObjetoPersistente (pai de todas as classes persistentes),

DAOFactory (classe que implementa o método fábrica e o classe abstrata).

2.7.2 Para o funcionamento adequado da persistencia deve adicionar as bibliotecas:

sqlitejdbc-v056.jar, slf4j-simple-1.6.1.jar, slf4j-api-1.6.1.jar, jta-1.1.jar, javassist-

3.12.0.GA.jar, hibernate3.jar, hibernate-jpa-2.0-api-1.0.1.Final.jar, dom4j-1.6.1.jar,

commons-collections-3.1.jar, cglib-2.2.jar, c3p0-0.9.1.jar e antlr-2.7.6.jar. Além do

dialect do SQLITE.

3 Resultados Esperados

O esperado é que seja possível estabelecer uma conexão dos clientes ao servidor JMS

(ActiveMQ) para poder enviar e receber as mensagens. Além disso as mensagens

trocadas sejam gravadas em um banco formando um histórico para cada cliente.

4 Resolução de problemas mais comuns

4.1 O chat só irá funcionar caso o ActiveMQ estiver ativo.

4.2 Se o IP não for encontrado não será possível estabelecer a comunicação.

4.3 Caso a rede cair haverá uma tentativa de reconexão, caso não haja sucesso o chat será

desativado e as mensagens enviadas neste tempo não serão entregues.

REFERÊNCIAS

http://mballem.wordpress.com/2011/02/09/chat-jms-com-activemq/http://onjava.com/pub/a/onjava/2001/12/12/jms_not.html

Link do Tutorial em Video - http://www.youtube.com/watch?v=7Q9qe6FQ2TE

Page 8: Tutorial jms

/* * Classe criada para o 2º trabalho da disciplina de Sistemas Distribuidos. */package chat.rede;

import chat.ctrl.CtrlChat;import javax.jms.*;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;

public class JmsSubscriber implements MessageListener {

private TopicConnection connect;

public JmsSubscriber(String factoryName, String topicName) throws JMSException, NamingException { // Obtém os dados da conexão JNDI através do arquivo jndi.properties Context jndiContext = new InitialContext(CtrlChat.getInstance().getProperties()); // O cliente utiliza o TopicConnectionFactory para criar um objeto do tipo TopicConnection com o provedor JMS TopicConnectionFactory factory = (TopicConnectionFactory) jndiContext.lookup(factoryName); // Pesquisa o destino do tópico via JNDI Topic topic = (Topic) jndiContext.lookup(topicName); // Utiliza o TopicConnectionFactory para criar a conexão com o provedor JMS this.connect = factory.createTopicConnection(); // Utiliza o TopicConnection para criar a sessão para o consumidor // Atributo false -> uso ou não de transações(tratar uma série de envios/recebimentos como unidade atômica e // controlá-la via commit e rollback) // Atributo AUTO_ACKNOWLEDGE -> Exige confirmação automática após recebimento correto TopicSession session = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // Cria(Assina) o tópico JMS do consumidor das mensagens através da sessão e o nome do tópico TopicSubscriber subscriber = session.createSubscriber(topic); // Escuta o tópico para receber as mensagens através do método onMessage() subscriber.setMessageListener(this); // Inicia a conexão JMS, permite que mensagens sejam entregues connect.start(); }

@Override // Recebe as mensagens do tópico assinado public void onMessage(Message message) { try {

Anexo

Page 9: Tutorial jms

// As mensagens criadas como TextMessage devem ser recebidas como TextMessage TextMessage textMsg = (TextMessage) message; String text = textMsg.getText(); CtrlChat.getInstance().printtTela(text); } catch (JMSException ex) { ex.printStackTrace(); } } // Fecha a conexão JMS public void close() throws JMSException { this.connect.close(); }}

Page 10: Tutorial jms

/* * Classe criada para o 2º trabalho da disciplina de Sistemas Distribuidos. */package chat.rede;

import chat.ctrl.CtrlChat;import javax.jms.*;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;

public class JmsPublisher {

private TopicPublisher publisher; private TopicSession session; private TopicConnection connect;

public JmsPublisher(String factoryName, String topicName) throws JMSException, NamingException { // Obtém os dados da conexão JNDI através do arquivo jndi.properties Context jndiContext = new InitialContext(CtrlChat.getInstance().getProperties()); // O cliente utiliza o TopicConnectionFactory para criar um objeto do tipo TopicConnection com o provedor JMS TopicConnectionFactory factory = (TopicConnectionFactory) jndiContext.lookup(factoryName); // Pesquisa o destino do tópico via JNDI Topic topic = (Topic) jndiContext.lookup(topicName); // Utiliza o TopicConnectionFactory para criar a conexão com o provedor JMS this.connect = factory.createTopicConnection(); // Utiliza o TopicConnection para criar a sessão para o produtor // Atributo false -> uso ou não de transações(tratar uma série de envios/recebimentos como unidade atômica e // controlá-la via commit e rollback) // Atributo AUTO_ACKNOWLEDGE -> Exige confirmação automática após recebimento correto this.session = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // Cria o tópico JMS do produtor das mensagens através da sessão e o nome do tópico this.publisher = session.createPublisher(topic); }

// Cria a mensagem de texto e a publica no tópico. Evento referente ao produtor public void publish(String message) throws JMSException { // Recebe um objeto da sessao para criar uma mensagem do tipo TextMessage TextMessage textMsg = this.session.createTextMessage(); // Seta no objeto a mensagem que será enviada textMsg.setText(message);

Page 11: Tutorial jms

// Publica a mensagem no tópico this.publisher.publish(textMsg, DeliveryMode.PERSISTENT, 1, 0); }

// Fecha a conexão JMS public void close() throws JMSException { this.connect.close(); }}

Page 12: Tutorial jms

/* * Classe criada para o 2º trabalho da disciplina de Sistemas Distribuidos. */package chat.ctrl;

import chat.cdp.Mensagem;import chat.cih.JanChat;import chat.cih.JanConfigurar;import java.util.List;import java.util.Properties;import java.util.logging.Level;import java.util.logging.Logger;import javax.jms.JMSException;import javax.naming.NamingException;import javax.swing.JOptionPane;import chat.rede.JmsPublisher;import chat.rede.JmsSubscriber;import util.cgd.DAO;import util.cgd.DAOFactory;

/** * * @author erigamonte */public class CtrlChat {

private JmsPublisher publisher = null; private JmsSubscriber subscriber = null; private String nome = "Anonimo"; private String ipServ = ""; private JanChat janChat; private Properties prop = null; private String topicName = "topicChat"; private String factoryName = "TopicCF";

private CtrlChat() { }

public static CtrlChat getInstance() { return CtrlChatHolder.INSTANCE; }

Page 13: Tutorial jms

private static class CtrlChatHolder {

private static final CtrlChat INSTANCE = new CtrlChat(); }

public Properties getProperties() { if (prop == null) { prop = new Properties();

//classe jndi para o ActiveMQ prop.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); //url para conexão com o provedor prop.put("java.naming.provider.url", "tcp://" + ipServ + ":61616"); //nome da conexão prop.put("connectionFactoryNames", factoryName); //nome do tópico jms prop.put("topic.topicChat", topicName); }

return prop; }

public void changeServer(String ip) { //inicia ou pega as propriedades Properties p = getProperties(); //remove o endereço anterior p.remove("java.naming.provider.url"); //adiciona um novo p.put("java.naming.provider.url", "tcp://" + ip + ":61616"); ipServ = ip;

}

public void iniciarJMS() { try { subscriber = new JmsSubscriber(factoryName, topicName); publisher = new JmsPublisher(factoryName, topicName);

publisher.publish(this.nome + " entrou na sala ..\n");

Page 14: Tutorial jms

//habilita os componentes da janela como enable true/false janChat.setComponentesEnable(true); } catch (JMSException ex) { JOptionPane.showMessageDialog(janChat, "Servidor não Encontrado!", "ERROR", JOptionPane.OK_OPTION); ipServ = ""; Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } catch (NamingException ex) { Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } }

public void reconectarPublisher() { try { publisher.close(); subscriber.close(); subscriber = new JmsSubscriber(factoryName, topicName); publisher = new JmsPublisher(factoryName, topicName); } catch (JMSException ex) { JOptionPane.showMessageDialog(janChat, "Servidor não Encontrado!", "ERROR", JOptionPane.OK_OPTION); ipServ = ""; janChat.setComponentesEnable(false); Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } catch (NamingException ex) { Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } }

public JmsPublisher getPublisher() { return publisher; }

public JmsSubscriber getSubscriber() { return subscriber; }

public void fecharConexao() { try {

Page 15: Tutorial jms

publisher.publish(this.nome + " saiu da sala ..\n");

this.publisher.close(); this.subscriber.close(); } catch (JMSException ex) { Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } }

public boolean servidorIniciado() { if (publisher != null && subscriber != null) { return true; } return false; }

public void abrirJanConfigurar() { new JanConfigurar().setVisible(true); }

public String getNome() { return nome; }

public void setNome(String nome) { if (servidorIniciado()) { try { //envia para o servidor publisher.publish(this.nome + " mudou o nome para " + nome + "\n"); } catch (JMSException ex) { Logger.getLogger(JanChat.class.getName()).log(Level.SEVERE, null, ex); } } this.nome = nome; }

public String getIpServidor() { return ipServ; }

Page 16: Tutorial jms

public void setIpServidor(String ipServ) { this.ipServ = ipServ; }

public void setTela(JanChat aThis) { janChat = aThis; }

public void printtTela(String msg) { janChat.printTela(msg); } //dao responsavel por salvar as mensagens no banco private DAO dao = DAOFactory.getInstance().obterDAO(Mensagem.class);

public void salvarHistorico(String msg) { Mensagem m = new Mensagem(); m.setTexto(msg);

try { dao.salvar(m); } catch (Exception ex) { Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex); } }

public String getHistorico() { List<Mensagem> conversa = null; String msg = ""; try { conversa = dao.obter(Mensagem.class); System.out.println("a"); for (int i = 0; conversa!= null && i < conversa.size(); i++) { msg += conversa.get(i).getTexto(); } } catch (Exception ex) { System.out.println("b"); Logger.getLogger(CtrlChat.class.getName()).log(Level.SEVERE, null, ex);

}

Page 17: Tutorial jms

return msg; }}

Page 18: Tutorial jms

/* * Frame criado para o 2º trabalho da disciplina de Sistemas Distribuidos. */package chat.cih;

import chat.ctrl.CtrlChat;import java.awt.AWTException;import java.awt.Color;import java.awt.Frame;import java.awt.Robot;import java.awt.event.KeyEvent;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.logging.Level;import java.util.logging.Logger;import javax.imageio.ImageIO;import javax.jms.JMSException;import javax.swing.JFileChooser;

public class JanChat extends javax.swing.JFrame {

private boolean shiftOn = false;

public JanChat() { initComponents(); initFrame(); CtrlChat.getInstance().setTela(this); }

@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {

panelPrincipal = new javax.swing.JPanel(); panelCenter = new javax.swing.JPanel(); filler5 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 10), new java.awt.Dimension(0, 10), new java.awt.Dimension(32767, 10)); filler7 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767)); filler8 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767)); panelTitulo = new javax.swing.JPanel(); tituloLabel = new javax.swing.JLabel(); conversaScrollPane = new javax.swing.JScrollPane(); conversaText = new javax.swing.JTextPane(); panelSouth = new javax.swing.JPanel(); filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 10), new java.awt.Dimension(0, 10), new java.awt.Dimension(32767, 10)); filler4 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767)); panelMensagem = new javax.swing.JPanel(); panelTexto = new javax.swing.JPanel(); mensagemScrollPane = new javax.swing.JScrollPane(); mensagemText = new javax.swing.JTextPane(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767)); panelBotao = new javax.swing.JPanel(); enviarButton = new javax.swing.JButton(); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767)); barraMenuChat = new javax.swing.JMenuBar(); arquivoMenu = new javax.swing.JMenu(); configItem = new javax.swing.JMenuItem(); separador = new javax.swing.JPopupMenu.Separator(); sairItem = new javax.swing.JMenuItem(); historicoMenu = new javax.swing.JMenu(); ativarCheckBox = new javax.swing.JCheckBoxMenuItem(); exportarHistoricoItem = new javax.swing.JMenuItem();

Page 19: Tutorial jms

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

panelPrincipal.setLayout(new java.awt.BorderLayout());

panelCenter.setLayout(new java.awt.BorderLayout()); panelCenter.add(filler5, java.awt.BorderLayout.PAGE_END); panelCenter.add(filler7, java.awt.BorderLayout.LINE_END); panelCenter.add(filler8, java.awt.BorderLayout.LINE_START);

tituloLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N tituloLabel.setText("CHAT JMS"); panelTitulo.add(tituloLabel);

panelCenter.add(panelTitulo, java.awt.BorderLayout.PAGE_START);

conversaText.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N conversaScrollPane.setViewportView(conversaText);

panelCenter.add(conversaScrollPane, java.awt.BorderLayout.CENTER);

panelPrincipal.add(panelCenter, java.awt.BorderLayout.CENTER);

panelSouth.setLayout(new java.awt.BorderLayout()); panelSouth.add(filler3, java.awt.BorderLayout.PAGE_END); panelSouth.add(filler4, java.awt.BorderLayout.LINE_START);

panelMensagem.setLayout(new javax.swing.BoxLayout(panelMensagem, javax.swing.BoxLayout.X_AXIS));

panelTexto.setLayout(new java.awt.BorderLayout());

mensagemText.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N mensagemText.setPreferredSize(new java.awt.Dimension(164, 94)); mensagemText.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { mensagemTextKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { mensagemTextKeyReleased(evt); } }); mensagemScrollPane.setViewportView(mensagemText);

panelTexto.add(mensagemScrollPane, java.awt.BorderLayout.CENTER); panelTexto.add(filler1, java.awt.BorderLayout.LINE_END);

panelMensagem.add(panelTexto);

panelBotao.setLayout(new javax.swing.BoxLayout(panelBotao, javax.swing.BoxLayout.LINE_AXIS));

enviarButton.setText("Enviar"); enviarButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { enviarButtonActionPerformed(evt); } }); panelBotao.add(enviarButton);

panelMensagem.add(panelBotao); panelMensagem.add(filler2);

Page 20: Tutorial jms

panelSouth.add(panelMensagem, java.awt.BorderLayout.CENTER);

panelPrincipal.add(panelSouth, java.awt.BorderLayout.PAGE_END);

getContentPane().add(panelPrincipal, java.awt.BorderLayout.CENTER);

arquivoMenu.setText("Arquivo");

configItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); configItem.setText("Configurações"); configItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configItemActionPerformed(evt); } }); arquivoMenu.add(configItem); arquivoMenu.add(separador);

sairItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK)); sairItem.setText("Sair"); sairItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sairItemActionPerformed(evt); } }); arquivoMenu.add(sairItem);

barraMenuChat.add(arquivoMenu);

historicoMenu.setText("Histórico");

ativarCheckBox.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK)); ativarCheckBox.setSelected(true); ativarCheckBox.setText("Ativar Gravação"); historicoMenu.add(ativarCheckBox);

exportarHistoricoItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); exportarHistoricoItem.setText("Exportar .."); exportarHistoricoItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportarHistoricoItemActionPerformed(evt); } }); historicoMenu.add(exportarHistoricoItem);

barraMenuChat.add(historicoMenu);

setJMenuBar(barraMenuChat);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-416)/2, (screenSize.height-351)/2, 416, 351); }// </editor-fold>//GEN-END:initComponents

/* * Esse método é chamado para configurar o frame. */ // <editor-fold defaultstate="collapsed" desc="Método de configuração do Frame"> private void initFrame() { super.setTitle("CHAT JMS"); super.setExtendedState(Frame.MAXIMIZED_BOTH);

try { //adição do icone ao programa super.setIconImage(ImageIO.read(getClass().getResource("/chat/img/icone.png"))); }

Page 21: Tutorial jms

catch (IOException ex) { System.err.println("Icone não encontrado!"); } conversaText.setEditable(false); setComponentesEnable(false); }// </editor-fold>

/* * Esses Métodos são os eventos dos componentes do frame. */ // <editor-fold defaultstate="collapsed" desc="Eventos de Componentes"> private void sairItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sairItemActionPerformed //fecha a janela this.dispose(); }//GEN-LAST:event_sairItemActionPerformed

private void enviarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarButtonActionPerformed if (CtrlChat.getInstance().servidorIniciado()) { //pega a mesagem que o usuario quer enviar String msg = mensagemText.getText();

if (!msg.trim().equals("")) { //adiciona o nome do usuario java.util.Date agora = new java.util.Date();; SimpleDateFormat formata = new SimpleDateFormat("HH:mm");

msg = formata.format(agora) + " " + CtrlChat.getInstance().getNome() + " says:\n " + msg + "\n";

//zera caixa de texto mensagemText.setText(""); try { //envia para o servidor CtrlChat.getInstance().getPublisher().publish(msg); } catch (JMSException ex) { printTela("------\nMENSAGEM PERDIDA:\n" + msg +"------\n"); CtrlChat.getInstance().reconectarPublisher(); Logger.getLogger(JanChat.class.getName()).log(Level.SEVERE, null, ex); } } }

//foco novamente para o componente de msg mensagemText.grabFocus(); }//GEN-LAST:event_enviarButtonActionPerformed

private void configItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configItemActionPerformed CtrlChat.getInstance().abrirJanConfigurar(); }//GEN-LAST:event_configItemActionPerformed

private void exportarHistoricoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarHistoricoItemActionPerformed JFileChooser jfc = new JFileChooser(); int result = jfc.showSaveDialog(this);

if (result == JFileChooser.APPROVE_OPTION) { File file = jfc.getSelectedFile();

PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(file)); } catch (IOException ex) { Logger.getLogger(JanChat.class.getName()).log(Level.SEVERE, null, ex); }

Page 22: Tutorial jms

pw.println(CtrlChat.getInstance().getHistorico()); pw.close(); } }//GEN-LAST:event_exportarHistoricoItemActionPerformed

private void frameClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_frameClosing if (CtrlChat.getInstance().servidorIniciado()) { CtrlChat.getInstance().fecharConexao(); } }//GEN-LAST:event_frameClosing

private void mensagemTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mensagemTextKeyPressed //se for clicado um enter dentro do componente de mensagem //o evento do botão enviar e acionado if (evt.getKeyCode() == KeyEvent.VK_ENTER) { if (!shiftOn) { enviarButtonActionPerformed(null); try { //retira a acao de pula de linha new Robot().keyPress(KeyEvent.VK_BACK_SPACE); } catch (AWTException ex) { //Logger.getLogger(JanChat.class.getName()).log(Level.SEVERE, null, ex); } } else { //add o \n no fim da msg mensagemText.setText(mensagemText.getText() + "\n"); } } else if (evt.getKeyCode() == KeyEvent.VK_SHIFT) { //shift pressionado shiftOn = true; } }//GEN-LAST:event_mensagemTextKeyPressed

private void mensagemTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mensagemTextKeyReleased if (evt.getKeyCode() == KeyEvent.VK_SHIFT) { //shift despressionado shiftOn = false; } }//GEN-LAST:event_mensagemTextKeyReleased// </editor-fold>

public void printTela(String msg) { //salva a mensagem no historico if(ativarCheckBox.isSelected()){ CtrlChat.getInstance().salvarHistorico(msg); } //concatena com a conversa ja existente msg = conversaText.getText() + msg;

//mostra na propria tela conversaText.setText(msg); //autoscroll conversaText.setCaretPosition(conversaText.getDocument().getLength()); }

public void setComponentesEnable(boolean ativo) { mensagemText.setEnabled(ativo); conversaText.setEnabled(ativo); enviarButton.setEnabled(ativo);

Page 23: Tutorial jms

}

public static void main(String args[]) { /* * Set the Windows 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 ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break;

} } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JanChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JanChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JanChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JanChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold>

java.awt.EventQueue.invokeLater(new Runnable() {

@Override public void run() { new JanChat().setVisible(true); }

}); } // <editor-fold defaultstate="collapsed" desc="Declaração dos Componentes do Frame"> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu arquivoMenu; private javax.swing.JCheckBoxMenuItem ativarCheckBox; private javax.swing.JMenuBar barraMenuChat; private javax.swing.JMenuItem configItem; private javax.swing.JScrollPane conversaScrollPane; private javax.swing.JTextPane conversaText; private javax.swing.JButton enviarButton; private javax.swing.JMenuItem exportarHistoricoItem; private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler2; private javax.swing.Box.Filler filler3; private javax.swing.Box.Filler filler4; private javax.swing.Box.Filler filler5; private javax.swing.Box.Filler filler7; private javax.swing.Box.Filler filler8; private javax.swing.JMenu historicoMenu;

Page 24: Tutorial jms

private javax.swing.JScrollPane mensagemScrollPane; private javax.swing.JTextPane mensagemText; private javax.swing.JPanel panelBotao; private javax.swing.JPanel panelCenter; private javax.swing.JPanel panelMensagem; private javax.swing.JPanel panelPrincipal; private javax.swing.JPanel panelSouth; private javax.swing.JPanel panelTexto; private javax.swing.JPanel panelTitulo; private javax.swing.JMenuItem sairItem; private javax.swing.JPopupMenu.Separator separador; private javax.swing.JLabel tituloLabel; // End of variables declaration//GEN-END:variables // </editor-fold>}

Page 25: Tutorial jms

/* * Frame criado para o 2º trabalho da disciplina de Sistemas Distribuidos. */package chat.cih;

import chat.ctrl.CtrlChat;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JDialog;

/** * * @author erigamonte */public class JanConfigurar extends javax.swing.JDialog {

public JanConfigurar() { initComponents(); initFrame(); nomeText.setText(CtrlChat.getInstance().getNome()); ipText.setText(CtrlChat.getInstance().getIpServidor()); }

@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {

jPanel1 = new javax.swing.JPanel(); panelPrincipal = new javax.swing.JPanel(); opcoesPanel = new javax.swing.JPanel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 10), new java.awt.Dimension(0, 10), new java.awt.Dimension(32767, 10)); primeiraLinhaPanel = new javax.swing.JPanel(); nomePanel = new javax.swing.JPanel(); nomeLabel = new javax.swing.JLabel(); nomeText = new javax.swing.JTextField(); segundaLinhaPanel = new javax.swing.JPanel(); ipPanel = new javax.swing.JPanel(); ipLabel = new javax.swing.JLabel(); ipText = new javax.swing.JTextField(); botaoPanel = new javax.swing.JPanel(); aplicarBotao = new javax.swing.JButton();

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 357, Short.MAX_VALUE)

Page 26: Tutorial jms

); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) );

setResizable(false);

panelPrincipal.setLayout(new java.awt.BorderLayout());

opcoesPanel.setLayout(new javax.swing.BoxLayout(opcoesPanel, javax.swing.BoxLayout.Y_AXIS)); opcoesPanel.add(filler1);

primeiraLinhaPanel.setLayout(new javax.swing.BoxLayout(primeiraLinhaPanel, javax.swing.BoxLayout.LINE_AXIS));

java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 0); flowLayout1.setAlignOnBaseline(true); nomePanel.setLayout(flowLayout1);

nomeLabel.setText("Nome:"); nomePanel.add(nomeLabel);

nomeText.setMinimumSize(new java.awt.Dimension(60, 20)); nomeText.setPreferredSize(new java.awt.Dimension(300, 20)); nomeText.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { keyPressedNomeText(evt); } }); nomePanel.add(nomeText);

primeiraLinhaPanel.add(nomePanel);

opcoesPanel.add(primeiraLinhaPanel);

segundaLinhaPanel.setLayout(new javax.swing.BoxLayout(segundaLinhaPanel, javax.swing.BoxLayout.LINE_AXIS));

ipPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 0));

ipLabel.setText("En. IP:"); ipPanel.add(ipLabel);

ipText.setMinimumSize(new java.awt.Dimension(60, 20)); ipText.setPreferredSize(new java.awt.Dimension(300, 20)); ipText.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { keyPressedIpText(evt); }

Page 27: Tutorial jms

}); ipPanel.add(ipText);

segundaLinhaPanel.add(ipPanel);

opcoesPanel.add(segundaLinhaPanel);

panelPrincipal.add(opcoesPanel, java.awt.BorderLayout.CENTER);

botaoPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

aplicarBotao.setText("Aplicar"); aplicarBotao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aplicarBotaoActionPerformed(evt); } }); botaoPanel.add(aplicarBotao);

panelPrincipal.add(botaoPanel, java.awt.BorderLayout.PAGE_END);

getContentPane().add(panelPrincipal, java.awt.BorderLayout.CENTER);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-373)/2, (screenSize.height-144)/2, 373, 144); }// </editor-fold>//GEN-END:initComponents

/* * Esses Métodos são os eventos dos componentes do frame. */ // <editor-fold defaultstate="collapsed" desc="Eventos de Componentes"> private void aplicarBotaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aplicarBotaoActionPerformed this.setVisible(false); if (!CtrlChat.getInstance().getNome().equals(nomeText.getText())) { CtrlChat.getInstance().setNome(nomeText.getText()); } if (!CtrlChat.getInstance().getIpServidor().equals(ipText.getText())) {

CtrlChat.getInstance().changeServer(ipText.getText()); CtrlChat.getInstance().iniciarJMS(); }

this.dispose(); }//GEN-LAST:event_aplicarBotaoActionPerformed

private void keyPressedNomeText(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressedNomeText if (evt.getKeyCode() == KeyEvent.VK_ENTER) { aplicarBotaoActionPerformed(null);

Page 28: Tutorial jms

} }//GEN-LAST:event_keyPressedNomeText

private void keyPressedIpText(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressedIpText keyPressedNomeText(evt); }//GEN-LAST:event_keyPressedIpText // </editor-fold>

/* * Esse método é chamado para configurar o frame. */ // <editor-fold defaultstate="collapsed" desc="Método de configuração do Frame"> private void initFrame() { super.setTitle("CHAT JMS - Configurações"); this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); this.setModal(true);

try { //adição do icone ao programa super.setIconImage(ImageIO.read(getClass().getResource("/chat/img/icone.png"))); } catch (IOException ex) { System.err.println("Icone não encontrado!"); } }// </editor-fold> // <editor-fold defaultstate="collapsed" desc="Declaração dos Componentes do Frame"> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton aplicarBotao; private javax.swing.JPanel botaoPanel; private javax.swing.Box.Filler filler1; private javax.swing.JLabel ipLabel; private javax.swing.JPanel ipPanel; private javax.swing.JTextField ipText; private javax.swing.JPanel jPanel1; private javax.swing.JLabel nomeLabel; private javax.swing.JPanel nomePanel; private javax.swing.JTextField nomeText; private javax.swing.JPanel opcoesPanel; private javax.swing.JPanel panelPrincipal; private javax.swing.JPanel primeiraLinhaPanel; private javax.swing.JPanel segundaLinhaPanel; // End of variables declaration//GEN-END:variables // </editor-fold>}

Page 29: Tutorial jms

package chat.cdp;

import javax.persistence.Entity;import util.cgd.ObjetoPersistente;

//Classe para persistir no banco@Entitypublic class Mensagem extends ObjetoPersistente {

private String texto;

public String getTexto() { return texto; }

public void setTexto(String texto) { this.texto = texto; }}

Page 30: Tutorial jms

package chat.cgd;

import chat.cdp.Mensagem;import util.cgd.DAO;

public interface MensagemDAO extends DAO<Mensagem>{}

Page 31: Tutorial jms

package chat.cgd;

import chat.cdp.Mensagem;import util.cgd.DAOJPA;

public class MensagemDAOJPA extends DAOJPA<Mensagem> implements MensagemDAO{}

Page 32: Tutorial jms

package util.cgd;

import java.io.Serializable;import java.util.List;

/** * * @author Administrador */

public interface DAO<T> extends Serializable{ public T salvar(T obj) throws Exception; public void excluir(T obj) throws Exception; public List<T> obter(Class<T> classe) throws Exception; public T obter(Class<T> classe, Long id) throws Exception ; }

Page 33: Tutorial jms

package util.cgd;

import java.util.List;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import javax.persistence.Query;

public abstract class DAOJPA<T extends ObjetoPersistente> implements DAO<T> {

protected static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("JPA"); protected static EntityManager entityManager = entityManagerFactory.createEntityManager();

public T salvar(T obj) throws Exception {

try { // Inicia uma transação com o banco de dados. entityManager.getTransaction().begin(); // Verifica se o objeto ainda não está salvo no banco de dados. if (obj.getId() == null) { //Salva os dados do objeto. entityManager.persist(obj); } else { //Atualiza os dados do objeto. obj = entityManager.merge(obj); } // Finaliza a transação. entityManager.getTransaction().commit(); } catch (Exception e) { obj = null; System.err.println("Erro ao obter " + e); throw new Exception("Erro ao obter " + e); } return obj; }

public void excluir(T obj) throws Exception { try { // Inicia uma transação com o banco de dados.

Page 34: Tutorial jms

entityManager.getTransaction().begin(); // Remove o objeto da base de dados. entityManager.remove(obj); // Finaliza a transação. entityManager.getTransaction().commit(); } catch (Exception e) { System.err.println("Erro ao excluir " + e); throw new Exception("Erro ao excluir " + e); } }

public List<T> obter(Class<T> classe) throws Exception { List<T> lista = null; try { Query query = entityManager.createQuery("SELECT t FROM " + classe.getSimpleName() + " t"); lista = query.getResultList(); } catch (Exception e) { System.err.println("Erro ao obter " + e); throw new Exception("Erro ao obter " + e); } return lista; } @Override public T obter(Class<T> classe, Long id) throws Exception { T obj = null; try { Query query = entityManager.createQuery("SELECT t FROM " + classe.getSimpleName() + " t where id = " + id); obj = (T)query.getSingleResult(); } catch (Exception e) { System.err.println("Erro ao obter " + e); throw new Exception("Erro ao obter " + e); } return obj; }}

Page 35: Tutorial jms

package util.cgd;

import java.util.logging.Level;import java.util.logging.Logger;

public class DAOFactory { public String TIPO_JDBC = "JDBC"; public String TIPO_HIBERNATE = "Hibernate"; public String TIPO_JPA = "JPA"; private String tipoFabrica = TIPO_JPA; private static DAOFactory instance = new DAOFactory(); public static DAOFactory getInstance() { if (instance == null) instance = new DAOFactory(); return instance; } public DAO obterDAO( Class classe) { String nome = classe.getName(); nome = nome.replace("cdp", "cgd"); nome = nome + "DAO" + this.getTipoFabrica(); try { return (DAO) Class.forName(nome).newInstance(); } catch (ClassNotFoundException ex) { Logger.getLogger(DAOFactory.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(DAOFactory.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(DAOFactory.class.getName()).log(Level.SEVERE, null, ex); } return null; } public String getTipoFabrica() { return tipoFabrica; }

public void setTipoFabrica(String tipoFabrica) { this.tipoFabrica = tipoFabrica; }}

Page 36: Tutorial jms

package util.cgd;

import java.io.Serializable;import java.rmi.Remote;import javax.persistence.*;

@MappedSuperclasspublic abstract class ObjetoPersistente implements Serializable, Remote {

private Long id;

@Id @SequenceGenerator(name="seqPessoa") @GeneratedValue(generator="seqPessoa") @Column(nullable = false, unique = true) public Long getId() { return this.id; }

public void setId(Long id) { this.id = id; }

@Override public boolean equals(Object obj) {

if (obj instanceof ObjetoPersistente) { ObjetoPersistente o = (ObjetoPersistente) obj; if (this.id != null && this.id == o.id) { return true; } } return false; }}

Page 37: Tutorial jms

a.sun.com/xml/ns/persistence/persistence_2_0.xsd"<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="JPA" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.driver_class" value="org.sqlite.JDBC"/> <property name="hibernate.connection.url" value="jdbc:sqlite:chatjms.db"/> <property name="hibernate.dialect" value="util.cgd.SQLiteDialect"/> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> <property name="hibernate.show_sql" value="false"/> <property name="hibernate.format_sql" value="false"/> <!--property name="hibernate.hbm2ddl.auto" value="create"/--> </properties> </persistence-unit></persistence>