1/*
2 * Copyright (C) 2011, 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.bandwidthtest.util;
18
19import android.util.Log;
20
21import com.android.internal.http.multipart.FilePart;
22import com.android.internal.http.multipart.MultipartEntity;
23import com.android.internal.http.multipart.Part;
24import com.android.internal.http.multipart.StringPart;
25
26import org.apache.http.HttpResponse;
27import org.apache.http.client.HttpClient;
28import org.apache.http.client.methods.HttpPost;
29import org.apache.http.impl.client.DefaultHttpClient;
30import org.apache.http.util.ByteArrayBuffer;
31
32import java.io.BufferedInputStream;
33import java.io.BufferedReader;
34import java.io.DataInputStream;
35import java.io.File;
36import java.io.FileInputStream;
37import java.io.FileOutputStream;
38import java.io.IOException;
39import java.io.InputStream;
40import java.io.InputStreamReader;
41import java.net.URL;
42import java.net.URLConnection;
43
44public class BandwidthTestUtil {
45    private static final String LOG_TAG = "BandwidthTestUtil";
46    /**
47     * Parses the first line in a file if exists.
48     *
49     * @param file {@link File} the input
50     * @return the integer value of the first line of the file.
51     */
52    public static int parseIntValueFromFile(File file) {
53        int value = 0;
54        if (file.exists()) {
55            try {
56                FileInputStream fstream = new FileInputStream(file);
57                DataInputStream in = new DataInputStream(fstream);
58                BufferedReader br = new BufferedReader(new InputStreamReader(in));
59                String strLine = br.readLine();
60                if (strLine != null) {
61                    value = Integer.parseInt(strLine);
62                }
63                // Close the input stream
64                in.close();
65            } catch (Exception e) {
66                System.err.println("Error: " + e.getMessage());
67            }
68        }
69        return value;
70    }
71
72    /**
73     * Creates the Download string for the test server.
74     *
75     * @param server url of the test server
76     * @param size in bytes of the file to download
77     * @param deviceId the device id that is downloading
78     * @param timestamp
79     * @return download url
80     */
81    public static String buildDownloadUrl(String server, int size, String deviceId,
82            String timestamp) {
83        String downloadUrl = server + "/download?size=" + size + "&device_id=" + deviceId +
84                "&timestamp=" + timestamp;
85        return downloadUrl;
86    }
87
88    /**
89     * Download a given file from a target url to a given destination file.
90     * @param targetUrl the url to download
91     * @param file the {@link File} location where to save to
92     * @return true if it succeeded
93     */
94    public static boolean DownloadFromUrl(String targetUrl, File file) {
95        try {
96            URL url = new URL(targetUrl);
97            Log.d(LOG_TAG, "Download begining");
98            Log.d(LOG_TAG, "Download url:" + url);
99            Log.d(LOG_TAG, "Downloaded file name:" + file.getAbsolutePath());
100            URLConnection ucon = url.openConnection();
101            InputStream is = ucon.getInputStream();
102            BufferedInputStream bis = new BufferedInputStream(is);
103            ByteArrayBuffer baf = new ByteArrayBuffer(50);
104            int current = 0;
105            while ((current = bis.read()) != -1) {
106                baf.append((byte) current);
107            }
108            FileOutputStream fos = new FileOutputStream(file);
109            fos.write(baf.toByteArray());
110            fos.close();
111        } catch (IOException e) {
112            Log.d(LOG_TAG, "Failed to download file with error: " + e);
113            return false;
114        }
115        return true;
116    }
117
118    /**
119     * Post a given file for a given device and timestamp to the server.
120     * @param server {@link String} url of test server
121     * @param deviceId {@link String} device id that is uploading
122     * @param timestamp {@link String} timestamp
123     * @param file {@link File} to upload
124     * @return true if it succeeded
125     */
126    public static boolean postFileToServer(String server, String deviceId, String timestamp,
127            File file) {
128        try {
129            Log.d(LOG_TAG, "Uploading begining");
130            HttpClient httpClient = new DefaultHttpClient();
131            String uri = server;
132            if (!uri.endsWith("/")) {
133                uri += "/";
134            }
135            uri += "upload";
136            Log.d(LOG_TAG, "Upload url:" + uri);
137            HttpPost postRequest = new HttpPost(uri);
138            Part[] parts = {
139                    new StringPart("device_id", deviceId),
140                    new StringPart("timestamp", timestamp),
141                    new FilePart("file", file)
142            };
143            MultipartEntity reqEntity = new MultipartEntity(parts, postRequest.getParams());
144            postRequest.setEntity(reqEntity);
145            HttpResponse res = httpClient.execute(postRequest);
146            res.getEntity().getContent().close();
147        } catch (IOException e) {
148            Log.e(LOG_TAG, "Could not upload file with error: " + e);
149            return false;
150        }
151        return true;
152    }
153}
154