1 /* 2 * Copyright (C) 2018 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 package com.android.dumpviewer.utils; 17 18 import android.content.Context; 19 import android.os.Handler; 20 import android.os.Looper; 21 import android.widget.Toast; 22 23 import com.android.dumpviewer.DumpActivity; 24 25 import java.util.regex.Pattern; 26 27 public class Utils { 28 public static final String TAG = DumpActivity.TAG; 29 30 public static Handler sMainHandler = new Handler(Looper.getMainLooper()); 31 Utils()32 private Utils() { 33 } 34 35 private static final Pattern sSafeStringPattern = Pattern.compile("^[a-zA-Z0-9\\-\\_\\.]$"); 36 shellEscape(String s)37 public static String shellEscape(String s) { 38 if (sSafeStringPattern.matcher(s).matches()) { 39 return s; 40 } 41 42 return "'" + s.replace("'", "'\\''") + "'"; 43 } 44 45 /** Parse a value as a base-10 integer. */ parseInt(String value, int defValue)46 public static int parseInt(String value, int defValue) { 47 return parseIntWithBase(value, 10, defValue); 48 } 49 50 /** Parse a value as an integer of a given base. */ parseIntWithBase(String value, int base, int defValue)51 public static int parseIntWithBase(String value, int base, int defValue) { 52 if (value == null) { 53 return defValue; 54 } 55 try { 56 return Integer.parseInt(value, base); 57 } catch (NumberFormatException e) { 58 return defValue; 59 } 60 } 61 toast(Context context, String message)62 public static void toast(Context context, String message) { 63 sMainHandler.post(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT)); 64 } 65 } 66