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 org.chromium.latency.walt; 18 19 import android.content.Context; 20 21 import androidx.loader.content.AsyncTaskLoader; 22 23 import java.io.BufferedOutputStream; 24 import java.io.IOException; 25 import java.io.PrintWriter; 26 import java.net.HttpURLConnection; 27 import java.net.URL; 28 29 class LogUploader extends AsyncTaskLoader<Integer> { 30 31 private String urlString; 32 private SimpleLogger logger; 33 LogUploader(Context context)34 LogUploader(Context context) { 35 super(context); 36 urlString = Utils.getStringPreference(context, R.string.preference_log_url, ""); 37 logger = SimpleLogger.getInstance(context); 38 39 } 40 LogUploader(Context context, String urlString)41 LogUploader(Context context, String urlString) { 42 super(context); 43 this.urlString = urlString; 44 logger = SimpleLogger.getInstance(context); 45 } 46 47 @Override loadInBackground()48 public Integer loadInBackground() { 49 if (urlString.isEmpty()) return -1; 50 try { 51 URL url = new URL(urlString); 52 HttpURLConnection urlConnection = 53 (HttpURLConnection) url.openConnection(); 54 urlConnection.setRequestMethod("POST"); 55 urlConnection.setDoOutput(true); 56 urlConnection.setRequestProperty("Content-Type", "text/plain"); 57 BufferedOutputStream out = 58 new BufferedOutputStream(urlConnection.getOutputStream()); 59 PrintWriter writer = new PrintWriter(out); 60 writer.write(logger.getLogText()); 61 writer.flush(); 62 final int responseCode = urlConnection.getResponseCode(); 63 if (responseCode / 100 == 2) { 64 logger.log("Log successfully uploaded"); 65 } else { 66 logger.log("Log upload may have failed. Server return status code " + responseCode); 67 } 68 return responseCode; 69 } catch (IOException e) { 70 logger.log("Failed to upload log"); 71 return -1; 72 } 73 } 74 startUpload()75 void startUpload() { 76 super.forceLoad(); 77 } 78 uploadIfAutoEnabled(Context context)79 static void uploadIfAutoEnabled(Context context) { 80 if (Utils.getBooleanPreference(context, R.string.preference_auto_upload_log, false)) { 81 new LogUploader(context).startUpload(); 82 } 83 } 84 } 85