-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathMainPanel.java
More file actions
301 lines (270 loc) · 9.89 KB
/
MainPanel.java
File metadata and controls
301 lines (270 loc) · 9.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.swing.*;
public final class MainPanel extends JPanel {
public static final String LOGGER_NAME = MethodHandles.lookup().lookupClass().getName();
private static final Logger LOGGER = Logger.getLogger(LOGGER_NAME);
private MainPanel() {
super(new BorderLayout());
LOGGER.setUseParentHandlers(false);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
LOGGER.addHandler(new TextAreaHandler(new TextAreaOutputStream(textArea)));
JPanel p = new JPanel(new GridLayout(2, 1, 10, 10));
p.add(makeZipPanel());
p.add(makeUnzipPanel());
add(p, BorderLayout.NORTH);
add(new JScrollPane(textArea));
setPreferredSize(new Dimension(320, 240));
}
private Component makeZipPanel() {
JTextField field = new JTextField(20);
JButton button = new JButton("select directory");
button.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int ret = fileChooser.showOpenDialog(button.getRootPane());
if (ret == JFileChooser.APPROVE_OPTION) {
field.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
});
JButton button1 = new JButton("zip");
button1.addActionListener(e -> {
String str = field.getText();
Path path = Paths.get(str);
// Files.notExists(path) noticeably poor performance in JDK 8
if (!str.isEmpty() && path.toFile().exists()) {
String name = path.getFileName() + ".zip";
zip(path, path.resolveSibling(name));
}
});
JPanel p = new JPanel(new BorderLayout(5, 2));
p.setBorder(BorderFactory.createTitledBorder("Zip"));
p.add(field);
p.add(button, BorderLayout.EAST);
p.add(button1, BorderLayout.SOUTH);
return p;
}
private void zip(Path path, Path tgt) {
// noticeably poor performance in JDK 8
// if (Files.exists(tgt)) {
Component p = getRootPane();
if (tgt.toFile().exists()) {
String s1 = String.format("%s already exists.", tgt);
String s2 = "Do you want to overwrite it?";
String m = String.format("<html>%s<br>%s", s1, s2);
int rv = JOptionPane.showConfirmDialog(p, m, "Zip", JOptionPane.YES_NO_OPTION);
if (rv != JOptionPane.YES_OPTION) {
return;
}
}
try {
ZipUtils.zip(path, tgt);
} catch (IOException ex) {
LOGGER.info(() -> String.format("Cant zip! : %s", path));
UIManager.getLookAndFeel().provideErrorFeedback(p);
}
}
private Component makeUnzipPanel() {
JTextField field = new JTextField(20);
JButton button = new JButton("select .zip file");
button.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
int ret = fileChooser.showOpenDialog(button.getRootPane());
if (ret == JFileChooser.APPROVE_OPTION) {
field.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
});
JButton button1 = new JButton("unzip");
button1.addActionListener(e -> {
String str = field.getText();
makeTargetDirPath(str).ifPresent(dir -> unzip(Paths.get(str), dir));
});
JPanel p = new JPanel(new BorderLayout(5, 2));
p.setBorder(BorderFactory.createTitledBorder("Unzip"));
p.add(field);
p.add(button, BorderLayout.EAST);
p.add(button1, BorderLayout.SOUTH);
return p;
}
private void unzip(Path path, Path dir) {
Component p = getRootPane();
try {
// noticeably poor performance in JDK 8
// if (Files.exists(dir)) {
if (dir.toFile().exists()) {
String s1 = String.format("%s already exists.", dir);
String s2 = "Do you want to overwrite it?";
String m = String.format("<html>%s<br>%s", s1, s2);
int rv = JOptionPane.showConfirmDialog(p, m, "Unzip", JOptionPane.YES_NO_OPTION);
if (rv != JOptionPane.YES_OPTION) {
return;
}
} else {
LOGGER.info(() -> String.format("mkdir0: %s", dir));
Files.createDirectories(dir);
}
ZipUtils.unzip(path, dir);
} catch (IOException ex) {
// ex.printStackTrace();
LOGGER.info(() -> String.format("Cant unzip! : %s", path));
UIManager.getLookAndFeel().provideErrorFeedback(p);
}
}
private static Optional<Path> makeTargetDirPath(String text) {
Optional<Path> op;
Path path = Paths.get(text);
// noticeably poor performance in JDK 8
// if (str.isEmpty() || Files.notExists(path)) {
if (text.isEmpty() || !path.toFile().exists()) {
op = Optional.empty();
} else {
String name = Objects.toString(path.getFileName());
int lastDotPos = name.lastIndexOf('.');
if (lastDotPos > 0) {
name = name.substring(0, lastDotPos);
}
op = Optional.of(path.resolveSibling(name));
}
return op;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException ignored) {
Toolkit.getDefaultToolkit().beep();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getGlobal().severe(ex::getMessage);
return;
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
final class ZipUtils {
private static final Logger LOGGER = Logger.getLogger(MainPanel.LOGGER_NAME);
private ZipUtils() {
/* HideUtilityClassConstructor */
}
public static void zip(Path srcDir, Path zip) throws IOException {
// noticeably poor performance in JDK 8
// try (Stream<Path> s = Files.walk(srcDir).filter(Files::isRegularFile)) {
try (Stream<Path> s = Files.walk(srcDir).filter(f -> f.toFile().isFile())) {
// Java 16: List<Path> files = s.toList();
List<Path> files = s.collect(Collectors.toList());
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zip))) {
for (Path path : files) {
String relativePath = srcDir.relativize(path).toString().replace('\\', '/');
LOGGER.info(() -> String.format("zip: %s", relativePath));
zos.putNextEntry(createZipEntry(relativePath));
Files.copy(path, zos);
zos.closeEntry();
}
}
}
}
private static ZipEntry createZipEntry(String name) {
return new ZipEntry(name);
}
public static void unzip(Path zipFilePath, Path targetDir) throws IOException {
try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) {
for (ZipEntry zipEntry : Collections.list(zipFile.entries())) {
String name = zipEntry.getName();
Path path = targetDir.resolve(name);
if (name.endsWith("/")) { // if (Files.isDirectory(path)) {
LOGGER.info(() -> String.format("mkdir1: %s", path));
Files.createDirectories(path);
} else {
Path parent = path.getParent();
// noticeably poor performance in JDK 8
// if (Objects.nonNull(parent) && Files.notExists(parent)) {
if (Objects.nonNull(parent) && !parent.toFile().exists()) {
LOGGER.info(() -> String.format("mkdir2: %s", parent));
Files.createDirectories(parent);
}
LOGGER.info(() -> String.format("copy: %s", path));
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}
}
class TextAreaOutputStream extends OutputStream {
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final JTextArea textArea;
protected TextAreaOutputStream(JTextArea textArea) {
super();
this.textArea = textArea;
}
// // Java 10:
// @Override public void flush() {
// textArea.append(buffer.toString(StandardCharsets.UTF_8));
// buffer.reset();
// }
@Override public void flush() throws IOException {
textArea.append(buffer.toString("UTF-8"));
buffer.reset();
}
@Override public void write(int b) {
buffer.write(b);
}
@Override public void write(byte[] b, int off, int len) {
buffer.write(b, off, len);
}
}
class TextAreaHandler extends StreamHandler {
protected TextAreaHandler(OutputStream os) {
super(os, new SimpleFormatter());
}
@Override public String getEncoding() {
return StandardCharsets.UTF_8.name();
}
// [UnsynchronizedOverridesSynchronized]
// Unsynchronized method publish overrides synchronized method in StreamHandler
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
@Override public synchronized void publish(LogRecord logRecord) {
super.publish(logRecord);
flush();
}
// [UnsynchronizedOverridesSynchronized]
// Unsynchronized method close overrides synchronized method in StreamHandler
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
@Override public synchronized void close() {
flush();
}
}