1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.chainsaw;
19
20 import org.apache.log4j.chainsaw.icons.ChainsawIcons;
21 import org.apache.log4j.helpers.LogLog;
22 import org.apache.log4j.xml.XMLLayout;
23
24 import javax.swing.*;
25 import java.awt.*;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.KeyEvent;
28 import java.io.*;
29 import java.util.List;
30 import java.util.Locale;
31 import java.util.zip.ZipEntry;
32 import java.util.zip.ZipOutputStream;
33
34
35
36
37
38
39
40
41
42
43 class FileSaveAction extends AbstractAction {
44 private LogUI parent;
45 private JFileChooser chooser = null;
46
47
48
49
50
51 public FileSaveAction(LogUI parent) {
52 super("Save displayed events as...");
53
54 putValue(
55 Action.ACCELERATOR_KEY,
56 KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
57 putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
58 putValue(
59 Action.SHORT_DESCRIPTION, "Saves displayed events for the current tab");
60 putValue(Action.SMALL_ICON, new ImageIcon(ChainsawIcons.FILE_SAVE_AS));
61 this.parent = parent;
62 }
63
64
65
66
67
68
69
70
71 public void actionPerformed(ActionEvent e) {
72
73 if (chooser == null) {
74 chooser = new JFileChooser();
75 }
76
77 chooser.setAcceptAllFileFilterUsed(true);
78 chooser.setDialogTitle("Save displayed events (XML or .zipped XML)...");
79 chooser.showSaveDialog(parent);
80
81 File selectedFile = chooser.getSelectedFile();
82
83 if (selectedFile != null) {
84 List v = parent.getCurrentLogPanel().getFilteredEvents();
85
86 if (((v != null) && (v.size() == 0)) || (v == null)) {
87
88 return;
89 }
90
91 XMLLayout layout = new XMLLayout();
92 layout.setProperties(true);
93 boolean saveAsZip = selectedFile.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip");
94 Writer writer = null;
95 try {
96 if (saveAsZip) {
97 ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile)));
98 ZipEntry entry = new ZipEntry(selectedFile.getName().substring(0, selectedFile.getName().length() - ".zip".length()) + ".xml");
99 zipOutput.putNextEntry(entry);
100 writer = new OutputStreamWriter(zipOutput);
101 } else {
102 writer = new BufferedWriter(new FileWriter(selectedFile));
103 }
104 for (Object aV : v) {
105 LoggingEventWrapper loggingEventWrapper = (LoggingEventWrapper) aV;
106 layout.setLocationInfo(loggingEventWrapper.getLoggingEvent().getThrowableInformation() != null);
107 writer.write(layout.format(loggingEventWrapper.getLoggingEvent()));
108 }
109 } catch (IOException ioe) {
110 LogLog.warn("Unable to save file", ioe);
111 } finally {
112 if (writer != null) {
113 try {
114 writer.flush();
115 writer.close();
116 } catch (IOException e1) {
117
118 }
119 }
120 }
121 }
122 }
123 }