From c3f75dbab68953858b82e60ab1f364e46b1e1e69 Mon Sep 17 00:00:00 2001 From: Gregor Santner Date: Tue, 19 Sep 2017 16:29:45 +0200 Subject: [PATCH] Add more opoc utils --- .../java/net/gsantner/opoc/util/Callback.java | 18 ++ .../net/gsantner/opoc/util/FileUtils.java | 169 +++++++++++++++ .../net/gsantner/opoc/util/NetworkUtils.java | 201 ++++++++++++++++++ 3 files changed, 388 insertions(+) create mode 100644 app/src/main/java/net/gsantner/opoc/util/Callback.java create mode 100644 app/src/main/java/net/gsantner/opoc/util/FileUtils.java create mode 100644 app/src/main/java/net/gsantner/opoc/util/NetworkUtils.java diff --git a/app/src/main/java/net/gsantner/opoc/util/Callback.java b/app/src/main/java/net/gsantner/opoc/util/Callback.java new file mode 100644 index 000000000..641461edc --- /dev/null +++ b/app/src/main/java/net/gsantner/opoc/util/Callback.java @@ -0,0 +1,18 @@ +/* + * ------------------------------------------------------------------------------ + * Lonami Exo wrote this. You can do whatever you want + * with it. If we meet some day, and you think it is worth it, you can buy me + * a coke in return. Provided as is without any kind of warranty. Do not blame + * or sue me if something goes wrong. No attribution required. + * - Lonami Exo + * + * License: Creative Commons Zero (CC0 1.0) + * http://creativecommons.org/publicdomain/zero/1.0/ + * ---------------------------------------------------------------------------- + */ +package net.gsantner.opoc.util; + +// Simple callback interface which includes an object +public interface Callback { + void onCallback(T t); +} diff --git a/app/src/main/java/net/gsantner/opoc/util/FileUtils.java b/app/src/main/java/net/gsantner/opoc/util/FileUtils.java new file mode 100644 index 000000000..ff5132dab --- /dev/null +++ b/app/src/main/java/net/gsantner/opoc/util/FileUtils.java @@ -0,0 +1,169 @@ +/* + * ------------------------------------------------------------------------------ + * Gregor Santner & Lonami Exo wrote + * this. You can do whatever you want with it. If we meet some day, and you + * think it is worth it, you can buy us a coke in return. Provided as is without + * any kind of warranty. Do not blame or sue us if something goes wrong. + * No attribution required. - Gregor Santner & Lonami Exo + * + * License: Creative Commons Zero (CC0 1.0) + * http://creativecommons.org/publicdomain/zero/1.0/ + * ---------------------------------------------------------------------------- + */ +package net.gsantner.opoc.util; + + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection", "deprecation"}) +public class FileUtils { + // Used on methods like copyFile(src, dst) + private static final int BUFFER_SIZE = 4096; + + public static String readTextFile(final File file) { + try { + return readCloseTextStream(new FileInputStream(file)); + } catch (FileNotFoundException e) { + System.err.println("readTextFile: File " + file + " not found."); + } + + return ""; + } + + public static String readCloseTextStream(final InputStream stream) { + return readCloseTextStream(stream, true).get(0); + } + + public static List readCloseTextStream(final InputStream stream, boolean concatToOneString) { + final ArrayList lines = new ArrayList<>(); + BufferedReader reader = null; + String line = ""; + try { + StringBuilder sb = new StringBuilder(); + reader = new BufferedReader(new InputStreamReader(stream)); + + while ((line = reader.readLine()) != null) { + if (concatToOneString) { + sb.append(line).append('\n'); + } else { + lines.add(line); + } + } + line = sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + if (concatToOneString) { + lines.clear(); + lines.add(line); + } + return lines; + } + + public static boolean writeFile(final File file, final String content) { + BufferedWriter writer = null; + try { + if (!file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) + return false; + + writer = new BufferedWriter(new FileWriter(file)); + writer.write(content); + writer.flush(); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static boolean copyFile(final File src, final File dst) { + InputStream is = null; + FileOutputStream os = null; + try { + try { + is = new FileInputStream(src); + os = new FileOutputStream(dst); + byte[] buf = new byte[BUFFER_SIZE]; + int len; + while ((len = is.read(buf)) > 0) { + os.write(buf, 0, len); + } + } finally { + if (is != null) { + is.close(); + } + if (os != null) { + os.close(); + } + } + } catch (IOException ex) { + return false; + } + return true; + } + + // Returns -1 if the file did not contain any of the needles, otherwise, + // the index of which needle was found in the contents of the file. + // + // Needless MUST be in lower-case. + public static int fileContains(File file, String... needles) { + try { + FileInputStream in = new FileInputStream(file); + + int i; + String line; + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + while ((line = reader.readLine()) != null) { + for (i = 0; i != needles.length; ++i) + if (line.toLowerCase().contains(needles[i])) { + return i; + } + } + + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return -1; + } + + public static boolean deleteRecursive(final File file) { + boolean ok = true; + if (file.exists()) { + if (file.isDirectory()) { + for (File child : file.listFiles()) + ok &= deleteRecursive(child); + } + ok &= file.delete(); + } + return ok; + } +} diff --git a/app/src/main/java/net/gsantner/opoc/util/NetworkUtils.java b/app/src/main/java/net/gsantner/opoc/util/NetworkUtils.java new file mode 100644 index 000000000..73177b66d --- /dev/null +++ b/app/src/main/java/net/gsantner/opoc/util/NetworkUtils.java @@ -0,0 +1,201 @@ +/* + * ------------------------------------------------------------------------------ + * Lonami Exo wrote this. You can do whatever you want + * with it. If we meet some day, and you think it is worth it, you can buy me + * a coke in return. Provided as is without any kind of warranty. Do not blame + * or sue me if something goes wrong. No attribution required. + * - Lonami Exo + * + * License: Creative Commons Zero (CC0 1.0) + * http://creativecommons.org/publicdomain/zero/1.0/ + * ---------------------------------------------------------------------------- + */ +package net.gsantner.opoc.util; + +import org.json.JSONObject; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection", "deprecation"}) +public class NetworkUtils { + private static final String UTF8 = "UTF-8"; + public static final String GET = "GET"; + public static final String POST = "POST"; + public static final String PATCH = "PATCH"; + + private final static int BUFFER_SIZE = 4096; + + // Downloads a file from the give url to the output file + // Creates the file's parent directory if it doesn't exist + public static boolean downloadFile(final String url, final File out) { + return downloadFile(url, out, null); + } + + public static boolean downloadFile(final String url, final File out, final Callback progressCallback) { + try { + return downloadFile(new URL(url), out, progressCallback); + } catch (MalformedURLException e) { + // Won't happen + e.printStackTrace(); + return false; + } + } + + public static boolean downloadFile(final URL url, final File outFile, final Callback progressCallback) { + InputStream input = null; + OutputStream output = null; + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) url.openConnection(); + connection.connect(); + input = connection.getInputStream(); + + if (!outFile.getParentFile().isDirectory()) + if (!outFile.getParentFile().mkdirs()) + return false; + output = new FileOutputStream(outFile); + + int count; + int written = 0; + final float invLength = 1f / connection.getContentLength(); + + byte data[] = new byte[BUFFER_SIZE]; + while ((count = input.read(data)) != -1) { + output.write(data, 0, count); + if (invLength != -1f && progressCallback != null) { + written += count; + progressCallback.onCallback(written * invLength); + } + } + + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } finally { + try { + if (output != null) + output.close(); + if (input != null) + input.close(); + } catch (IOException ignored) { + } + if (connection != null) + connection.disconnect(); + } + } + + // No parameters, method can be GET, POST, etc. + public static String performCall(final String url, final String method) { + try { + return performCall(new URL(url), method, ""); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return ""; + } + + // URL encoded parameters + public static String performCall(final String url, final String method, final HashMap params) { + try { + return performCall(new URL(url), method, encodeQuery(params)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + e.printStackTrace(); + } + return ""; + } + + // Defaults to POST + public static String performCall(final String url, final JSONObject json) { + return performCall(url, POST, json); + } + + public static String performCall(final String url, final String method, final JSONObject json) { + try { + return performCall(new URL(url), method, json.toString()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return ""; + } + + private static String performCall(final URL url, final String method, final String data) { + try { + final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod(method); + conn.setDoInput(true); + + if (data != null && !data.isEmpty()) { + conn.setDoOutput(true); + final OutputStream output = conn.getOutputStream(); + output.write(data.getBytes(Charset.forName(UTF8))); + output.flush(); + output.close(); + } + + return FileUtils.readCloseTextStream(conn.getInputStream()); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + private static String encodeQuery(final HashMap params) throws UnsupportedEncodingException { + final StringBuilder result = new StringBuilder(); + boolean first = true; + for (Map.Entry entry : params.entrySet()) { + if (first) first = false; + else result.append("&"); + + result.append(URLEncoder.encode(entry.getKey(), UTF8)); + result.append("="); + result.append(URLEncoder.encode(entry.getValue(), UTF8)); + } + + return result.toString(); + } + + public static HashMap getDataMap(final String query) { + final HashMap result = new HashMap<>(); + final StringBuilder sb = new StringBuilder(); + String name = ""; + + try { + for (int i = 0; i < query.length(); i++) { + char c = query.charAt(i); + switch (c) { + case '=': + name = URLDecoder.decode(sb.toString(), UTF8); + sb.setLength(0); + break; + case '&': + result.put(name, URLDecoder.decode(sb.toString(), UTF8)); + sb.setLength(0); + break; + default: + sb.append(c); + break; + } + } + if (!name.isEmpty()) + result.put(name, URLDecoder.decode(sb.toString(), UTF8)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + return result; + } +}