• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 
17 package com.android.compatibility.common.util;
18 
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.zip.GZIPOutputStream;
25 
26 /**
27  * Uploads a result through a HTTP POST multipart/form-data request containing
28  * the test result XML.
29  */
30 public class ResultUploader {
31 
32     private static final int RESULT_XML_BYTES = 500 * 1024;
33 
34     /* package */ MultipartForm mMultipartForm;
35 
ResultUploader(String serverUrl, String suiteName)36     public ResultUploader(String serverUrl, String suiteName) {
37         mMultipartForm = new MultipartForm(serverUrl).addFormValue("suite", suiteName);
38     }
39 
40     /**
41      * Uploads the given file to the server.
42      *
43      * @param reportFile The file to upload.
44      * @param referenceUrl A reference url to use.
45      * @throws IOException
46      */
uploadResult(File reportFile, String referenceUrl)47     public int uploadResult(File reportFile, String referenceUrl) throws IOException {
48         InputStream input = new FileInputStream(reportFile);
49         try {
50             byte[] data = getBytes(input);
51             mMultipartForm.addFormFile("resultXml", "test-result.xml.gz", data);
52             if (referenceUrl != null && !referenceUrl.trim().isEmpty()) {
53                 mMultipartForm.addFormValue("referenceUrl", referenceUrl);
54             }
55             return mMultipartForm.submit();
56         } finally {
57             input.close();
58         }
59     }
60 
getBytes(InputStream input)61     private static byte[] getBytes(InputStream input) throws IOException {
62         ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(RESULT_XML_BYTES);
63         GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput);
64         byte[] buffer = new byte[1024];
65         int count;
66         while ((count = input.read(buffer)) > 0) {
67             gzipOutput.write(buffer, 0, count);
68         }
69         gzipOutput.close();
70         return byteOutput.toByteArray();
71     }
72 
73 }
74