1 /* 2 * Copyright (C) 2016 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.server.wifi.util; 18 19 import java.util.Random; 20 import java.util.stream.Collectors; 21 22 /** Basic string utilities */ 23 public class StringUtil { 24 static final byte ASCII_PRINTABLE_MIN = ' '; 25 static final byte ASCII_PRINTABLE_MAX = '~'; 26 27 /** Returns true if-and-only-if |byteArray| can be safely printed as ASCII. */ isAsciiPrintable(byte[] byteArray)28 public static boolean isAsciiPrintable(byte[] byteArray) { 29 if (byteArray == null) { 30 return true; 31 } 32 33 for (byte b : byteArray) { 34 switch (b) { 35 // Control characters which actually are printable. Fall-throughs are deliberate. 36 case 0x07: // bell ('\a' not recognized in Java) 37 case '\f': // form feed 38 case '\n': // new line 39 case '\t': // horizontal tab 40 case 0x0b: // vertical tab ('\v' not recognized in Java) 41 continue; 42 } 43 44 if (b < ASCII_PRINTABLE_MIN || b > ASCII_PRINTABLE_MAX) { 45 return false; 46 } 47 } 48 49 return true; 50 } 51 52 /** Returns a random number string. */ generateRandomNumberString(int length)53 public static String generateRandomNumberString(int length) { 54 final String pool = "0123456789"; 55 return new Random(System.currentTimeMillis()) 56 .ints(length, 0, pool.length()) 57 .mapToObj(i -> Character.toString(pool.charAt(i))) 58 .collect(Collectors.joining()); 59 } 60 } 61