summaryrefslogtreecommitdiff
path: root/icu4j/main/common_tests/src/test/java/com/ibm/icu/dev/test/serializable/CompatibilityTest.java
blob: fb77b2e9060e5ba887a72c6218e6aedf16befe00 (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
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
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
 *******************************************************************************
 * Copyright (C) 1996-2016, International Business Machines Corporation and
 * others. All Rights Reserved.
 *******************************************************************************
 *
 */

package com.ibm.icu.dev.test.serializable;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.ibm.icu.dev.test.CoreTestFmwk;
import com.ibm.icu.dev.test.serializable.SerializableTestUtility.Handler;

import junitparams.JUnitParamsRunner;
import junitparams.Parameters;

/**
 * @author sgill
 * @author emader
 */
@RunWith(JUnitParamsRunner.class)
public class CompatibilityTest extends CoreTestFmwk
{
    private static final class FileHolder {
        String className;
        String icuVersion;
        byte[] b;
        boolean skip;

        FileHolder(String fileName, byte[] b) {
            this.b = b;

            // Replace '\' with '/' to normalize fileName before extracting
            // substrings. This is required if serialization test data is
            // loaded from Windows file system.
            String tmpPath = fileName.replaceAll("\\\\", "/");

            int fileBreak = tmpPath.lastIndexOf('/');
            this.className = fileName.substring(fileBreak + 1, tmpPath.lastIndexOf('.'));
            int finalDirBreak = tmpPath.lastIndexOf("/ICU");
            this.icuVersion = tmpPath.substring(finalDirBreak + 1, fileBreak);
            className = className.substring(className.lastIndexOf('/') + 1);

            this.skip = skipFile(this.icuVersion, this.className);
        }

        private static boolean skipFile(String icuVersion, String className) {
            for (int skip = 0; skip < SKIP_CASES.length; skip++) {
                if (icuVersion.equals(SKIP_CASES[skip][0]) && className.equals(SKIP_CASES[skip][1])) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public String toString() {
            return icuVersion + "[" + className + "]";
        }
    }

    @Test
    @Parameters(method="generateClassList")
    public void testCompatibility(FileHolder holder) throws ClassNotFoundException, IOException {
        if (holder.skip) {
            logln("Skipping File = " + holder);
            return;
        }

        Object[] oldObjects = SerializableTestUtility.getSerializedObjects(holder.b);
        Handler classHandler = SerializableTestUtility.getHandler(holder.className);

        Object[] testObjects = classHandler.getTestObjects();
        for (int i = 0; i < testObjects.length; i++) {
            if (!classHandler.hasSameBehavior(oldObjects[i], testObjects[i])) {
                errln("Input object " + i + ", className " + holder.className + ": failed behavior test.");
            }
        }
    }

    /**
     * The path to an actual data resource file in the JAR. This is needed because when the
     * code is packaged for Android the resulting archive does not have entries for directories
     * and so only actual resources can be found.
     */
    private static final String ACTUAL_RESOURCE = "/ICU_3.6/com.ibm.icu.impl.OlsonTimeZone.dat";

    @SuppressWarnings("unused")
    private List<FileHolder> generateClassList() throws IOException {
        // Get the URL to an actual resource and then compute the URL to the directory just in
        // case the resources are in a JAR file that doesn't have entries for directories.
        URL dataURL = getClass().getResource("data" + ACTUAL_RESOURCE);
        try {
            dataURL = new URL(dataURL.toExternalForm().replace(ACTUAL_RESOURCE, ""));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        String protocol = dataURL.getProtocol();

        if (protocol.equals("jar")) {
            return getJarList(dataURL);
        } else if (protocol.equals("file")) {
            return getFileList(dataURL);
        } else {
            errln("Don't know how to test " + dataURL);
            return null;
        }
    }

    private List<FileHolder> getFileList(URL dataURL) throws IOException {
        List<FileHolder> classList = new ArrayList();

        File topDir = new File(dataURL.getPath());
        File dataDirs[] = topDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }});

        for (File dataDir : dataDirs) {
            File files[] = dataDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isFile() && pathname.getName().endsWith(".dat");
                }});

                for (File file : files) {
                    FileInputStream fis = new FileInputStream(file);
                    byte[] fileBytes;
                    try {
                        fileBytes = SerializableTestUtility.copyStreamBytes(fis);
                    } finally {
                        fis.close();
                    }
                    classList.add(new FileHolder(file.getAbsolutePath(), fileBytes));
                }
        }
        return classList;
    }

    private List<FileHolder> getJarList(URL jarURL) throws IOException {
        List<FileHolder> classList = new ArrayList();

        String prefix = jarURL.getPath();
        int ix = prefix.indexOf("!/");
        if (ix >= 0) {
            prefix = prefix.substring(ix + 2);
        }

        JarFile jarFile = null;
        try {
            // Need to trim the directory off the JAR entry before opening the connection otherwise
            // it could fail as it will try and find the entry within the JAR which may not exist.
            String urlAsString = jarURL.toExternalForm();
            ix = urlAsString.indexOf("!/");
            jarURL = new URL(urlAsString.substring(0, ix + 2));

            JarURLConnection conn = (JarURLConnection) jarURL.openConnection();
            jarFile = conn.getJarFile();
            Enumeration entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = (JarEntry) entries.nextElement();
                if (!entry.isDirectory()) {
                    String entryName = entry.getName();

                    if (entryName.startsWith(prefix) && entryName.endsWith(".dat")) {
                        FileHolder holder = new FileHolder(entryName,
                                SerializableTestUtility.copyStreamBytes(jarFile.getInputStream(entry)));
                        classList.add(holder);

                    }
                }
            }
        } finally {
            if (jarFile != null) {
                jarFile.close();
            }
        }
        return classList;
    }

    private static final String[][] SKIP_CASES = {
            // ICU 52+ PluralRules/PluralFormat/CurrencyPluralInfo are not
            // serialization-compatible with previous versions.
            {"ICU_50.1", "com.ibm.icu.text.CurrencyPluralInfo"},
            {"ICU_51.1", "com.ibm.icu.text.CurrencyPluralInfo"},

            {"ICU_50.1", "com.ibm.icu.text.PluralFormat"},
            {"ICU_51.1", "com.ibm.icu.text.PluralFormat"},

            {"ICU_50.1", "com.ibm.icu.text.PluralRules"},
            {"ICU_51.1", "com.ibm.icu.text.PluralRules"},

            // GeneralMeasureFormat was in technical preview, but is going away after ICU 52.1.
            {"ICU_52.1", "com.ibm.icu.text.GeneralMeasureFormat"},

            // RuleBasedNumberFormat
            {"ICU_3.6",     "com.ibm.icu.text.RuleBasedNumberFormat"},

            // ICU 4.8+ MessageFormat is not serialization-compatible with previous versions.
            {"ICU_3.6",     "com.ibm.icu.text.MessageFormat"},
    };
}