summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/base/utils/FileHelper.java
blob: f1d86876370a9e5a4da3dd371c94f899079a6713 (plain)
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
package se.leap.bitmaskclient.base.utils;

import android.content.Context;

import androidx.annotation.VisibleForTesting;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import de.blinkt.openvpn.core.NativeUtils;

/**
 * Created by cyberta on 18.03.18.
 */

public class FileHelper {

    public interface FileHelperInterface {
        File createFile(File dir, String fileName);
        void persistFile(File file, String content) throws IOException;
    }

    public static class DefaultFileHelper implements FileHelperInterface {
        @Override
        public File createFile(File dir, String fileName) {
            return new File(dir, fileName);
        }

        @Override
        public void persistFile(File file, String content) throws IOException {
            FileWriter writer = new FileWriter(file);
            writer.write(content);
            writer.close();
        }
    }

    private static FileHelperInterface instance = new DefaultFileHelper();

    @VisibleForTesting
    public FileHelper(FileHelperInterface helperInterface) {
        if (!NativeUtils.isUnitTest()) {
            throw new IllegalStateException("FileHelper injected with FileHelperInterface outside of an unit test");
        }

        instance = helperInterface;
    }

    public static File createFile(File dir, String fileName) {
        return instance.createFile(dir, fileName);
    }

    public static void persistFile(File file, String content) throws IOException {
        instance.persistFile(file, content);
    }

    public static String readPublicKey(Context context) {
        {
            InputStream inputStream;
            try {
                inputStream = context.getAssets().open("public.pgp");
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                reader.close();
                return sb.toString();
            } catch (IOException errabi) {
                return null;
            }
        }
    }

}