001: /*
002: * Created on 13/10/2004
003: *
004: * Swing Components - visit http://sf.net/projects/gfd
005: *
006: * Copyright (C) 2004 Igor Regis da Silva Simões
007: *
008: * This program is free software; you can redistribute it and/or
009: * modify it under the terms of the GNU General Public License
010: * as published by the Free Software Foundation; either version 2
011: * of the License, or (at your option) any later version.
012: *
013: * This program is distributed in the hope that it will be useful,
014: * but WITHOUT ANY WARRANTY; without even the implied warranty of
015: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016: * GNU General Public License for more details.
017: *
018: * You should have received a copy of the GNU General Public License
019: * along with this program; if not, write to the Free Software
020: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
021: */
022: package br.com.gfp.actions;
023:
024: import java.awt.event.ActionEvent;
025: import java.awt.event.ActionListener;
026: import java.io.DataInputStream;
027: import java.io.File;
028: import java.io.FileInputStream;
029: import java.io.FileNotFoundException;
030: import java.io.IOException;
031: import java.io.RandomAccessFile;
032: import java.sql.SQLException;
033: import java.util.ArrayList;
034: import java.util.Locale;
035: import java.util.Properties;
036: import java.util.zip.ZipEntry;
037: import java.util.zip.ZipFile;
038: import java.util.zip.ZipInputStream;
039:
040: import javax.swing.JFileChooser;
041: import javax.swing.JFrame;
042: import javax.swing.JOptionPane;
043:
044: import br.com.gfp.dao.GFPController;
045: import br.com.gfp.dao.PluginDAO;
046: import br.com.gfp.data.ConfigLocalizacao;
047: import br.com.gfp.data.Plugin;
048: import br.com.gfp.db.DBInicializador;
049: import br.com.gfp.internationalization.ActionsMessages;
050: import br.com.gfp.util.GFPProperties;
051: import br.com.gfp.util.SimpleLog;
052: import br.com.gfp.windows.GFPPrincipal;
053: import br.com.gfp.windows.TransactionWindow;
054: import br.com.gfpshare.beans.MessageView;
055: import br.com.gfpshare.beans.aplicativos.ArquivosRecentes;
056: import br.com.gfpshare.config.Propriedades;
057: import br.com.gfpshare.controllers.ArquivoDeDadosAbertoContoller;
058: import br.com.gfpshare.controllers.PropriedadesController;
059: import br.com.gfpshare.db.DataBaseManager;
060: import br.com.gfpshare.util.MyFileFilter;
061:
062: /**
063: * @author Igor Regis da Silva Simoes
064: */
065: public class AbrirDBAction implements ActionListener {
066: private static AbrirDBAction action = null;
067:
068: private JFileChooser chooser = null;
069:
070: /**
071: *
072: */
073: private AbrirDBAction() {
074: super ();
075: chooser = new JFileChooser();
076: chooser.setDialogTitle(ActionsMessages.getMessages().getString(
077: "tituloAbrirArquivoDialog"));
078: chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
079: chooser.setFileFilter(new MyFileFilter("gfp", ActionsMessages
080: .getMessages().getString("arquivoDeFinancas")));
081: }
082:
083: /**
084: * @return Retorna uma instancia desta action
085: */
086: public static AbrirDBAction getAction() {
087: return action;
088: }
089:
090: /**
091: *
092: */
093: public static void initializeAction() {
094: if (action == null)
095: action = new AbrirDBAction();
096: }
097:
098: /**
099: * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
100: */
101: public void actionPerformed(ActionEvent e) {
102: if (e != null && e.getActionCommand() != null
103: && e.getActionCommand().endsWith("gfp")) {
104: openFile(new File(e.getActionCommand()), e);
105: return;
106: }
107: chooser.updateUI();
108: if (chooser.showOpenDialog((JFrame) GFPController
109: .getGFPController().getContexto().get(
110: GFPController.FRAME_PRINCIPAL)) == JFileChooser.APPROVE_OPTION) {
111: openFile(chooser.getSelectedFile(), e);
112: }
113: }
114:
115: private void openFile(final File file, final ActionEvent e) {
116: (new Thread("AbrindoArquivo") {
117: @Override
118: public void run() {
119: MessageView messages = (MessageView) GFPController
120: .getGFPController().getContexto().get(
121: GFPController.RODAPE_MESSAGER);
122: messages = messages.showMessage(ActionsMessages
123: .getMessages().getString("AbrirArquivoTitulo"),
124: ActionsMessages.getMessages().getString(
125: "AbrirArquivoMessage"), true);
126: messages.getMessagePanel().getProgressBar()
127: .setIndeterminate(true);
128:
129: garanteDBFechado(e);
130:
131: String dirOrigem = System
132: .getProperty(GFPProperties.DIRETORIO_BANCO_DE_DADOS);
133: //Abrimos o novo arquivo
134: try {
135: ZipEntry ze = null;
136: FileInputStream fos = new FileInputStream(file);
137: ZipInputStream zis = new ZipInputStream(fos);
138: ZipFile zf = new ZipFile(file);
139:
140: while ((ze = zis.getNextEntry()) != null) {
141: DataInputStream fonte = new DataInputStream(zf
142: .getInputStream(ze));
143: byte[] data = new byte[fonte.available()];
144:
145: //String tempName = ze.getName();
146: //tempName = dirOrigem + File.separator + tempName.substring(tempName.lastIndexOf('\\') + 1);
147:
148: int lastIndex = ze.getName().lastIndexOf('/') == -1 ? ze
149: .getName().lastIndexOf('\\')
150: : ze.getName().lastIndexOf('/');
151: String fileDestino = dirOrigem + File.separator
152: + ze.getName().substring(++lastIndex);
153:
154: RandomAccessFile destino = new RandomAccessFile(
155: fileDestino, "rw");
156: fonte.readFully(data);
157: destino.write(data);
158: destino.close();
159:
160: fonte.close();
161: }
162: zf.close();
163:
164: //Abrimos conexão com o Banco de dados
165: /*AQUI VAI DAR ERRO!! QUALQUER OUTRA CHAMADA DEVE SER FEITA NO FINALLY*/
166: DBInicializador.inicializarBancoDeDados();
167:
168: } catch (FileNotFoundException e) {
169: //TODO Need internationalization (precisa de TRADUÇÃO)
170: messages.getMessagePanel().setMessage(
171: ActionsMessages.getMessages().getString(
172: "ErroAbrirArquivo"), true);
173: messages.getMessagePanel().getProgressBar()
174: .setIndeterminate(false);
175: messages.finishUse();
176:
177: try {
178: new ArquivosRecentes(System
179: .getProperty("user.dir")
180: + File.separator + "db").remove(file);
181: } catch (Exception e1) {
182: ((SimpleLog) GFPController.getGFPController()
183: .getContexto().get(GFPController.LOG))
184: .log("Erro na abertura do arquivo de financas!");
185: ((SimpleLog) GFPController.getGFPController()
186: .getContexto().get(GFPController.LOG))
187: .log(e1.getLocalizedMessage());
188: ((SimpleLog) GFPController.getGFPController()
189: .getContexto().get(GFPController.LOG))
190: .log(e1);
191: }
192:
193: JOptionPane
194: .showMessageDialog(
195: (JFrame) GFPController
196: .getGFPController()
197: .getContexto()
198: .get(
199: GFPController.FRAME_PRINCIPAL),
200: e.getLocalizedMessage());
201: } catch (IOException e) {
202: ((SimpleLog) GFPController.getGFPController()
203: .getContexto().get(GFPController.LOG))
204: .log("Erro na abertura do arquivo de financas!");
205: ((SimpleLog) GFPController.getGFPController()
206: .getContexto().get(GFPController.LOG))
207: .log(e.getLocalizedMessage());
208: ((SimpleLog) GFPController.getGFPController()
209: .getContexto().get(GFPController.LOG))
210: .log(e);
211: } catch (SQLException sqle) {
212: if (sqle.getErrorCode() != -21) {
213: ((SimpleLog) GFPController.getGFPController()
214: .getContexto().get(GFPController.LOG))
215: .log("Erro ao abrir banco de dados!");
216: ((SimpleLog) GFPController.getGFPController()
217: .getContexto().get(GFPController.LOG))
218: .log(sqle.getLocalizedMessage());
219: ((SimpleLog) GFPController.getGFPController()
220: .getContexto().get(GFPController.LOG))
221: .log(sqle);
222: }
223: } finally {
224: checaVersaoPlugins(messages);
225: finalizarAberturaDeArquivo(file, dirOrigem);
226: }
227:
228: //Guarda o nome completo do arquivo aberto
229: ArquivoDeDadosAbertoContoller.getInstance(
230: file.getAbsolutePath()).setArquivoAberto();
231:
232: //Reconstrói os menus e menubar
233: ((GFPPrincipal) GFPController.getGFPController()
234: .getContexto().get(
235: GFPController.FRAME_PRINCIPAL))
236: .buildMenusAndButtons(true);
237:
238: messages.getMessagePanel().setMessage(
239: ActionsMessages.getMessages().getString(
240: "ArquivoAberto"), true);
241: messages.getMessagePanel().getProgressBar()
242: .setIndeterminate(false);
243: messages.finishUse(30);
244:
245: GFPController.getGFPController().create(
246: TransactionWindow.class, true);
247: }
248: }).start();
249: }
250:
251: private void garanteDBFechado(ActionEvent e) {
252: if (ArquivoDeDadosAbertoContoller.getInstance(null) != null
253: && ArquivoDeDadosAbertoContoller.getInstance(null)
254: .isArquivoAberto()) {
255: FecharDBAction.getAction().actionPerformed(e);
256: }
257:
258: //Forçamos o fechamento de qualquer banco de dados que esteja aberto
259: try {
260: DataBaseManager.getDataBaseManager().executarAtualizacao(
261: "SHUTDOWN", null);
262: DataBaseManager.getDataBaseManager().fecharBancoDeDados();
263: } catch (Exception e2) {
264: // Não precisa fazer nada
265: }
266: String dbDir = System.getProperty("user.dir") + File.separator
267: + "db" + File.separator;
268: new File(dbDir + "db.script").delete();
269: new File(dbDir + "db.properties").delete();
270: new File(dbDir + "db.backup").delete();
271: new File(dbDir + "db.data").delete();
272: new File(dbDir + "gfd_db.properties").delete();
273: new File(dbDir + "db.log").delete();
274:
275: }
276:
277: /**
278: * @param file
279: * @param dirOrigem
280: */
281: private void finalizarAberturaDeArquivo(final File file,
282: String dirOrigem) {
283: try {
284: DBInicializador.inicializarDBDosPlugins();
285: } catch (Exception e1) {
286: ((SimpleLog) GFPController.getGFPController().getContexto()
287: .get(GFPController.LOG))
288: .log("Erro ao inicializar plugins DB: "
289: + e1.getLocalizedMessage());
290: ((SimpleLog) GFPController.getGFPController().getContexto()
291: .get(GFPController.LOG)).log(e1);
292: }
293:
294: try {
295: //Setamos o local Default com baso no que está configurado no arquivo .gfp
296: ConfigLocalizacao configLocalizacao = (ConfigLocalizacao) Propriedades
297: .loadPropiedades(ConfigLocalizacao.class);
298: new PropriedadesController().getBy(configLocalizacao
299: .getPersistentObject());
300: Locale localDefault = new Locale(configLocalizacao
301: .getIdioma(), configLocalizacao.getPais());
302: Locale.setDefault(localDefault);
303: } catch (SQLException e) {
304: ((SimpleLog) GFPController.getGFPController().getContexto()
305: .get(GFPController.LOG))
306: .log("Erro ao ler configuracao de idioma e pais!");
307: ((SimpleLog) GFPController.getGFPController().getContexto()
308: .get(GFPController.LOG)).log(e
309: .getLocalizedMessage());
310: ((SimpleLog) GFPController.getGFPController().getContexto()
311: .get(GFPController.LOG)).log(e);
312: }
313:
314: try {
315: new ArquivosRecentes(dirOrigem).add(file.getAbsolutePath());
316: } catch (Exception e) {
317: ((SimpleLog) GFPController.getGFPController().getContexto()
318: .get(GFPController.LOG))
319: .log("Erro ao escrever arquivos recentes!");
320: ((SimpleLog) GFPController.getGFPController().getContexto()
321: .get(GFPController.LOG)).log(e
322: .getLocalizedMessage());
323: ((SimpleLog) GFPController.getGFPController().getContexto()
324: .get(GFPController.LOG)).log(e);
325: }
326: }
327:
328: private void checaVersaoPlugins(MessageView mensagens) {
329: MessageView errorMessage = null;
330: PluginDAO controller = new PluginDAO();
331: ArrayList<Plugin> plugins = null;
332: try {
333: plugins = controller.getAllBy(new Plugin());
334: } catch (SQLException e) {
335: ((SimpleLog) GFPController.getGFPController().getContexto()
336: .get(GFPController.LOG))
337: .log("Erro ao ler configurações de plugins instalados");
338: ((SimpleLog) GFPController.getGFPController().getContexto()
339: .get(GFPController.LOG)).log(e
340: .getLocalizedMessage());
341: ((SimpleLog) GFPController.getGFPController().getContexto()
342: .get(GFPController.LOG)).log(e);
343: return;
344: }
345:
346: PluginConf conf = new PluginConf();
347:
348: for (Plugin plugin : plugins) {
349: conf.setInstallDir(plugin.getInstallDir());
350: try {
351: conf.loadFile();
352: } catch (IOException e) {
353: ((SimpleLog) GFPController.getGFPController()
354: .getContexto().get(GFPController.LOG))
355: .log("Erro ao ler configurações do plugin "
356: + plugin.getNome()
357: + " possivelmente não instalado");
358: ((SimpleLog) GFPController.getGFPController()
359: .getContexto().get(GFPController.LOG)).log(e
360: .getLocalizedMessage());
361: ((SimpleLog) GFPController.getGFPController()
362: .getContexto().get(GFPController.LOG)).log(e);
363: showPluginErrorMessage(mensagens, errorMessage,
364: ActionsMessages.getMessages().getString(
365: "ErroPluginInstalado")
366: + plugin.getNome());
367: errorMessage.getMessagePanel().piscar(true);
368: }
369:
370: if (conf.getVersao() < plugin.getVersao()) {
371: showPluginErrorMessage(mensagens, errorMessage,
372: ActionsMessages.getMessages().getString(
373: "ErroPluginInstalado")
374: + plugin.getNome());
375: showPluginErrorMessage(mensagens, errorMessage,
376: ActionsMessages.getMessages().getString(
377: "VersaoInstalada")
378: + conf.getVersao());
379: showPluginErrorMessage(mensagens, errorMessage,
380: ActionsMessages.getMessages().getString(
381: "VersaoEsperada")
382: + plugin.getVersao());
383: errorMessage.getMessagePanel().piscar(true);
384: }
385: }
386: }
387:
388: private void showPluginErrorMessage(MessageView main,
389: MessageView error, String message) {
390: if (error == null)
391: error = main.showMessage(ActionsMessages.getMessages()
392: .getString("ErroTitle"), message, false);
393: else
394: error.getMessagePanel().addMessage(message);
395: }
396:
397: /**
398: * Esta classe abstrai o acesso ao arquivo de configuração do
399: * plugin onde podemos encontrar informações a respeito
400: * da versão, versão do DB entre outras.
401: *
402: * @author Igor Regis da Silva Simoes
403: * @since 21/07/2006
404: */
405: private class PluginConf {
406: private Properties prop = new Properties();
407:
408: private String installDir = null;
409:
410: public PluginConf() {
411: //Faz nada
412: }
413:
414: /**
415: * Cria um leitor do arquivo de configuração de plugin
416: * @param installDir Diretorio de instalação do plugin
417: * @throws IOException Caso exista erro ao ler o arquivo de configuração
418: */
419: public PluginConf(String installDir) throws IOException {
420: setInstallDir(installDir);
421: loadFile();
422: }
423:
424: /**
425: * Diretorio de instalação do plugin
426: * @param installDir
427: */
428: public void setInstallDir(String installDir) {
429: this .installDir = installDir;
430: }
431:
432: /**
433: * Le o arquivo de configuração do plugin
434: * @throws IOException
435: */
436: public void loadFile() throws IOException {
437: FileInputStream is = new FileInputStream(System
438: .getProperty("user.dir")
439: + File.separator
440: + "plugins"
441: + File.separator
442: + installDir + File.separator + "plugin.conf");
443: prop.load(is);
444: is.close();
445: }
446:
447: /**
448: * Retorna a versão atualmente instalada do plugin
449: * @return String
450: */
451: public double getVersao() {
452: return Double.parseDouble(prop.getProperty("release"));
453: }
454: }
455: }
|