View Javadoc

1   /**
2    * Copyright 2008 WebPhotos
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package net.sf.webphotos.gui.util;
17  
18  // Modelo de tabela para bases de dados com suporte a cursores rolantes (MYSQL)
19  import java.util.List;
20  import javax.sql.RowSetEvent;
21  import javax.sql.RowSetListener;
22  import javax.swing.JOptionPane;
23  import javax.swing.table.AbstractTableModel;
24  import net.sf.webphotos.dao.jpa.AlbumDAO;
25  import net.sf.webphotos.util.ApplicationContextResource;
26  import org.apache.log4j.Logger;
27  
28  /**
29   * Gera o modelo da tabela de albuns.
30   */
31  public class TableModelAlbum extends AbstractTableModel implements RowSetListener {
32  
33      private static final long serialVersionUID = 8393087620197315052L;
34      private static final TableModelAlbum instancia = new TableModelAlbum();
35      private String ultimoSQL;
36      
37      private List<Object[]> tableData = null;
38      private static Logger log = Logger.getLogger(TableModelAlbum.class);
39      private static AlbumDAO albunsDAO = (AlbumDAO) ApplicationContextResource.getBean("albunsDAO");
40  
41      // construtor
42      private TableModelAlbum() {
43          super();
44      }
45  
46      /**
47       * Retorna a instância da própria classe.
48       *
49       * @return Retorna um TableModelAlbum.
50       */
51      public static TableModelAlbum getModel() {
52          return instancia;
53      }
54  
55      /**
56       * Repassa para a função {@link java.util.TableModelAlbum#update(String) update(String sql)}
57       * enviando a variavel últimoSQL como parametro.
58       */
59      public void update() {
60          update(getUltimoSQL());
61      }
62  
63      /**
64       * Executa um update no banco. Caso ocorra algum problema, o sistema tenta
65       * reconectar ao Banco de Dados. Recebe uma variável para realizar um
66       * comando no banco.
67       *
68       * @param sql Comando de sql.
69       */
70      public void update(String sql) {
71          try {
72              ultimoSQL = sql;
73              log.debug("Executando - " + ultimoSQL);
74              tableData = albunsDAO.findByNativeQuery(ultimoSQL);
75          } catch (Exception ex) {
76              log.error("Ocorreu um erro durante a leitura do álbum no banco de dados", ex);
77              int selecao = JOptionPane.showConfirmDialog(null,
78                      "ERRO durante leitura do álbum no banco de dados.\n\nTentar Novamente?",
79                      "Aviso!",
80                      JOptionPane.YES_NO_OPTION,
81                      JOptionPane.WARNING_MESSAGE);
82              if (selecao == JOptionPane.YES_OPTION) {
83                  update(sql);
84              } else {
85                  log.error("Ocorreu um erro inexperado durante a leitura do álbum", ex);
86                  JOptionPane.showMessageDialog(null, "ERRO inexperado durante leitura do álbum - " + ex.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
87                  throw new RuntimeException("Ocorreu um erro inexperado durante a leitura do álbum", ex);
88              }
89          }
90      }
91  
92      /**
93       * Retorna o nome de uma coluna.
94       * @param col Número da coluna.
95       * @return Retorna o nome da coluna.
96       */
97      @Override
98      public String getColumnName(int col) {
99          try {
100             return albunsDAO.createNativeQuery(ultimoSQL).getParameter(col).getName();
101         } catch (Exception e) {
102             log.error("Error trying to get column name", e);
103             return "Error";
104         }
105     }
106 
107     /**
108      * Retorna o número de colunas.
109      *
110      * @return Retorna o numero de colunas.
111      */
112     @Override
113     public int getColumnCount() {
114         try {
115             return albunsDAO.createNativeQuery(ultimoSQL).getParameters().size();
116         } catch (Exception e) {
117             log.error("Error trying to get column count", e);
118             return 0;
119         }
120     }
121 
122     /**
123      * Retorna o número de linhas.
124      *
125      * @return Retorna o número de linhas.
126      */
127     @Override
128     public int getRowCount() {
129         try {
130             return albunsDAO.createNativeQuery(ultimoSQL).getResultList().size();
131         } catch (Exception e) {
132             log.error("Error trying to get row count", e);
133             return 0;
134         }
135     }
136 
137     /**
138      * Obtém o valor na tabela. Faz a procura através da linha e coluna.
139      *
140      * @param row Número da linha.
141      * @param col Número da coluna.
142      * @return Retorna o valor na tabela.
143      */
144     @Override
145     public Object getValueAt(int row, int col) {
146         try {
147             return tableData.get(row)[col];
148         } catch (Exception e) {
149             log.error("Error trying to get value at (" + row + "," + col + ")", e);
150             return null;
151         }
152     }
153 
154     /**
155      * Retorna o valor false. Recebe os valores numéricos da linha e coluna,
156      * porém Não os utiliza. TODO: avaliar a funcionalidade desse método.
157      *
158      * @param l Número da linha.
159      * @param c Número da coluna.
160      * @return Retorna <I>false</I>.
161      */
162     @Override
163     public boolean isCellEditable(int l, int c) {
164         log.debug("Coordinates(" + l + "," + c + ")");
165         return false;
166     }
167 
168     /**
169      * Busca qual o tipo de uma coluna especifica e retorna sua classe. Recebe
170      * um valor numerico para indicar a coluna e busca os dados atraves do
171      * método {@link java.sql.ResultSet#getMetaData() getMetaData()}.
172      *
173      * @param column Numero da coluna.
174      * @return Retorna uma classe.
175      */
176     @Override
177     public Class<?> getColumnClass(int column) {
178         try {
179             return albunsDAO.createNativeQuery(ultimoSQL).getParameter(column).getParameterType();
180         } catch (Exception e) {
181             log.warn("Error getting column class, returning SuperType information", e);
182             return super.getColumnClass(column);
183         }
184     }
185 
186     /**
187      * Retorna o valor de ultimoSQL.
188      *
189      * @return Retorna um comando SQL.
190      */
191     public String getUltimoSQL() {
192         return ultimoSQL;
193     }
194 
195     /**
196      * Seta o valor de ultimoSQL.
197      *
198      * @param ultimoSQL Comando de SQL.
199      */
200     public void setUltimoSQL(String ultimoSQL) {
201         this.ultimoSQL = ultimoSQL;
202     }
203 
204     /**
205      * Notifica aos listenners que a estrutura da tabela foi modificada. Apenas
206      * chama o método {@link javax.swing.table.AbstractTableModel#fireTableStructureChanged() fireTableStructureChanged()}.
207      *
208      * @param event Evento de ação na tabela.
209      */
210     @Override
211     public void rowSetChanged(RowSetEvent event) {
212         fireTableStructureChanged();
213     }
214 
215     /**
216      * Notifica que a estrutura da tabela foi modificada, porém informa qual a
217      * função foi feita (insert, delete ou update).
218      *
219      * @param event Evento de ação na tabela.
220      */
221     @Override
222     public void rowChanged(RowSetEvent event) {
223         fireTableDataChanged();
224     }
225 
226     /**
227      * Não possui corpo. TODO: avaliar a exclusão dessa função.
228      *
229      * @param event Evento.
230      */
231     @Override
232     public void cursorMoved(RowSetEvent event) {
233     }
234 }