aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/xtremelabs/robolectric/bytecode/ClassCache.java
blob: 323b9670c90d0ae8ee25cff7695e7a63ffbf1e0b (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
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
package com.xtremelabs.robolectric.bytecode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class ClassCache {
    private static final Attributes.Name VERSION_ATTRIBUTE = new Attributes.Name("version");

    private Map<String, byte[]> cachedClasses = new HashMap<String, byte[]>();
    private boolean startedWriting = false;

    public ClassCache(String classCachePath, final int expectedCacheVersion) {
        final File cacheJarFile = new File(classCachePath);
        JarFile cacheFile;
        try {
            cacheFile = new JarFile(cacheJarFile);
            int cacheVersion = 0;
            Manifest manifest = cacheFile.getManifest();
            if (manifest != null) {
                Attributes attributes = manifest.getEntries().get("robolectric");
                if (attributes != null) {
                    String cacheVersionStr = (String) attributes.get(VERSION_ATTRIBUTE);
                    if (cacheVersionStr != null) {
                        cacheVersion = Integer.parseInt(cacheVersionStr);
                    }
                }
            }
            if (cacheVersion != expectedCacheVersion) {
                cacheJarFile.delete();
            } else {
                readEntries(cacheFile);
            }
        } catch (IOException e) {
            // no problem
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override public void run() {
                Manifest manifest = new Manifest();
                Attributes attributes = new Attributes();
                attributes.put(VERSION_ATTRIBUTE, String.valueOf(expectedCacheVersion));
                manifest.getEntries().put("robolectric", attributes);

                saveAllClassesToCache(cacheJarFile, manifest);
            }
        });
    }

    public byte[] getClassBytesFor(String name) {
        return cachedClasses.get(name);
    }

    public boolean isWriting() {
        synchronized (this) {
            return startedWriting;
        }
    }

    public void addClass(String className, byte[] classBytes) {
        cachedClasses.put(className, classBytes);
    }

    private void readEntries(JarFile cacheFile) {
        Enumeration<JarEntry> entries = cacheFile.entries();
        try {
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String className = entry.getName();
                if (className.endsWith(".class")) {
                    int classSize = (int) entry.getSize();
                    InputStream inputStream = cacheFile.getInputStream(entry);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(classSize);
                    int c;
                    while ((c = inputStream.read()) != -1) {
                        baos.write(c);
                    }
                    className = className.substring(0, className.indexOf(".class")).replace('/', '.');
                    addClass(className, baos.toByteArray());
                }

            }
        } catch (IOException e) {
            // no problem, we didn't want those bytes that much anyway
        }
    }

    protected void saveAllClassesToCache(File file, Manifest manifest) {
        synchronized (this) {
            startedWriting = true;
    
            if (cachedClasses.size() > 0) {
                JarOutputStream jarOutputStream = null;
                try {
                    File cacheJarDir = file.getParentFile();
                    if (!cacheJarDir.exists()) {
                        cacheJarDir.mkdirs();
                    }
    
                    jarOutputStream = new JarOutputStream(new FileOutputStream(file), manifest);
                    for (Map.Entry<String, byte[]> entry : cachedClasses.entrySet()) {
                        String key = entry.getKey();
                        jarOutputStream.putNextEntry(new JarEntry(key.replace('.', '/') + ".class"));
                        jarOutputStream.write(entry.getValue());
                        jarOutputStream.closeEntry();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (jarOutputStream != null) {
                        try {
                            jarOutputStream.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
            startedWriting = false;
        }
    }
}