1/*
2 * Generally useful functions :)
3 */
4
5package com.sleepycat.db.test;
6
7import static org.junit.Assert.fail;
8
9import com.sleepycat.db.*;
10
11import java.io.BufferedInputStream;
12import java.io.BufferedReader;
13import java.io.File;
14import java.io.FileInputStream;
15import java.io.FileOutputStream;
16import java.io.FileNotFoundException;
17import java.io.InputStream;
18import java.io.IOException;
19import java.io.OutputStream;
20import java.util.Properties;
21
22public class TestUtils
23{
24    public static boolean config_loaded = false;
25    public static boolean verbose_flag = false;
26    public static int debug_level = 2;
27
28    // should be initialized by calling loadEnvVars. Shared between all tests.
29    public static String BASETEST_DBDIR   = "";
30    public static File   BASETEST_DBFILE  = null; //      new File(TestUtils.BASETEST_DBDIR);
31
32    public static void ERR(String a)
33    {
34        System.err.println("FAIL: " + a);
35        fail(a);
36    }
37
38    public static void DEBUGOUT(String s)
39    {
40        DEBUGOUT(1, s);
41    }
42
43    public static void DEBUGOUT(int importance, String s)
44    {
45        if(importance > debug_level)
46            System.out.println("DEBUG: " +s);
47    }
48
49    public static void VERBOSEOUT(String s)
50    {
51        if (verbose_flag)
52            System.out.println(s);
53    }
54
55    public static void sysexit(int code)
56    {
57        System.exit(code);
58    }
59
60    public static void check_file_removed(String name, boolean fatal,
61					   boolean force_remove_first)
62    {
63        File f = new File(name);
64        if (force_remove_first) {
65            f.delete();
66        }
67        if (f.exists()) {
68            if (fatal)
69                System.out.print("FAIL: ");
70            DEBUGOUT(1, "File \"" + name + "\" still exists after check_file_removed\n");
71            if (fatal)
72                fail("File \"" + name + "\" still exists after check_file_removed");
73        }
74    }
75
76
77    // remove any existing environment or database
78    public static void removeall(boolean use_db, boolean remove_env, String envpath, String dbname)
79    {
80        {
81            try {
82                if (remove_env)
83                    Environment.remove(new File(envpath), true, EnvironmentConfig.DEFAULT);
84                if (use_db)
85                    Database.remove(dbname, null, DatabaseConfig.DEFAULT);
86            }
87            catch (DatabaseException dbe) {
88                DEBUGOUT(1, "TestUtil::removeall exception caught: " + dbe);
89            }
90            catch (FileNotFoundException dbe) {
91                DEBUGOUT(1, "TestUtil::removeall exception caught: " + dbe);
92            }
93        }
94        check_file_removed(dbname, false, !use_db);
95        if (remove_env) {
96            for (int i=0; i<8; i++) {
97                String fname = envpath + "/" + "__db." + i;
98                check_file_removed(fname, true, !use_db);
99            }
100
101            // ensure the user knows if there is junk remaining.
102            // clean out spurious log.00X files
103            File dir = new File(envpath);
104            if(dir.isDirectory()) {
105                String[] remainingfiles = dir.list();
106                for(int i = 0; i < remainingfiles.length; i++) {
107                    if(remainingfiles[i].startsWith("log") || remainingfiles[i].endsWith("db2") ||
108                        remainingfiles[i].endsWith("log") || remainingfiles[i].startsWith("__db")) {
109                        DEBUGOUT(1, "TestUtils::removeall removing: " +remainingfiles[i]);
110                        check_file_removed(envpath + "/" + remainingfiles[i], false, true);
111                    } else {
112                        if(remainingfiles[i].indexOf("del") == -1)
113                            DEBUGOUT(3, "TestUtils::removeall warning, file: " + remainingfiles[i] + " remains in directory after cleanup.");
114                    }
115                }
116            }
117        }
118    }
119
120    public static boolean removeDir(String dirname)
121    {
122        try {
123            File deldir = new File(dirname);
124
125            if (!deldir.exists()) {
126                return true;
127            } else if(!deldir.isDirectory()) {
128                return false;
129            } else {
130                // The following will fail if the directory contains sub-dirs.
131                File[] contents = deldir.listFiles();
132                for (int i = 0; i < contents.length; i++)
133                    contents[i].delete();
134                deldir.delete();
135            }
136        } catch (Exception e) {
137            TestUtils.DEBUGOUT(4, "Warning: error encountered removing directory.\n" + e);
138        }
139        return true;
140    }
141
142    static public String shownull(Object o)
143    {
144        if (o == null)
145            return "null";
146        else
147            return "not null";
148    }
149
150	/*
151	 * The config file is not currently required.
152	 * The only variable that can be set via the
153	 * config file is the base directory for the
154	 * tests to be run in. The default is "data"
155	 * and will be created for the tests.
156	 */
157    public static void loadConfig(String envfilename)
158    {
159        if(config_loaded)
160            return;
161
162        String configname = envfilename;
163        if(envfilename == null)
164        {
165            String OSStr = java.lang.System.getProperty("os.name");
166            if((OSStr.toLowerCase()).indexOf("windows") != -1)
167            {
168                configname = "config_win32";
169            } else {
170                // assume a nix variant.
171                configname = "config_nix";
172            }
173        }
174        config_loaded = true;
175        try {
176            InputStream in = new FileInputStream(configname);
177            DEBUGOUT(2, "Opened " + configname + " to read configuration.");
178            Properties props = new Properties();
179            props.load(in);
180
181            String var = props.getProperty("BASETEST_DBDIR");
182            if(var != null)
183            { // Property seems to encase things in "";
184                var = var.substring(1);
185                var = var.substring(0, var.length() -2);
186                BASETEST_DBDIR = var;
187            }
188            DEBUGOUT(2, "BASETEST_DBDIR is: " + BASETEST_DBDIR);
189
190        } catch (Exception e) {
191			// expected - the config file is optional.
192            DEBUGOUT(0, "loadEnvVars -- loading of default variables failed. error: " + e);
193        }
194		if (BASETEST_DBDIR == "")
195			BASETEST_DBDIR = "data";
196        BASETEST_DBFILE = new File(BASETEST_DBDIR);
197        if (!BASETEST_DBFILE.exists())
198		    BASETEST_DBFILE.mkdirs();
199    }
200
201    public static String getDBFileName(String dbname)
202    {
203        DEBUGOUT(1, "getDBFileName returning: " + BASETEST_DBDIR + "/" + dbname);
204        return BASETEST_DBDIR + "/" + dbname;
205    }
206
207    public static OutputStream getErrorStream()
208    {
209        OutputStream retval = System.err;
210        try {
211            File outfile = new File(BASETEST_DBDIR + "/" + "errstream.log");
212            if(outfile.exists())
213            {
214                outfile.delete();
215                outfile.createNewFile();
216            } else {
217                outfile.createNewFile();
218            }
219            retval = new FileOutputStream(outfile);
220        } catch (FileNotFoundException fnfe) {
221            DEBUGOUT(3, "Unable to open error log file. " + fnfe);
222        } catch (IOException ioe) {
223            DEBUGOUT(3, "Unable to create error log file. " + ioe);
224        }
225        return retval;
226    }
227}
228