summaryrefslogtreecommitdiff
path: root/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils
diff options
context:
space:
mode:
Diffstat (limited to 'pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils')
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/FileUploadSource.java57
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/LocaleSerializer.java59
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/SWTUtils.java235
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/UpdateCheckManager.java110
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/VersionComparator.java101
-rw-r--r--pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/Zipper.java128
6 files changed, 0 insertions, 690 deletions
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/FileUploadSource.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/FileUploadSource.java
deleted file mode 100644
index b0ff16ea..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/FileUploadSource.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2012 by A-SIT, Secure Information Technology Center Austria
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://joinup.ec.europa.eu/software/page/eupl
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- */
-package at.asit.pdfover.gui.utils;
-
-// Imports
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.commons.httpclient.methods.multipart.PartSource;
-
-import at.asit.pdfover.signer.DocumentSource;
-
-/**
- *
- */
-public class FileUploadSource implements PartSource {
-
- private DocumentSource source;
-
- /**
- * Constructor
- *
- * @param source
- * the source
- */
- public FileUploadSource(DocumentSource source) {
- this.source = source;
- }
-
- @Override
- public long getLength() {
- return this.source.getLength();
- }
-
- @Override
- public String getFileName() {
- return "sign.pdf";
- }
-
- @Override
- public InputStream createInputStream() throws IOException {
- return this.source.getInputStream();
- }
-}
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/LocaleSerializer.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/LocaleSerializer.java
deleted file mode 100644
index 5d90ae6f..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/LocaleSerializer.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2012 by A-SIT, Secure Information Technology Center Austria
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://joinup.ec.europa.eu/software/page/eupl
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- */
-package at.asit.pdfover.gui.utils;
-
-// Imports
-import java.util.Locale;
-
-import javax.annotation.Nonnull;
-
-import at.asit.pdfover.commons.Constants;
-
-/**
- *
- */
-public class LocaleSerializer {
- /**
- * Parse a locale from a string
- * @param localeString the string
- * @return the locale
- */
- public static Locale parseFromString(String localeString) {
-
- if(localeString == null || localeString.isEmpty()) {
- return null;
- }
-
- Locale targetLocale = null;
- Locale[] locale = Locale.getAvailableLocales();
- for(int i = 0; i < locale.length; i++) {
- if(locale[i].toString().equals(localeString)) {
- targetLocale = locale[i];
- break;
- }
- }
- return targetLocale;
- }
-
- /**
- * creates a parsable string for a locale
- * @param locale the locale
- * @return the parsable string
- */
- public static @Nonnull String getParsableString(Locale locale) {
- return Constants.ISNOTNULL(locale.toString());
- }
-}
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/SWTUtils.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/SWTUtils.java
deleted file mode 100644
index 22e52467..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/SWTUtils.java
+++ /dev/null
@@ -1,235 +0,0 @@
-package at.asit.pdfover.gui.utils;
-
-import java.awt.Desktop;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.function.Consumer;
-
-import javax.annotation.Nullable;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.program.Program;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Event;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import at.asit.pdfover.commons.Messages;
-
-public final class SWTUtils {
-
- private static final Logger log = LoggerFactory.getLogger(SWTUtils.class);
-
- /* oh how i miss C++, and compile-time safety; this would be so much cleaner as a templated function */
- private static void genericSetText(Object swtObj, String text) {
- try {
- Method m = swtObj.getClass().getMethod("setText", String.class);
- m.invoke(swtObj, text);
- } catch (NoSuchMethodException | IllegalAccessException e) {
- log.error("Attempted to setLocalizedText on object of type {}, which does not have an accessible setText method", swtObj.getClass().getSimpleName(), e);
- } catch (InvocationTargetException e) {
- log.error("Failed to setLocalizedText on object of type {}", swtObj.getClass().getSimpleName(), e);
- }
-
- try {
- // request re-layout if possible, changing the text content will change the bounding box
- Method m = swtObj.getClass().getMethod("requestLayout");
- m.invoke(swtObj);
- } catch (NoSuchMethodException | IllegalAccessException e) {
- // do nothing, this may not exist on every control we use
- } catch (InvocationTargetException e) {
- log.error("Failed to re-layout {}", swtObj.getClass().getSimpleName(), e);
- }
- }
- public static void setLocalizedText(Object o, String messageKey) { genericSetText(o, Messages.getString(messageKey)); }
- public static void setLocalizedText(Object o, String formatMessageKey, Object... formatArgs) { genericSetText(o, Messages.formatString(formatMessageKey, formatArgs)); }
-
- private static void genericSetToolTipText(Object swtObj, String text) {
- try {
- Method m = swtObj.getClass().getMethod("setToolTipText", String.class);
- m.invoke(swtObj, text);
- } catch (NoSuchMethodException | IllegalAccessException e) {
- log.error("Attempted to setLocalizedToolTipText on object of type {}, which does not have an accessible setToolTipText method", swtObj.getClass().getSimpleName(), e);
- } catch (InvocationTargetException e) {
- log.error("Failed to setLocalizedToolTipText on object of type {}", swtObj.getClass().getSimpleName(), e);
- }
- }
- public static void setLocalizedToolTipText(Object o, String messageKey) { genericSetToolTipText(o, Messages.getString(messageKey));}
-
- public static void disableEventDefault(Control c, int event) {
- c.addListener(event, (Event e) -> { e.doit = false; });
- }
-
- public static void scrollPassthrough(Control c) {
- c.addListener(SWT.MouseVerticalWheel, (Event e) -> {
- // disable default handling
- e.doit = false;
-
- // find containing ScrolledComposite
- Composite target = c.getParent();
- while ((target != null) && !(target instanceof ScrolledComposite))
- target = target.getParent();
-
- if (target == null)
- return;
-
- // scroll containing ScrolledComposite
- ScrolledComposite sTarget = (ScrolledComposite)target;
- Point origin = sTarget.getOrigin();
- origin.y -= (e.count * 10);
- sTarget.setOrigin(origin);
- });
- }
-
- public static void setFontHeight(Control c, int height) {
- FontData[] fD = c.getFont().getFontData();
- fD[0].setHeight(height);
- Font font = new Font(c.getDisplay(), fD[0]);
- c.setFont(font);
- }
-
- public static void setFontStyle(Control c, int style) {
- FontData[] fD = c.getFont().getFontData();
- fD[0].setStyle(style);
- Font font = new Font(c.getDisplay(), fD[0]);
- c.setFont(font);
- }
-
- public static class AnchorSetter {
- private final Control c;
- private final FormData fd;
- private AnchorSetter(Control c, boolean isNew)
- {
- this.c = c;
- if (isNew) {
- this.fd = new FormData();
- this.c.setLayoutData(this.fd);
- } else {
- Object layoutData = this.c.getLayoutData();
- try {
- this.fd = (FormData)layoutData;
- } catch (ClassCastException e) {
- log.error("Tried to reanchor() object with layout data of type {} (not FormData)", layoutData.getClass().getSimpleName(), e);
- throw new RuntimeException("Invalid reanchor() use");
- }
- }
- }
-
- public AnchorSetter height(int h) { fd.height = h; return this; }
- public AnchorSetter width(int w) { fd.width = w; return this; }
-
- public AnchorSetter top(FormAttachment a) { fd.top = a; return this; }
- public AnchorSetter left(FormAttachment a) { fd.left = a; return this; }
- public AnchorSetter right(FormAttachment a) { fd.right = a; return this; }
- public AnchorSetter bottom(FormAttachment a) { fd.bottom = a; return this; }
-
- public AnchorSetter top(Control control, int offset, int alignment) { return top(new FormAttachment(control, offset, alignment)); }
- public AnchorSetter top(Control control, int offset) { return top(new FormAttachment(control, offset)); }
- public AnchorSetter top(Control control) { return top(new FormAttachment(control)); }
- public AnchorSetter top(int num, int offset) { return top(new FormAttachment(num, offset)); }
- public AnchorSetter top(int num) { return top(new FormAttachment(num)); }
-
- public AnchorSetter left(Control control, int offset, int alignment) { return left(new FormAttachment(control, offset, alignment)); }
- public AnchorSetter left(Control control, int offset) { return left(new FormAttachment(control, offset)); }
- public AnchorSetter left(Control control) { return left(new FormAttachment(control)); }
- public AnchorSetter left(int num, int offset) { return left(new FormAttachment(num, offset)); }
- public AnchorSetter left(int num) { return left(new FormAttachment(num)); }
-
- public AnchorSetter right(Control control, int offset, int alignment) { return right(new FormAttachment(control, offset, alignment)); }
- public AnchorSetter right(Control control, int offset) { return right(new FormAttachment(control, offset)); }
- public AnchorSetter right(Control control) { return right(new FormAttachment(control)); }
- public AnchorSetter right(int num, int offset) { return right(new FormAttachment(num, offset)); }
- public AnchorSetter right(int num) { return right(new FormAttachment(num)); }
-
- public AnchorSetter bottom(Control control, int offset, int alignment) { return bottom(new FormAttachment(control, offset, alignment)); }
- public AnchorSetter bottom(Control control, int offset) { return bottom(new FormAttachment(control, offset)); }
- public AnchorSetter bottom(Control control) { return bottom(new FormAttachment(control)); }
- public AnchorSetter bottom(int num, int offset) { return bottom(new FormAttachment(num, offset)); }
- public AnchorSetter bottom(int num) { return bottom(new FormAttachment(num)); }
- }
- public static AnchorSetter anchor(Control c) { return new AnchorSetter(c, true); }
- public static AnchorSetter reanchor(Control c) { return new AnchorSetter(c, false); }
-
- /**
- * functional-interface wrapper around swtObj.addSelectionListener
- * @param swtObj SWT widget supporting addSelectionListener
- * @param callback widgetSelected method
- */
- public static void addSelectionListener(Object swtObj, Consumer<SelectionEvent> callback) {
- try {
- Method m = swtObj.getClass().getMethod("addSelectionListener", SelectionListener.class);
- m.invoke(swtObj, new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { callback.accept(e); } });
- } catch (NoSuchMethodException | IllegalAccessException e) {
- log.error("Attempted to pass object of type {} to addSelectionListener; object does not have an accessible addSelectionListener method", swtObj.getClass().getSimpleName(), e);
- } catch (InvocationTargetException e) {
- log.error("Failed to add selection listener on object of type {}", swtObj.getClass().getSimpleName(), e);
- }
- }
-
- /**
- * @see SWTUtils#addSelectionListener(Object, Consumer)
- */
- public static void addSelectionListener(Object swtObj, Runnable callback) {
- addSelectionListener(swtObj, (e) -> { callback.run(); });
- }
-
- /**
- * functional-interface wrapper around swtObj.addMouseListener
- * @param swtObj SWT widget supporting addMouseListener
- * @param callback mouseDown method
- */
- public static void addMouseDownListener(Object swtObj, Consumer<MouseEvent> callback) {
- try {
- Method m = swtObj.getClass().getMethod("addMouseListener", MouseListener.class);
- m.invoke(swtObj, new MouseAdapter() { @Override public void mouseDown (MouseEvent e) { callback.accept(e); } });
- } catch (NoSuchMethodException | IllegalAccessException e) {
- log.error("Attempted to pass object of type {} to addMouseDownListener; object does not have an accessible addMouseListener method", swtObj.getClass().getSimpleName(), e);
- } catch (InvocationTargetException e) {
- log.error("Failed to add selection listeer on object of type {}", swtObj.getClass().getSimpleName(), e);
- }
- }
-
- /**
- * @see SWTUtils#addMouseDownListener(Object, Consumer)
- */
- public static void addMouseDownListener(Object swtObj, Runnable callback) {
- addMouseDownListener(swtObj, (e) -> { callback.run(); });
- }
-
- public static void openURL(@Nullable URI uri) {
- try {
- if (uri == null) return;
- if (Desktop.isDesktopSupported()) {
- Desktop.getDesktop().browse(uri);
- } else {
- Program.launch(uri.toURL().toExternalForm());
- }
- } catch (Exception e) {
- log.warn("Failed to open URI: {}", uri, e);
- }
- }
-
- public static void openURL(@Nullable String uri) {
- if (uri == null) return;
- try {
- openURL(new URI(uri));
- } catch (URISyntaxException e) {
- log.warn("Failed to open URI: {}", uri, e);
- }
- }
-}
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/UpdateCheckManager.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/UpdateCheckManager.java
deleted file mode 100644
index 168f5b18..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/UpdateCheckManager.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package at.asit.pdfover.gui.utils;
-
-import java.util.ArrayList;
-import java.util.function.Consumer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import at.asit.pdfover.commons.Constants;
-import at.asit.pdfover.commons.Messages;
-import at.asit.pdfover.gui.bku.BKUHelper;
-import at.asit.pdfover.gui.controls.Dialog;
-import at.asit.pdfover.gui.controls.Dialog.BUTTONS;
-import at.asit.pdfover.gui.controls.Dialog.ICON;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Shell;
-
-public final class UpdateCheckManager {
- private static final Logger log = LoggerFactory.getLogger(UpdateCheckManager.class);
- private static Thread updateCheckThread = null;
- private static boolean needsCheck = false;
-
- public enum Status { NOT_CHECKED, CHECKING, OUTDATED, UP_TO_DATE, FAILED };
- private static Status currentStatus = Status.NOT_CHECKED;
- public static Status getCurrentStatus() {
- synchronized (UpdateCheckManager.class) {
- return currentStatus;
- }
- }
-
- private static ArrayList<Consumer<Status>> statusCallbacks = new ArrayList<>();
- public static void registerStatusCallback(Consumer<Status> f) {
- synchronized (UpdateCheckManager.class) {
- statusCallbacks.add(f);
- f.accept(currentStatus);
- }
- }
-
- private static void setStatus(Status status) {
- synchronized(UpdateCheckManager.class) {
- currentStatus = status;
- for (Consumer<Status> f : statusCallbacks)
- f.accept(status);
- }
- }
-
- private static String latestVersionNotified = null;
- private static Status runCheck(Shell shell) {
- HttpClient client = (HttpClient) BKUHelper.getHttpClient();
- GetMethod method = new GetMethod(Constants.CURRENT_RELEASE_URL);
- try {
- client.executeMethod(method);
- final String version = method.getResponseBodyAsString().trim();
- if (!VersionComparator.before(Constants.APP_VERSION, version))
- return Status.UP_TO_DATE;
-
- if ((latestVersionNotified == null) || VersionComparator.before(latestVersionNotified, version)) {
- latestVersionNotified = version;
- // invoke GUI message in main thread
- shell.getDisplay().asyncExec(() -> {
- Dialog info = new Dialog(shell,
- Messages.getString("version_check.UpdateTitle"),
- Messages.formatString("version_check.UpdateText", version),
- BUTTONS.OK_CANCEL, ICON.INFORMATION);
-
- if (info.open() == SWT.OK)
- SWTUtils.openURL(Constants.UPDATE_URL);
- });
- }
-
- return Status.OUTDATED;
- } catch (Exception e) {
- log.error("Error downloading update information: ", e);
- return Status.FAILED;
- }
- }
-
- public static void checkNow(Shell shell) {
- if (Constants.APP_VERSION == null)
- return;
-
- synchronized (UpdateCheckManager.class) {
- if (updateCheckThread != null)
- return;
-
- needsCheck = true;
- updateCheckThread = new Thread(() -> {
- synchronized(UpdateCheckManager.class) {
- setStatus(Status.CHECKING);
- }
- while (true) {
- Status status = runCheck(shell);
- synchronized (UpdateCheckManager.class) {
- if (!UpdateCheckManager.needsCheck) {
- setStatus(status);
- UpdateCheckManager.updateCheckThread = null;
- return;
- }
- UpdateCheckManager.needsCheck = false;
- setStatus(Status.CHECKING);
- }
- }
- });
- updateCheckThread.start();
- }
- }
-}
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/VersionComparator.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/VersionComparator.java
deleted file mode 100644
index 9d06dfb1..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/VersionComparator.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2012 by A-SIT, Secure Information Technology Center Austria
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://joinup.ec.europa.eu/software/page/eupl
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- */
-package at.asit.pdfover.gui.utils;
-
-// Imports
-import java.util.Comparator;
-
-/**
- *
- */
-public class VersionComparator implements Comparator<String> {
- /* (non-Javadoc)
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- */
- @Override
- public int compare(String v1, String v2) {
- String[] v1Parts = v1.split("\\.|-");
- String[] v2Parts = v2.split("\\.|-");
-
- int length = Math.max(v1Parts.length, v2Parts.length);
- for (int i = 0; i < length; ++i) {
- int v1Part = 0;
- try {
- if (i < v1Parts.length)
- v1Part = Integer.parseInt(v1Parts[i]);
- } catch (NumberFormatException e) {
- if (v1Parts[i].equals("SNAPSHOT"))
- v1Part = Integer.MAX_VALUE;
- }
-
- int v2Part = 0;
- try {
- if (i < v2Parts.length)
- v2Part = Integer.parseInt(v2Parts[i]);
- } catch (NumberFormatException e) {
- if (v2Parts[i].equals("SNAPSHOT"))
- v2Part = Integer.MAX_VALUE;
- }
-
- if (v1Part < v2Part)
- return -1;
- if (v1Part > v2Part)
- return 1;
- }
- return 0;
- }
-
- /**
- * Compare two version strings (static version)
- * @param v1 version 1
- * @param v2 version 2
- * @return -1 if v1 &lt; v2, 0 if v1 = v2, 1 if v1 &gt; v2
- */
- public static int compare_s(String v1, String v2) {
- VersionComparator vc = new VersionComparator();
- return vc.compare(v1, v2);
- }
-
- /**
- * Check two version strings for equality
- * @param v1 version 1
- * @param v2 version 2
- * @return v1 == v2
- */
- public static boolean equals(String v1, String v2) {
- return compare_s(v1, v2) == 0;
- }
-
- /**
- * Check two version strings for order
- * @param v1 version 1
- * @param v2 version 2
- * @return v1 &lt; v2
- */
- public static boolean before(String v1, String v2) {
- return compare_s(v1, v2) < 0;
- }
-
- /**
- * Check two version strings for order
- * @param v1 version 1
- * @param v2 version 2
- * @return v1 &gt; v2
- */
- public static boolean after(String v1, String v2) {
- return compare_s(v1, v2) > 0;
- }
-}
diff --git a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/Zipper.java b/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/Zipper.java
deleted file mode 100644
index a25de58a..00000000
--- a/pdf-over-gui/src/main/java/at/asit/pdfover/gui/utils/Zipper.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2012 by A-SIT, Secure Information Technology Center Austria
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://joinup.ec.europa.eu/software/page/eupl
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- */
-package at.asit.pdfover.gui.utils;
-
-// Imports
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URI;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Zipper/unzipper to backup/extract configuration
- */
-public class Zipper {
- /**
- * SLF4J Logger instance
- **/
- private static final Logger log = LoggerFactory.getLogger(Zipper.class);
-
- /**
- * Compresses the source path to Zip File output stream
- * @param sourcePath
- * @param os
- * @throws IOException
- */
- public static void zip(String sourcePath, OutputStream os) throws IOException {
- zip(sourcePath, os, false);
- }
-
- /**
- * Compresses the source path to Zip File output stream
- * @param sourcePath
- * @param os
- * @param doDelete whether to delete content after compression
- * @throws IOException
- */
- public static void zip(String sourcePath, OutputStream os, boolean doDelete) throws IOException {
- ZipOutputStream zos = new ZipOutputStream(os);
- File dir = new File(sourcePath);
- zip(dir, dir.toURI(), zos, doDelete);
- zos.close();
- }
-
- private static void zip(File f, URI root, ZipOutputStream zos, boolean doDelete) throws IOException {
- if (f.isDirectory()) {
- File[] subDirs = f.listFiles();
- for (File subDir : subDirs) {
- zip(subDir, root, zos, doDelete);
- if (doDelete && !f.toURI().equals(root))
- subDir.delete();
- }
- } else {
- URI path = root.relativize(f.toURI());
- ZipEntry entry = new ZipEntry(path.toString());
- zos.putNextEntry(entry);
- byte[] buffer = new byte[1024];
- int len;
- BufferedInputStream is = new BufferedInputStream(new FileInputStream(f));
- while ((len = is.read(buffer)) >= 0)
- zos.write(buffer, 0, len);
- is.close();
- zos.closeEntry();
- if (doDelete)
- f.delete();
- }
- }
-
- /**
- * Extracts Zip File input stream to target path
- * @param is
- * @param targetPath
- * @throws IOException
- */
- public static void unzip(InputStream is, String targetPath) throws IOException {
- ZipInputStream zis = new ZipInputStream(is);
- ZipEntry entry;
- // while there are entries I process them
- while ((entry = zis.getNextEntry()) != null) {
- log.debug("entry: " + entry.getName() + ", " ////
- + entry.getSize());
- // consume all the data from this entry
-
- if (entry.isDirectory()) {
- log.debug("Extracting directory: " + entry.getName());
-
- File nDir = new File(targetPath + File.separator + entry.getName());
- if(!nDir.exists()) {
- if(!nDir.mkdir()) {
- throw new IOException("Failed to create dir: " + entry.getName());
- }
- }
- continue;
- }
- byte[] buffer = new byte[1024];
- int len;
- BufferedOutputStream out = new BufferedOutputStream(
- new FileOutputStream(targetPath + File.separator + entry.getName()));
- while ((len = zis.read(buffer)) >= 0)
- out.write(buffer, 0, len);
-
- out.close();
- }
- }
-}