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.action;
17
18 import java.awt.event.ActionEvent;
19 import java.io.*;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import javax.swing.AbstractAction;
23 import javax.swing.JOptionPane;
24 import javax.swing.JTable;
25 import net.sf.webphotos.Album;
26 import net.sf.webphotos.gui.PainelWebFotos;
27 import net.sf.webphotos.gui.util.TableModelFoto;
28 import net.sf.webphotos.gui.util.TableSorter;
29 import net.sf.webphotos.util.Util;
30 import org.apache.log4j.Logger;
31
32 /**
33 * Exclui fotos. Possui os dados tabela de fotos e largura da coluna de fotos.
34 * Seu construtor seta esses dados para serem utilizados posteriormente pelo
35 * método que implementa a ação.
36 */
37 public class AcaoExcluirFoto extends AbstractAction {
38
39 /**
40 *
41 */
42 private static final long serialVersionUID = -6690995860578985531L;
43 private static final Logger log = Logger.getLogger(AcaoExcluirFoto.class);
44 private JTable tbFotos;
45 private String larguraColunasFotos;
46
47 /**
48 * Construtor da classe. Seta os valores da tabela de fotos por um parâmetro
49 * recebido e através da tabela seta o valor da largura da coluna.
50 *
51 * @param tabela Tabela de fotos.
52 */
53 public AcaoExcluirFoto(JTable tabela) {
54 tbFotos = tabela;
55 larguraColunasFotos = Util.getConfig().getString("colunas2");
56 }
57
58 /**
59 * Método responsável pela exclusão de fotos. Identifica os IDs e nomes das
60 * fotos selecionadas. Armazena quais e quantas linhas foram selecionadas.
61 * Checa se existe apenas uma foto no albúm e mostra ao usuário que se a
62 * foto for excluída, o albúm também será. Pede confirmação e efetua a ação.
63 * Faz um controle de exclusão de no máximo 20 fotos por vez. Lista os
64 * albúns selecionados ao usuário e pede uma confirmação de exclusão. Caso o
65 * usuário confirme, exclui as fotos selecionadas com o método
66 * {@link net.sf.webphotos.Album#excluirFotos(int[]) excluirFotos(albunsID)}
67 * da classe Album. Ao ser iniciado o método que implementa a ação, checa se
68 * a foto não é recente, se já possui registro no banco. Então cria um array
69 * com os IDs das fotos. Cria um arquivo javascript. E por último atualiza a
70 * lista e área das fotos no programa.
71 *
72 * @param e Evento de ação de exclusão de fotos.
73 */
74 @Override
75 public void actionPerformed(ActionEvent e) {
76 HashSet<String> fotosID = new HashSet<String>();
77 HashSet<String> nomesArquivos = new HashSet<String>();
78 int[] linhasSelecionadas = tbFotos.getSelectedRows();
79 int numeroLinhasSelecionadas = tbFotos.getSelectedRowCount();
80 String msg = "";
81
82 if (tbFotos.getRowCount() == 1) {
83 int retorno = JOptionPane.showConfirmDialog(null,
84 "Esta é a última foto deste álbum.\nExcluir essa foto irá excluir seu álbum.",
85 "Excluir álbum ?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
86 if (retorno == 0) {
87 // exclui o álbum e retorna
88 Util.out.println("remove album: " + Album.getAlbum().getAlbumID());
89 return;
90 }
91 // usuário preferiu não excluir a última foto (e o álbum também)
92 return;
93 }
94 // permite somente a exclusão de 20 fotos de cada vez
95 if (numeroLinhasSelecionadas > 20 || numeroLinhasSelecionadas == 0) {
96 JOptionPane.showMessageDialog(null,
97 "Você deve selecionar entre 1 e 20 fotos\npara serem excluídas", "Informação",
98 JOptionPane.INFORMATION_MESSAGE);
99 return;
100 }
101
102 // pede confirmacao
103 for (int i = 0; i < numeroLinhasSelecionadas; i++) {
104 msg = msg + "\n" + tbFotos.getModel().getValueAt(linhasSelecionadas[i], 0) + " - " + tbFotos.getModel().getValueAt(linhasSelecionadas[i], 1);
105 }
106
107 if (numeroLinhasSelecionadas == 1) {
108 msg = "Confirma a exclusão da foto ?\n" + msg;
109 } else {
110 msg = "Confirma a exclusão de " + numeroLinhasSelecionadas + " fotos ?\n" + msg;
111 }
112 int confirmacao = JOptionPane.showConfirmDialog(null, msg, "Confirmação de exclusão", JOptionPane.WARNING_MESSAGE);
113
114 // apaga a foto
115 if (confirmacao == 0) {
116 // primeiro checa se o usuário não está excluindo fotos que
117 // acabou de adicionar (nesse caso não tem entrada em db)
118 String indice = "";
119
120 for (int i = 0; i < numeroLinhasSelecionadas; i++) {
121 indice = tbFotos.getModel().getValueAt(linhasSelecionadas[i], 0).toString();
122
123 // se acaba com jpg então não é numero
124 if (indice.toLowerCase().endsWith(".jpg")) {
125 nomesArquivos.add(indice);
126 } else {
127 fotosID.add(indice);
128 }
129 }
130
131 Album album = Album.getAlbum();
132
133 // monta os arrays para passar ao album
134 if (nomesArquivos.size() > 0) {
135 // passa na forma de um array de strings
136 Util.out.println("nomesArquivos: " + nomesArquivos.toString());
137 album.excluirFotos((String[]) nomesArquivos.toArray(new String[nomesArquivos.size()]));
138 }
139
140 if (fotosID.size() > 0) {
141 // passa na forma de um array de int
142 Iterator<String> iter = fotosID.iterator();
143 int[] fotoID = new int[fotosID.size()];
144 int ct = 0;
145 while (iter.hasNext()) {
146 fotoID[ct] = Integer.parseInt(iter.next().toString());
147 ct++;
148 }
149
150 album.excluirFotos(fotoID);
151
152 // escreve o arquivo javaScript
153 String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + album.getAlbumID();
154 try {
155 FileWriter out = new FileWriter(caminhoAlbum + File.separator + album.getAlbumID() + ".js");
156 out.write(album.toJavaScript());
157 out.flush();
158 Util.out.println("escrevendo: " + album.toJavaScript());
159
160 } catch (IOException ex) {
161 log.error(ex);
162 }
163 }
164
165 // atualiza o modelo
166 // aqui o codigo que atualiza a tabela
167 TableModelFoto.getModel().update();
168 TableModelFoto.getModel().fireTableDataChanged();
169 //TableModelFoto.getModel().addMouseListener(tbFotos);
170 //tbFotos.setModel(TableModelFoto.getModel());
171 tbFotos.setModel(new TableSorter(TableModelFoto.getModel(), tbFotos.getTableHeader()));
172
173 // ajusta colunas
174 Util.ajustaLargura(tbFotos, larguraColunasFotos);
175 tbFotos.repaint();
176
177 // limpa controle de foto
178 PainelWebFotos.resetFoto();
179 }
180 }
181 }