FsUtils.java revision 5af84db492a0c198377ba4dacc83c5a211e96ff6
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.dumprendertree2;
18
19import android.util.Log;
20
21import com.android.dumprendertree2.forwarder.ForwarderManager;
22
23import org.apache.http.HttpEntity;
24import org.apache.http.HttpResponse;
25import org.apache.http.HttpStatus;
26import org.apache.http.client.HttpClient;
27import org.apache.http.client.ResponseHandler;
28import org.apache.http.client.methods.HttpGet;
29import org.apache.http.conn.ClientConnectionManager;
30import org.apache.http.conn.scheme.PlainSocketFactory;
31import org.apache.http.conn.scheme.Scheme;
32import org.apache.http.conn.scheme.SchemeRegistry;
33import org.apache.http.conn.ssl.SSLSocketFactory;
34import org.apache.http.impl.client.DefaultHttpClient;
35import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
36import org.apache.http.params.BasicHttpParams;
37import org.apache.http.params.HttpConnectionParams;
38import org.apache.http.params.HttpParams;
39import org.apache.http.util.EntityUtils;
40
41import java.io.BufferedReader;
42import java.io.File;
43import java.io.FileInputStream;
44import java.io.FileOutputStream;
45import java.io.IOException;
46import java.io.InputStream;
47import java.io.InputStreamReader;
48import java.io.OutputStream;
49import java.net.MalformedURLException;
50import java.net.SocketTimeoutException;
51import java.net.URL;
52import java.util.LinkedList;
53import java.util.List;
54
55/**
56 *
57 */
58public class FsUtils {
59    public static final String LOG_TAG = "FsUtils";
60
61    private static final String SCRIPT_URL = ForwarderManager.getHostSchemePort(false) +
62            "WebKitTools/DumpRenderTree/android/get_layout_tests_dir_contents.php";
63
64    private static final int HTTP_TIMEOUT_MS = 5000;
65
66    private static HttpClient sHttpClient;
67
68    private static HttpClient getHttpClient() {
69        if (sHttpClient == null) {
70            HttpParams params = new BasicHttpParams();
71
72            SchemeRegistry schemeRegistry = new SchemeRegistry();
73            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(),
74                    ForwarderManager.HTTP_PORT));
75            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(),
76                    ForwarderManager.HTTPS_PORT));
77
78            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params,
79                    schemeRegistry);
80            sHttpClient = new DefaultHttpClient(connectionManager, params);
81            HttpConnectionParams.setSoTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
82            HttpConnectionParams.setConnectionTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
83        }
84        return sHttpClient;
85    }
86
87    public static void writeDataToStorage(File file, byte[] bytes, boolean append) {
88        Log.d(LOG_TAG, "writeDataToStorage(): " + file.getAbsolutePath());
89        try {
90            OutputStream outputStream = null;
91            try {
92                file.getParentFile().mkdirs();
93                file.createNewFile();
94                Log.d(LOG_TAG, "writeDataToStorage(): File created: " + file.getAbsolutePath());
95                outputStream = new FileOutputStream(file, append);
96                outputStream.write(bytes);
97            } finally {
98                if (outputStream != null) {
99                    outputStream.close();
100                }
101            }
102        } catch (IOException e) {
103            Log.e(LOG_TAG, "file.getAbsolutePath=" + file.getAbsolutePath() + " append=" + append,
104                    e);
105        }
106    }
107
108    public static byte[] readDataFromStorage(File file) {
109        if (!file.exists()) {
110            Log.d(LOG_TAG, "readDataFromStorage(): File does not exist: "
111                    + file.getAbsolutePath());
112            return null;
113        }
114
115        byte[] bytes = null;
116        try {
117            FileInputStream fis = null;
118            try {
119                fis = new FileInputStream(file);
120                bytes = new byte[(int)file.length()];
121                fis.read(bytes);
122            } finally {
123                if (fis != null) {
124                    fis.close();
125                }
126            }
127        } catch (IOException e) {
128            Log.e(LOG_TAG, "file.getAbsolutePath=" + file.getAbsolutePath(), e);
129        }
130
131        return bytes;
132    }
133
134    public static byte[] readDataFromUrl(URL url) {
135        if (url == null) {
136            Log.w(LOG_TAG, "readDataFromUrl(): url is null!");
137            return null;
138        }
139
140        HttpGet httpRequest = new HttpGet(url.toString());
141        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
142            @Override
143            public byte[] handleResponse(HttpResponse response) throws IOException {
144                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
145                    return null;
146                }
147                HttpEntity entity = response.getEntity();
148                return (entity == null ? null : EntityUtils.toByteArray(entity));
149            }
150        };
151
152        byte[] bytes = null;
153        try {
154            /**
155             * TODO: Not exactly sure why some requests hang indefinitely, but adding this
156             * timeout (in static getter for http client) in loop helps.
157             */
158            boolean timedOut;
159            do {
160                timedOut = false;
161                try {
162                    bytes = getHttpClient().execute(httpRequest, handler);
163                } catch (SocketTimeoutException e) {
164                    timedOut = true;
165                    Log.w(LOG_TAG, "Expected SocketTimeoutException: " + url, e);
166                }
167            } while (timedOut);
168        } catch (IOException e) {
169            Log.e(LOG_TAG, "url=" + url, e);
170        }
171
172        return bytes;
173    }
174
175    public static List<String> getLayoutTestsDirContents(String dirRelativePath, boolean recurse,
176            boolean mode) {
177        String modeString = (mode ? "folders" : "files");
178
179        URL url = null;
180        try {
181            url = new URL(SCRIPT_URL +
182                    "?path=" + dirRelativePath +
183                    "&recurse=" + recurse +
184                    "&mode=" + modeString);
185        } catch (MalformedURLException e) {
186            Log.e(LOG_TAG, "path=" + dirRelativePath + " recurse=" + recurse + " mode=" +
187                    modeString, e);
188            return new LinkedList<String>();
189        }
190
191        HttpGet httpRequest = new HttpGet(url.toString());
192        ResponseHandler<LinkedList<String>> handler = new ResponseHandler<LinkedList<String>>() {
193            @Override
194            public LinkedList<String> handleResponse(HttpResponse response)
195                    throws IOException {
196                LinkedList<String> lines = new LinkedList<String>();
197
198                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
199                    return lines;
200                }
201                HttpEntity entity = response.getEntity();
202                if (entity == null) {
203                    return lines;
204                }
205
206                BufferedReader reader =
207                        new BufferedReader(new InputStreamReader(entity.getContent()));
208                String line;
209                try {
210                    while ((line = reader.readLine()) != null) {
211                        lines.add(line);
212                    }
213                } finally {
214                    if (reader != null) {
215                        reader.close();
216                    }
217                }
218
219                return lines;
220            }
221        };
222
223        try {
224            return getHttpClient().execute(httpRequest, handler);
225        } catch (IOException e) {
226            Log.e(LOG_TAG, "url=" + url, e);
227        }
228
229        return new LinkedList<String>();
230    }
231
232    public static void closeInputStream(InputStream inputStream) {
233        try {
234            if (inputStream != null) {
235                inputStream.close();
236            }
237        } catch (IOException e) {
238            Log.e(LOG_TAG, "Couldn't close stream!", e);
239        }
240    }
241
242    public static void closeOutputStream(OutputStream outputStream) {
243        try {
244            if (outputStream != null) {
245                outputStream.close();
246            }
247        } catch (IOException e) {
248            Log.e(LOG_TAG, "Couldn't close stream!", e);
249        }
250    }
251}