text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```java package com.blankj.utilcode.util; import android.content.ContentResolver; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.net.Uri; import android.os.Build; import android.os.StatFs; import android.text.TextUtils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.net.ssl.HttpsURLConnection; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/05/03 * desc : utils about file * </pre> */ public final class FileUtils { private static final String LINE_SEP = System.getProperty("line.separator"); private FileUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return the file by path. * * @param filePath The path of file. * @return the file */ public static File getFileByPath(final String filePath) { return UtilsBridge.isSpace(filePath) ? null : new File(filePath); } /** * Return whether the file exists. * * @param file The file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isFileExists(final File file) { if (file == null) return false; if (file.exists()) { return true; } return isFileExists(file.getAbsolutePath()); } /** * Return whether the file exists. * * @param filePath The path of file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isFileExists(final String filePath) { File file = getFileByPath(filePath); if (file == null) return false; if (file.exists()) { return true; } return isFileExistsApi29(filePath); } private static boolean isFileExistsApi29(String filePath) { if (Build.VERSION.SDK_INT >= 29) { try { Uri uri = Uri.parse(filePath); ContentResolver cr = Utils.getApp().getContentResolver(); AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r"); if (afd == null) return false; try { afd.close(); } catch (IOException ignore) { } } catch (FileNotFoundException e) { return false; } return true; } return false; } /** * Rename the file. * * @param filePath The path of file. * @param newName The new name of file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean rename(final String filePath, final String newName) { return rename(getFileByPath(filePath), newName); } /** * Rename the file. * * @param file The file. * @param newName The new name of file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean rename(final File file, final String newName) { // file is null then return false if (file == null) return false; // file doesn't exist then return false if (!file.exists()) return false; // the new name is space then return false if (UtilsBridge.isSpace(newName)) return false; // the new name equals old name then return true if (newName.equals(file.getName())) return true; File newFile = new File(file.getParent() + File.separator + newName); // the new name of file exists then return false return !newFile.exists() && file.renameTo(newFile); } /** * Return whether it is a directory. * * @param dirPath The path of directory. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isDir(final String dirPath) { return isDir(getFileByPath(dirPath)); } /** * Return whether it is a directory. * * @param file The file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isDir(final File file) { return file != null && file.exists() && file.isDirectory(); } /** * Return whether it is a file. * * @param filePath The path of file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isFile(final String filePath) { return isFile(getFileByPath(filePath)); } /** * Return whether it is a file. * * @param file The file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isFile(final File file) { return file != null && file.exists() && file.isFile(); } /** * Create a directory if it doesn't exist, otherwise do nothing. * * @param dirPath The path of directory. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise */ public static boolean createOrExistsDir(final String dirPath) { return createOrExistsDir(getFileByPath(dirPath)); } /** * Create a directory if it doesn't exist, otherwise do nothing. * * @param file The file. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise */ public static boolean createOrExistsDir(final File file) { return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); } /** * Create a file if it doesn't exist, otherwise do nothing. * * @param filePath The path of file. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise */ public static boolean createOrExistsFile(final String filePath) { return createOrExistsFile(getFileByPath(filePath)); } /** * Create a file if it doesn't exist, otherwise do nothing. * * @param file The file. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise */ public static boolean createOrExistsFile(final File file) { if (file == null) return false; if (file.exists()) return file.isFile(); if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * Create a file if it doesn't exist, otherwise delete old file before creating. * * @param filePath The path of file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean createFileByDeleteOldFile(final String filePath) { return createFileByDeleteOldFile(getFileByPath(filePath)); } /** * Create a file if it doesn't exist, otherwise delete old file before creating. * * @param file The file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean createFileByDeleteOldFile(final File file) { if (file == null) return false; // file exists and unsuccessfully delete then return false if (file.exists() && !file.delete()) return false; if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * Copy the directory or file. * * @param srcPath The path of source. * @param destPath The path of destination. * @return {@code true}: success<br>{@code false}: fail */ public static boolean copy(final String srcPath, final String destPath) { return copy(getFileByPath(srcPath), getFileByPath(destPath), null); } /** * Copy the directory or file. * * @param srcPath The path of source. * @param destPath The path of destination. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean copy(final String srcPath, final String destPath, final OnReplaceListener listener) { return copy(getFileByPath(srcPath), getFileByPath(destPath), listener); } /** * Copy the directory or file. * * @param src The source. * @param dest The destination. * @return {@code true}: success<br>{@code false}: fail */ public static boolean copy(final File src, final File dest) { return copy(src, dest, null); } /** * Copy the directory or file. * * @param src The source. * @param dest The destination. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean copy(final File src, final File dest, final OnReplaceListener listener) { if (src == null) return false; if (src.isDirectory()) { return copyDir(src, dest, listener); } return copyFile(src, dest, listener); } /** * Copy the directory. * * @param srcDir The source directory. * @param destDir The destination directory. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ private static boolean copyDir(final File srcDir, final File destDir, final OnReplaceListener listener) { return copyOrMoveDir(srcDir, destDir, listener, false); } /** * Copy the file. * * @param srcFile The source file. * @param destFile The destination file. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ private static boolean copyFile(final File srcFile, final File destFile, final OnReplaceListener listener) { return copyOrMoveFile(srcFile, destFile, listener, false); } /** * Move the directory or file. * * @param srcPath The path of source. * @param destPath The path of destination. * @return {@code true}: success<br>{@code false}: fail */ public static boolean move(final String srcPath, final String destPath) { return move(getFileByPath(srcPath), getFileByPath(destPath), null); } /** * Move the directory or file. * * @param srcPath The path of source. * @param destPath The path of destination. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean move(final String srcPath, final String destPath, final OnReplaceListener listener) { return move(getFileByPath(srcPath), getFileByPath(destPath), listener); } /** * Move the directory or file. * * @param src The source. * @param dest The destination. * @return {@code true}: success<br>{@code false}: fail */ public static boolean move(final File src, final File dest) { return move(src, dest, null); } /** * Move the directory or file. * * @param src The source. * @param dest The destination. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean move(final File src, final File dest, final OnReplaceListener listener) { if (src == null) return false; if (src.isDirectory()) { return moveDir(src, dest, listener); } return moveFile(src, dest, listener); } /** * Move the directory. * * @param srcDir The source directory. * @param destDir The destination directory. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean moveDir(final File srcDir, final File destDir, final OnReplaceListener listener) { return copyOrMoveDir(srcDir, destDir, listener, true); } /** * Move the file. * * @param srcFile The source file. * @param destFile The destination file. * @param listener The replace listener. * @return {@code true}: success<br>{@code false}: fail */ public static boolean moveFile(final File srcFile, final File destFile, final OnReplaceListener listener) { return copyOrMoveFile(srcFile, destFile, listener, true); } private static boolean copyOrMoveDir(final File srcDir, final File destDir, final OnReplaceListener listener, final boolean isMove) { if (srcDir == null || destDir == null) return false; // destDir's path locate in srcDir's path then return false String srcPath = srcDir.getPath() + File.separator; String destPath = destDir.getPath() + File.separator; if (destPath.contains(srcPath)) return false; if (!srcDir.exists() || !srcDir.isDirectory()) return false; if (!createOrExistsDir(destDir)) return false; File[] files = srcDir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { File oneDestFile = new File(destPath + file.getName()); if (file.isFile()) { if (!copyOrMoveFile(file, oneDestFile, listener, isMove)) return false; } else if (file.isDirectory()) { if (!copyOrMoveDir(file, oneDestFile, listener, isMove)) return false; } } } return !isMove || deleteDir(srcDir); } private static boolean copyOrMoveFile(final File srcFile, final File destFile, final OnReplaceListener listener, final boolean isMove) { if (srcFile == null || destFile == null) return false; // srcFile equals destFile then return false if (srcFile.equals(destFile)) return false; // srcFile doesn't exist or isn't a file then return false if (!srcFile.exists() || !srcFile.isFile()) return false; if (destFile.exists()) { if (listener == null || listener.onReplace(srcFile, destFile)) {// require delete the old file if (!destFile.delete()) {// unsuccessfully delete then return false return false; } } else { return true; } } if (!createOrExistsDir(destFile.getParentFile())) return false; try { return UtilsBridge.writeFileFromIS(destFile.getAbsolutePath(), new FileInputStream(srcFile)) && !(isMove && !deleteFile(srcFile)); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } /** * Delete the directory. * * @param filePath The path of file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean delete(final String filePath) { return delete(getFileByPath(filePath)); } /** * Delete the directory. * * @param file The file. * @return {@code true}: success<br>{@code false}: fail */ public static boolean delete(final File file) { if (file == null) return false; if (file.isDirectory()) { return deleteDir(file); } return deleteFile(file); } /** * Delete the directory. * * @param dir The directory. * @return {@code true}: success<br>{@code false}: fail */ private static boolean deleteDir(final File dir) { if (dir == null) return false; // dir doesn't exist then return true if (!dir.exists()) return true; // dir isn't a directory then return false if (!dir.isDirectory()) return false; File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (file.isFile()) { if (!file.delete()) return false; } else if (file.isDirectory()) { if (!deleteDir(file)) return false; } } } return dir.delete(); } /** * Delete the file. * * @param file The file. * @return {@code true}: success<br>{@code false}: fail */ private static boolean deleteFile(final File file) { return file != null && (!file.exists() || file.isFile() && file.delete()); } /** * Delete the all in directory. * * @param dirPath The path of directory. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteAllInDir(final String dirPath) { return deleteAllInDir(getFileByPath(dirPath)); } /** * Delete the all in directory. * * @param dir The directory. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteAllInDir(final File dir) { return deleteFilesInDirWithFilter(dir, new FileFilter() { @Override public boolean accept(File pathname) { return true; } }); } /** * Delete all files in directory. * * @param dirPath The path of directory. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteFilesInDir(final String dirPath) { return deleteFilesInDir(getFileByPath(dirPath)); } /** * Delete all files in directory. * * @param dir The directory. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteFilesInDir(final File dir) { return deleteFilesInDirWithFilter(dir, new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile(); } }); } /** * Delete all files that satisfy the filter in directory. * * @param dirPath The path of directory. * @param filter The filter. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteFilesInDirWithFilter(final String dirPath, final FileFilter filter) { return deleteFilesInDirWithFilter(getFileByPath(dirPath), filter); } /** * Delete all files that satisfy the filter in directory. * * @param dir The directory. * @param filter The filter. * @return {@code true}: success<br>{@code false}: fail */ public static boolean deleteFilesInDirWithFilter(final File dir, final FileFilter filter) { if (dir == null || filter == null) return false; // dir doesn't exist then return true if (!dir.exists()) return true; // dir isn't a directory then return false if (!dir.isDirectory()) return false; File[] files = dir.listFiles(); if (files != null && files.length != 0) { for (File file : files) { if (filter.accept(file)) { if (file.isFile()) { if (!file.delete()) return false; } else if (file.isDirectory()) { if (!deleteDir(file)) return false; } } } } return true; } /** * Return the files in directory. * <p>Doesn't traverse subdirectories</p> * * @param dirPath The path of directory. * @return the files in directory */ public static List<File> listFilesInDir(final String dirPath) { return listFilesInDir(dirPath, null); } /** * Return the files in directory. * <p>Doesn't traverse subdirectories</p> * * @param dir The directory. * @return the files in directory */ public static List<File> listFilesInDir(final File dir) { return listFilesInDir(dir, null); } /** * Return the files in directory. * <p>Doesn't traverse subdirectories</p> * * @param dirPath The path of directory. * @param comparator The comparator to determine the order of the list. * @return the files in directory */ public static List<File> listFilesInDir(final String dirPath, Comparator<File> comparator) { return listFilesInDir(getFileByPath(dirPath), false, comparator); } /** * Return the files in directory. * <p>Doesn't traverse subdirectories</p> * * @param dir The directory. * @param comparator The comparator to determine the order of the list. * @return the files in directory */ public static List<File> listFilesInDir(final File dir, Comparator<File> comparator) { return listFilesInDir(dir, false, comparator); } /** * Return the files in directory. * * @param dirPath The path of directory. * @param isRecursive True to traverse subdirectories, false otherwise. * @return the files in directory */ public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive) { return listFilesInDir(getFileByPath(dirPath), isRecursive); } /** * Return the files in directory. * * @param dir The directory. * @param isRecursive True to traverse subdirectories, false otherwise. * @return the files in directory */ public static List<File> listFilesInDir(final File dir, final boolean isRecursive) { return listFilesInDir(dir, isRecursive, null); } /** * Return the files in directory. * * @param dirPath The path of directory. * @param isRecursive True to traverse subdirectories, false otherwise. * @param comparator The comparator to determine the order of the list. * @return the files in directory */ public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive, final Comparator<File> comparator) { return listFilesInDir(getFileByPath(dirPath), isRecursive, comparator); } /** * Return the files in directory. * * @param dir The directory. * @param isRecursive True to traverse subdirectories, false otherwise. * @param comparator The comparator to determine the order of the list. * @return the files in directory */ public static List<File> listFilesInDir(final File dir, final boolean isRecursive, final Comparator<File> comparator) { return listFilesInDirWithFilter(dir, new FileFilter() { @Override public boolean accept(File pathname) { return true; } }, isRecursive, comparator); } /** * Return the files that satisfy the filter in directory. * <p>Doesn't traverse subdirectories</p> * * @param dirPath The path of directory. * @param filter The filter. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final String dirPath, final FileFilter filter) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter); } /** * Return the files that satisfy the filter in directory. * <p>Doesn't traverse subdirectories</p> * * @param dir The directory. * @param filter The filter. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final File dir, final FileFilter filter) { return listFilesInDirWithFilter(dir, filter, false, null); } /** * Return the files that satisfy the filter in directory. * <p>Doesn't traverse subdirectories</p> * * @param dirPath The path of directory. * @param filter The filter. * @param comparator The comparator to determine the order of the list. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final String dirPath, final FileFilter filter, final Comparator<File> comparator) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter, comparator); } /** * Return the files that satisfy the filter in directory. * <p>Doesn't traverse subdirectories</p> * * @param dir The directory. * @param filter The filter. * @param comparator The comparator to determine the order of the list. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final File dir, final FileFilter filter, final Comparator<File> comparator) { return listFilesInDirWithFilter(dir, filter, false, comparator); } /** * Return the files that satisfy the filter in directory. * * @param dirPath The path of directory. * @param filter The filter. * @param isRecursive True to traverse subdirectories, false otherwise. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final String dirPath, final FileFilter filter, final boolean isRecursive) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive); } /** * Return the files that satisfy the filter in directory. * * @param dir The directory. * @param filter The filter. * @param isRecursive True to traverse subdirectories, false otherwise. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final File dir, final FileFilter filter, final boolean isRecursive) { return listFilesInDirWithFilter(dir, filter, isRecursive, null); } /** * Return the files that satisfy the filter in directory. * * @param dirPath The path of directory. * @param filter The filter. * @param isRecursive True to traverse subdirectories, false otherwise. * @param comparator The comparator to determine the order of the list. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final String dirPath, final FileFilter filter, final boolean isRecursive, final Comparator<File> comparator) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive, comparator); } /** * Return the files that satisfy the filter in directory. * * @param dir The directory. * @param filter The filter. * @param isRecursive True to traverse subdirectories, false otherwise. * @param comparator The comparator to determine the order of the list. * @return the files that satisfy the filter in directory */ public static List<File> listFilesInDirWithFilter(final File dir, final FileFilter filter, final boolean isRecursive, final Comparator<File> comparator) { List<File> files = listFilesInDirWithFilterInner(dir, filter, isRecursive); if (comparator != null) { Collections.sort(files, comparator); } return files; } private static List<File> listFilesInDirWithFilterInner(final File dir, final FileFilter filter, final boolean isRecursive) { List<File> list = new ArrayList<>(); if (!isDir(dir)) return list; File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (filter.accept(file)) { list.add(file); } if (isRecursive && file.isDirectory()) { list.addAll(listFilesInDirWithFilterInner(file, filter, true)); } } } return list; } /** * Return the time that the file was last modified. * * @param filePath The path of file. * @return the time that the file was last modified */ public static long getFileLastModified(final String filePath) { return getFileLastModified(getFileByPath(filePath)); } /** * Return the time that the file was last modified. * * @param file The file. * @return the time that the file was last modified */ public static long getFileLastModified(final File file) { if (file == null) return -1; return file.lastModified(); } /** * Return the charset of file simply. * * @param filePath The path of file. * @return the charset of file simply */ public static String getFileCharsetSimple(final String filePath) { return getFileCharsetSimple(getFileByPath(filePath)); } /** * Return the charset of file simply. * * @param file The file. * @return the charset of file simply */ public static String getFileCharsetSimple(final File file) { if (file == null) return ""; if (isUtf8(file)) return "UTF-8"; int p = 0; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); p = (is.read() << 8) + is.read(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } switch (p) { case 0xfffe: return "Unicode"; case 0xfeff: return "UTF-16BE"; default: return "GBK"; } } /** * Return whether the charset of file is utf8. * * @param filePath The path of file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isUtf8(final String filePath) { return isUtf8(getFileByPath(filePath)); } /** * Return whether the charset of file is utf8. * * @param file The file. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isUtf8(final File file) { if (file == null) return false; InputStream is = null; try { byte[] bytes = new byte[24]; is = new BufferedInputStream(new FileInputStream(file)); int read = is.read(bytes); if (read != -1) { byte[] readArr = new byte[read]; System.arraycopy(bytes, 0, readArr, 0, read); return isUtf8(readArr) == 100; } else { return false; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; } /** * UTF-8 * ---------------------------------------------- * 0xxxxxxx * 110xxxxx 10xxxxxx * 1110xxxx 10xxxxxx 10xxxxxx * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ private static int isUtf8(byte[] raw) { int i, len; int utf8 = 0, ascii = 0; if (raw.length > 3) { if ((raw[0] == (byte) 0xEF) && (raw[1] == (byte) 0xBB) && (raw[2] == (byte) 0xBF)) { return 100; } } len = raw.length; int child = 0; for (i = 0; i < len; ) { // UTF-8 byte shouldn't be FF and FE if ((raw[i] & (byte) 0xFF) == (byte) 0xFF || (raw[i] & (byte) 0xFE) == (byte) 0xFE) { return 0; } if (child == 0) { // ASCII format is 0x0******* if ((raw[i] & (byte) 0x7F) == raw[i] && raw[i] != 0) { ascii++; } else if ((raw[i] & (byte) 0xC0) == (byte) 0xC0) { // 0x11****** maybe is UTF-8 for (int bit = 0; bit < 8; bit++) { if ((((byte) (0x80 >> bit)) & raw[i]) == ((byte) (0x80 >> bit))) { child = bit; } else { break; } } utf8++; } i++; } else { child = (raw.length - i > child) ? child : (raw.length - i); boolean currentNotUtf8 = false; for (int children = 0; children < child; children++) { // format must is 0x10****** if ((raw[i + children] & ((byte) 0x80)) != ((byte) 0x80)) { if ((raw[i + children] & (byte) 0x7F) == raw[i + children] && raw[i] != 0) { // ASCII format is 0x0******* ascii++; } currentNotUtf8 = true; } } if (currentNotUtf8) { utf8--; i++; } else { utf8 += child; i += child; } child = 0; } } // UTF-8 contains ASCII if (ascii == len) { return 100; } return (int) (100 * ((float) (utf8 + ascii) / (float) len)); } /** * Return the number of lines of file. * * @param filePath The path of file. * @return the number of lines of file */ public static int getFileLines(final String filePath) { return getFileLines(getFileByPath(filePath)); } /** * Return the number of lines of file. * * @param file The file. * @return the number of lines of file */ public static int getFileLines(final File file) { int count = 1; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int readChars; if (LINE_SEP.endsWith("\n")) { while ((readChars = is.read(buffer, 0, 1024)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\n') ++count; } } } else { while ((readChars = is.read(buffer, 0, 1024)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\r') ++count; } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return count; } /** * Return the size. * * @param filePath The path of file. * @return the size */ public static String getSize(final String filePath) { return getSize(getFileByPath(filePath)); } /** * Return the size. * * @param file The directory. * @return the size */ public static String getSize(final File file) { if (file == null) return ""; if (file.isDirectory()) { return getDirSize(file); } return getFileSize(file); } /** * Return the size of directory. * * @param dir The directory. * @return the size of directory */ private static String getDirSize(final File dir) { long len = getDirLength(dir); return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len); } /** * Return the size of file. * * @param file The file. * @return the length of file */ private static String getFileSize(final File file) { long len = getFileLength(file); return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len); } /** * Return the length. * * @param filePath The path of file. * @return the length */ public static long getLength(final String filePath) { return getLength(getFileByPath(filePath)); } /** * Return the length. * * @param file The file. * @return the length */ public static long getLength(final File file) { if (file == null) return 0; if (file.isDirectory()) { return getDirLength(file); } return getFileLength(file); } /** * Return the length of directory. * * @param dir The directory. * @return the length of directory */ private static long getDirLength(final File dir) { if (!isDir(dir)) return 0; long len = 0; File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (file.isDirectory()) { len += getDirLength(file); } else { len += file.length(); } } } return len; } /** * Return the length of file. * * @param filePath The path of file. * @return the length of file */ public static long getFileLength(final String filePath) { boolean isURL = filePath.matches("[a-zA-z]+://[^\\s]*"); if (isURL) { try { HttpsURLConnection conn = (HttpsURLConnection) new URL(filePath).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.connect(); if (conn.getResponseCode() == 200) { return conn.getContentLength(); } return -1; } catch (IOException e) { e.printStackTrace(); } } return getFileLength(getFileByPath(filePath)); } /** * Return the length of file. * * @param file The file. * @return the length of file */ private static long getFileLength(final File file) { if (!isFile(file)) return -1; return file.length(); } /** * Return the MD5 of file. * * @param filePath The path of file. * @return the md5 of file */ public static String getFileMD5ToString(final String filePath) { File file = UtilsBridge.isSpace(filePath) ? null : new File(filePath); return getFileMD5ToString(file); } /** * Return the MD5 of file. * * @param file The file. * @return the md5 of file */ public static String getFileMD5ToString(final File file) { return UtilsBridge.bytes2HexString(getFileMD5(file)); } /** * Return the MD5 of file. * * @param filePath The path of file. * @return the md5 of file */ public static byte[] getFileMD5(final String filePath) { return getFileMD5(getFileByPath(filePath)); } /** * Return the MD5 of file. * * @param file The file. * @return the md5 of file */ public static byte[] getFileMD5(final File file) { if (file == null) return null; DigestInputStream dis = null; try { FileInputStream fis = new FileInputStream(file); MessageDigest md = MessageDigest.getInstance("MD5"); dis = new DigestInputStream(fis, md); byte[] buffer = new byte[1024 * 256]; while (true) { if (!(dis.read(buffer) > 0)) break; } md = dis.getMessageDigest(); return md.digest(); } catch (NoSuchAlgorithmException | IOException e) { e.printStackTrace(); } finally { try { if (dis != null) { dis.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Return the file's path of directory. * * @param file The file. * @return the file's path of directory */ public static String getDirName(final File file) { if (file == null) return ""; return getDirName(file.getAbsolutePath()); } /** * Return the file's path of directory. * * @param filePath The path of file. * @return the file's path of directory */ public static String getDirName(final String filePath) { if (UtilsBridge.isSpace(filePath)) return ""; int lastSep = filePath.lastIndexOf(File.separator); return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1); } /** * Return the name of file. * * @param file The file. * @return the name of file */ public static String getFileName(final File file) { if (file == null) return ""; return getFileName(file.getAbsolutePath()); } /** * Return the name of file. * * @param filePath The path of file. * @return the name of file */ public static String getFileName(final String filePath) { if (UtilsBridge.isSpace(filePath)) return ""; int lastSep = filePath.lastIndexOf(File.separator); return lastSep == -1 ? filePath : filePath.substring(lastSep + 1); } /** * Return the name of file without extension. * * @param file The file. * @return the name of file without extension */ public static String getFileNameNoExtension(final File file) { if (file == null) return ""; return getFileNameNoExtension(file.getPath()); } /** * Return the name of file without extension. * * @param filePath The path of file. * @return the name of file without extension */ public static String getFileNameNoExtension(final String filePath) { if (UtilsBridge.isSpace(filePath)) return ""; int lastPoi = filePath.lastIndexOf('.'); int lastSep = filePath.lastIndexOf(File.separator); if (lastSep == -1) { return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi)); } if (lastPoi == -1 || lastSep > lastPoi) { return filePath.substring(lastSep + 1); } return filePath.substring(lastSep + 1, lastPoi); } /** * Return the extension of file. * * @param file The file. * @return the extension of file */ public static String getFileExtension(final File file) { if (file == null) return ""; return getFileExtension(file.getPath()); } /** * Return the extension of file. * * @param filePath The path of file. * @return the extension of file */ public static String getFileExtension(final String filePath) { if (UtilsBridge.isSpace(filePath)) return ""; int lastPoi = filePath.lastIndexOf('.'); int lastSep = filePath.lastIndexOf(File.separator); if (lastPoi == -1 || lastSep >= lastPoi) return ""; return filePath.substring(lastPoi + 1); } /** * Notify system to scan the file. * * @param filePath The path of file. */ public static void notifySystemToScan(final String filePath) { notifySystemToScan(getFileByPath(filePath)); } /** * Notify system to scan the file. * * @param file The file. */ public static void notifySystemToScan(final File file) { if (file == null || !file.exists()) return; Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.parse("file://" + file.getAbsolutePath())); Utils.getApp().sendBroadcast(intent); } /** * Return the total size of file system. * * @param anyPathInFs Any path in file system. * @return the total size of file system */ public static long getFsTotalSize(String anyPathInFs) { if (TextUtils.isEmpty(anyPathInFs)) return 0; StatFs statFs = new StatFs(anyPathInFs); long blockSize; long totalSize; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFs.getBlockSizeLong(); totalSize = statFs.getBlockCountLong(); } else { blockSize = statFs.getBlockSize(); totalSize = statFs.getBlockCount(); } return blockSize * totalSize; } /** * Return the available size of file system. * * @param anyPathInFs Any path in file system. * @return the available size of file system */ public static long getFsAvailableSize(final String anyPathInFs) { if (TextUtils.isEmpty(anyPathInFs)) return 0; StatFs statFs = new StatFs(anyPathInFs); long blockSize; long availableSize; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFs.getBlockSizeLong(); availableSize = statFs.getAvailableBlocksLong(); } else { blockSize = statFs.getBlockSize(); availableSize = statFs.getAvailableBlocks(); } return blockSize * availableSize; } /////////////////////////////////////////////////////////////////////////// // interface /////////////////////////////////////////////////////////////////////////// public interface OnReplaceListener { boolean onReplace(File srcFile, File destFile); } } ```
/content/code_sandbox/lib/utilcode/src/main/java/com/blankj/utilcode/util/FileUtils.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
10,274
```java package com.blankj.utilcode.util; import android.annotation.SuppressLint; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.util.Properties; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/07/04 * desc : utils about rom * </pre> */ public final class RomUtils { private static final String[] ROM_HUAWEI = {"huawei"}; private static final String[] ROM_VIVO = {"vivo"}; private static final String[] ROM_XIAOMI = {"xiaomi"}; private static final String[] ROM_OPPO = {"oppo"}; private static final String[] ROM_LEECO = {"leeco", "letv"}; private static final String[] ROM_360 = {"360", "qiku"}; private static final String[] ROM_ZTE = {"zte"}; private static final String[] ROM_ONEPLUS = {"oneplus"}; private static final String[] ROM_NUBIA = {"nubia"}; private static final String[] ROM_COOLPAD = {"coolpad", "yulong"}; private static final String[] ROM_LG = {"lg", "lge"}; private static final String[] ROM_GOOGLE = {"google"}; private static final String[] ROM_SAMSUNG = {"samsung"}; private static final String[] ROM_MEIZU = {"meizu"}; private static final String[] ROM_LENOVO = {"lenovo"}; private static final String[] ROM_SMARTISAN = {"smartisan", "deltainno"}; private static final String[] ROM_HTC = {"htc"}; private static final String[] ROM_SONY = {"sony"}; private static final String[] ROM_GIONEE = {"gionee", "amigo"}; private static final String[] ROM_MOTOROLA = {"motorola"}; private static final String VERSION_PROPERTY_HUAWEI = "ro.build.version.emui"; private static final String VERSION_PROPERTY_VIVO = "ro.vivo.os.build.display.id"; private static final String VERSION_PROPERTY_XIAOMI = "ro.build.version.incremental"; private static final String VERSION_PROPERTY_OPPO = "ro.build.version.opporom"; private static final String VERSION_PROPERTY_LEECO = "ro.letv.release.version"; private static final String VERSION_PROPERTY_360 = "ro.build.uiversion"; private static final String VERSION_PROPERTY_ZTE = "ro.build.MiFavor_version"; private static final String VERSION_PROPERTY_ONEPLUS = "ro.rom.version"; private static final String VERSION_PROPERTY_NUBIA = "ro.build.rom.id"; private final static String UNKNOWN = "unknown"; private static RomInfo bean = null; private RomUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return whether the rom is made by huawei. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isHuawei() { return ROM_HUAWEI[0].equals(getRomInfo().name); } /** * Return whether the rom is made by vivo. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isVivo() { return ROM_VIVO[0].equals(getRomInfo().name); } /** * Return whether the rom is made by xiaomi. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isXiaomi() { return ROM_XIAOMI[0].equals(getRomInfo().name); } /** * Return whether the rom is made by oppo. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isOppo() { return ROM_OPPO[0].equals(getRomInfo().name); } /** * Return whether the rom is made by leeco. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isLeeco() { return ROM_LEECO[0].equals(getRomInfo().name); } /** * Return whether the rom is made by 360. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean is360() { return ROM_360[0].equals(getRomInfo().name); } /** * Return whether the rom is made by zte. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isZte() { return ROM_ZTE[0].equals(getRomInfo().name); } /** * Return whether the rom is made by oneplus. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isOneplus() { return ROM_ONEPLUS[0].equals(getRomInfo().name); } /** * Return whether the rom is made by nubia. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNubia() { return ROM_NUBIA[0].equals(getRomInfo().name); } /** * Return whether the rom is made by coolpad. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isCoolpad() { return ROM_COOLPAD[0].equals(getRomInfo().name); } /** * Return whether the rom is made by lg. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isLg() { return ROM_LG[0].equals(getRomInfo().name); } /** * Return whether the rom is made by google. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isGoogle() { return ROM_GOOGLE[0].equals(getRomInfo().name); } /** * Return whether the rom is made by samsung. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isSamsung() { return ROM_SAMSUNG[0].equals(getRomInfo().name); } /** * Return whether the rom is made by meizu. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isMeizu() { return ROM_MEIZU[0].equals(getRomInfo().name); } /** * Return whether the rom is made by lenovo. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isLenovo() { return ROM_LENOVO[0].equals(getRomInfo().name); } /** * Return whether the rom is made by smartisan. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isSmartisan() { return ROM_SMARTISAN[0].equals(getRomInfo().name); } /** * Return whether the rom is made by htc. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isHtc() { return ROM_HTC[0].equals(getRomInfo().name); } /** * Return whether the rom is made by sony. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isSony() { return ROM_SONY[0].equals(getRomInfo().name); } /** * Return whether the rom is made by gionee. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isGionee() { return ROM_GIONEE[0].equals(getRomInfo().name); } /** * Return whether the rom is made by motorola. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isMotorola() { return ROM_MOTOROLA[0].equals(getRomInfo().name); } /** * Return the rom's information. * * @return the rom's information */ public static RomInfo getRomInfo() { if (bean != null) return bean; bean = new RomInfo(); final String brand = getBrand(); final String manufacturer = getManufacturer(); if (isRightRom(brand, manufacturer, ROM_HUAWEI)) { bean.name = ROM_HUAWEI[0]; String version = getRomVersion(VERSION_PROPERTY_HUAWEI); String[] temp = version.split("_"); if (temp.length > 1) { bean.version = temp[1]; } else { bean.version = version; } return bean; } if (isRightRom(brand, manufacturer, ROM_VIVO)) { bean.name = ROM_VIVO[0]; bean.version = getRomVersion(VERSION_PROPERTY_VIVO); return bean; } if (isRightRom(brand, manufacturer, ROM_XIAOMI)) { bean.name = ROM_XIAOMI[0]; bean.version = getRomVersion(VERSION_PROPERTY_XIAOMI); return bean; } if (isRightRom(brand, manufacturer, ROM_OPPO)) { bean.name = ROM_OPPO[0]; bean.version = getRomVersion(VERSION_PROPERTY_OPPO); return bean; } if (isRightRom(brand, manufacturer, ROM_LEECO)) { bean.name = ROM_LEECO[0]; bean.version = getRomVersion(VERSION_PROPERTY_LEECO); return bean; } if (isRightRom(brand, manufacturer, ROM_360)) { bean.name = ROM_360[0]; bean.version = getRomVersion(VERSION_PROPERTY_360); return bean; } if (isRightRom(brand, manufacturer, ROM_ZTE)) { bean.name = ROM_ZTE[0]; bean.version = getRomVersion(VERSION_PROPERTY_ZTE); return bean; } if (isRightRom(brand, manufacturer, ROM_ONEPLUS)) { bean.name = ROM_ONEPLUS[0]; bean.version = getRomVersion(VERSION_PROPERTY_ONEPLUS); return bean; } if (isRightRom(brand, manufacturer, ROM_NUBIA)) { bean.name = ROM_NUBIA[0]; bean.version = getRomVersion(VERSION_PROPERTY_NUBIA); return bean; } if (isRightRom(brand, manufacturer, ROM_COOLPAD)) { bean.name = ROM_COOLPAD[0]; } else if (isRightRom(brand, manufacturer, ROM_LG)) { bean.name = ROM_LG[0]; } else if (isRightRom(brand, manufacturer, ROM_GOOGLE)) { bean.name = ROM_GOOGLE[0]; } else if (isRightRom(brand, manufacturer, ROM_SAMSUNG)) { bean.name = ROM_SAMSUNG[0]; } else if (isRightRom(brand, manufacturer, ROM_MEIZU)) { bean.name = ROM_MEIZU[0]; } else if (isRightRom(brand, manufacturer, ROM_LENOVO)) { bean.name = ROM_LENOVO[0]; } else if (isRightRom(brand, manufacturer, ROM_SMARTISAN)) { bean.name = ROM_SMARTISAN[0]; } else if (isRightRom(brand, manufacturer, ROM_HTC)) { bean.name = ROM_HTC[0]; } else if (isRightRom(brand, manufacturer, ROM_SONY)) { bean.name = ROM_SONY[0]; } else if (isRightRom(brand, manufacturer, ROM_GIONEE)) { bean.name = ROM_GIONEE[0]; } else if (isRightRom(brand, manufacturer, ROM_MOTOROLA)) { bean.name = ROM_MOTOROLA[0]; } else { bean.name = manufacturer; } bean.version = getRomVersion(""); return bean; } private static boolean isRightRom(final String brand, final String manufacturer, final String... names) { for (String name : names) { if (brand.contains(name) || manufacturer.contains(name)) { return true; } } return false; } private static String getManufacturer() { try { String manufacturer = Build.MANUFACTURER; if (!TextUtils.isEmpty(manufacturer)) { return manufacturer.toLowerCase(); } } catch (Throwable ignore) {/**/} return UNKNOWN; } private static String getBrand() { try { String brand = Build.BRAND; if (!TextUtils.isEmpty(brand)) { return brand.toLowerCase(); } } catch (Throwable ignore) {/**/} return UNKNOWN; } private static String getRomVersion(final String propertyName) { String ret = ""; if (!TextUtils.isEmpty(propertyName)) { ret = getSystemProperty(propertyName); } if (TextUtils.isEmpty(ret) || ret.equals(UNKNOWN)) { try { String display = Build.DISPLAY; if (!TextUtils.isEmpty(display)) { ret = display.toLowerCase(); } } catch (Throwable ignore) {/**/} } if (TextUtils.isEmpty(ret)) { return UNKNOWN; } return ret; } private static String getSystemProperty(final String name) { String prop = getSystemPropertyByShell(name); if (!TextUtils.isEmpty(prop)) return prop; prop = getSystemPropertyByStream(name); if (!TextUtils.isEmpty(prop)) return prop; if (Build.VERSION.SDK_INT < 28) { return getSystemPropertyByReflect(name); } return prop; } private static String getSystemPropertyByShell(final String propName) { String line; BufferedReader input = null; try { Process p = Runtime.getRuntime().exec("getprop " + propName); input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024); String ret = input.readLine(); if (ret != null) { return ret; } } catch (IOException ignore) { } finally { if (input != null) { try { input.close(); } catch (IOException ignore) {/**/} } } return ""; } private static String getSystemPropertyByStream(final String key) { try { Properties prop = new Properties(); FileInputStream is = new FileInputStream( new File(Environment.getRootDirectory(), "build.prop") ); prop.load(is); return prop.getProperty(key, ""); } catch (Exception ignore) {/**/} return ""; } private static String getSystemPropertyByReflect(String key) { try { @SuppressLint("PrivateApi") Class<?> clz = Class.forName("android.os.SystemProperties"); Method getMethod = clz.getMethod("get", String.class, String.class); return (String) getMethod.invoke(clz, key, ""); } catch (Exception e) {/**/} return ""; } public static class RomInfo { private String name; private String version; public String getName() { return name; } public String getVersion() { return version; } @Override public String toString() { return "RomInfo{name=" + name + ", version=" + version + "}"; } } } ```
/content/code_sandbox/lib/utilcode/src/main/java/com/blankj/utilcode/util/RomUtils.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,462
```java package com.blankj.utilcode.util; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/01/04 * desc : test CacheMemoryStaticUtils * </pre> */ public class CacheMemoryStaticUtilsTest extends BaseTest { private CacheMemoryUtils mCacheMemoryUtils = CacheMemoryUtils.getInstance(3); @Before public void setUp() { for (int i = 0; i < 10; i++) { CacheMemoryStaticUtils.put(String.valueOf(i), i); } for (int i = 0; i < 10; i++) { CacheMemoryStaticUtils.put(String.valueOf(i), i, mCacheMemoryUtils); } } @Test public void get() { for (int i = 0; i < 10; i++) { assertEquals(i, CacheMemoryStaticUtils.get(String.valueOf(i))); } for (int i = 0; i < 10; i++) { if (i < 7) { assertNull(CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils)); } else { assertEquals(i, CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils)); } } } @Test public void getExpired() throws Exception { CacheMemoryStaticUtils.put("10", 10, 2 * CacheMemoryUtils.SEC); assertEquals(10, CacheMemoryStaticUtils.get("10")); Thread.sleep(1500); assertEquals(10, CacheMemoryStaticUtils.get("10")); Thread.sleep(1500); assertNull(CacheMemoryStaticUtils.get("10")); } @Test public void getDefault() { assertNull(CacheMemoryStaticUtils.get("10")); assertEquals("10", CacheMemoryStaticUtils.get("10", "10")); } @Test public void getCacheCount() { assertEquals(10, CacheMemoryStaticUtils.getCacheCount()); assertEquals(3, CacheMemoryStaticUtils.getCacheCount(mCacheMemoryUtils)); } @Test public void remove() { assertEquals(0, CacheMemoryStaticUtils.remove("0")); assertNull(CacheMemoryStaticUtils.get("0")); assertNull(CacheMemoryStaticUtils.remove("0")); } @Test public void clear() { CacheMemoryStaticUtils.clear(); CacheMemoryStaticUtils.clear(mCacheMemoryUtils); for (int i = 0; i < 10; i++) { assertNull(CacheMemoryStaticUtils.get(String.valueOf(i))); } for (int i = 0; i < 10; i++) { assertNull(CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils)); } assertEquals(0, CacheMemoryStaticUtils.getCacheCount()); assertEquals(0, CacheMemoryStaticUtils.getCacheCount(mCacheMemoryUtils)); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryStaticUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
648
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/09/26 * desc : test GsonUtils * </pre> */ public class GsonUtilsTest extends BaseTest { @Test public void getGson() { Assert.assertNotNull(GsonUtils.getGson()); } @Test public void toJson() { Result<Person> result = new Result<>(new Person("Blankj")); Assert.assertEquals( "{\"code\":200,\"message\":\"success\",\"data\":{\"name\":\"Blankj\",\"gender\":0,\"address\":null}}", GsonUtils.toJson(result) ); } @Test public void fromJson() { List<Person> people = new ArrayList<>(); people.add(new Person("Blankj")); people.add(new Person("Ming")); Result<List<Person>> result = new Result<>(people); Assert.assertEquals( GsonUtils.toJson(result), GsonUtils.toJson( GsonUtils.fromJson( GsonUtils.toJson(result), GsonUtils.getType(Result.class, GsonUtils.getListType(Person.class)) ) ) ); } @Test public void getType() { Assert.assertEquals( "java.util.List<java.lang.String>", GsonUtils.getListType(String.class).toString() ); Assert.assertEquals( "java.util.Map<java.lang.String, java.lang.Integer>", GsonUtils.getMapType(String.class, Integer.class).toString() ); Assert.assertEquals( "java.lang.String[]", GsonUtils.getArrayType(String.class).toString() ); Assert.assertEquals( "com.blankj.utilcode.util.GsonUtilsTest$Result<java.lang.String>", GsonUtils.getType(Result.class, String.class).toString() ); Assert.assertEquals( "java.util.Map<java.lang.String, java.util.List<java.lang.String>>", GsonUtils.getMapType(String.class, GsonUtils.getListType(String.class)).toString() ); } static class Result<T> { int code; String message; T data; Result(T data) { this.code = 200; this.message = "success"; this.data = data; } } static class Person { String name; int gender; String address; Person(String name) { this.name = name; } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/GsonUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
531
```java package com.blankj.utilcode.util; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CountDownLatch; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/07/11 * desc : * </pre> */ public class BusUtilsTest extends BaseTest { private static final String TAG_NO_PARAM = "TagNoParam"; private static final String TAG_ONE_PARAM = "TagOneParam"; private static final String TAG_NO_PARAM_STICKY = "TagNoParamSticky"; private static final String TAG_ONE_PARAM_STICKY = "TagOneParamSticky"; private static final String TAG_IO = "TAG_IO"; private static final String TAG_CPU = "TAG_CPU"; private static final String TAG_CACHED = "TAG_CACHED"; private static final String TAG_SINGLE = "TAG_SINGLE"; @BusUtils.Bus(tag = TAG_NO_PARAM) public void noParamFun() { System.out.println("noParam"); } @BusUtils.Bus(tag = TAG_NO_PARAM) public void noParamSameTagFun() { System.out.println("sameTag: noParam"); } @BusUtils.Bus(tag = TAG_ONE_PARAM) public void oneParamFun(String param) { System.out.println(param); } @BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true) public void foo() { System.out.println("foo"); } @BusUtils.Bus(tag = TAG_ONE_PARAM_STICKY, sticky = true) public void oneParamStickyFun(Callback callback) { if (callback != null) { System.out.println(callback.call()); } } @BusUtils.Bus(tag = TAG_IO, threadMode = BusUtils.ThreadMode.IO) public void ioFun(CountDownLatch latch) { System.out.println("Thread.currentThread() = " + Thread.currentThread()); latch.countDown(); } @BusUtils.Bus(tag = TAG_CPU, threadMode = BusUtils.ThreadMode.CPU) public void cpuFun(CountDownLatch latch) { System.out.println("Thread.currentThread() = " + Thread.currentThread()); latch.countDown(); } @BusUtils.Bus(tag = TAG_CACHED, threadMode = BusUtils.ThreadMode.CACHED) public void cachedFun(CountDownLatch latch) { System.out.println("Thread.currentThread() = " + Thread.currentThread()); latch.countDown(); } @BusUtils.Bus(tag = TAG_SINGLE, threadMode = BusUtils.ThreadMode.SINGLE) public void singleFun(CountDownLatch latch) { System.out.println("Thread.currentThread() = " + Thread.currentThread()); latch.countDown(); } @Before public void setUp() throws Exception { BusUtils.registerBus4Test(TAG_NO_PARAM, BusUtilsTest.class.getName(), "noParamFun", "", "", false, "POSTING", 0); BusUtils.registerBus4Test(TAG_ONE_PARAM, BusUtilsTest.class.getName(), "oneParamFun", String.class.getName(), "param", false, "POSTING", 0); BusUtils.registerBus4Test(TAG_NO_PARAM_STICKY, BusUtilsTest.class.getName(), "noParamStickyFun", "", "", true, "POSTING", 0); BusUtils.registerBus4Test(TAG_NO_PARAM_STICKY, BusUtilsTest.class.getName(), "foo", "", "", true, "POSTING", 0); BusUtils.registerBus4Test(TAG_ONE_PARAM_STICKY, BusUtilsTest.class.getName(), "oneParamStickyFun", Callback.class.getName(), "callback", true, "POSTING", 0); BusUtils.registerBus4Test(TAG_IO, BusUtilsTest.class.getName(), "ioFun", CountDownLatch.class.getName(), "latch", false, "IO", 0); BusUtils.registerBus4Test(TAG_CPU, BusUtilsTest.class.getName(), "cpuFun", CountDownLatch.class.getName(), "latch", false, "CPU", 0); BusUtils.registerBus4Test(TAG_CACHED, BusUtilsTest.class.getName(), "cachedFun", CountDownLatch.class.getName(), "latch", false, "CACHED", 0); BusUtils.registerBus4Test(TAG_SINGLE, BusUtilsTest.class.getName(), "singleFun", CountDownLatch.class.getName(), "latch", false, "SINGLE", 0); } @BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true) public void noParamStickyFun() { // BusUtils.removeSticky(TAG_NO_PARAM_STICKY); System.out.println("noParamSticky"); } @Subscribe(sticky = true) public void eventBusFun(String param) { System.out.println(param); } @Subscribe(sticky = true) public void eventBusFun1(String param) { System.out.println("foo"); } @Test public void testEventBusSticky() { EventBus.getDefault().postSticky("test"); System.out.println("----"); BusUtilsTest test = new BusUtilsTest(); EventBus.getDefault().register(new BusUtilsTest()); EventBus.getDefault().register(new BusUtilsTest()); EventBus.getDefault().register(new BusUtilsTest()); System.out.println("----"); EventBus.getDefault().postSticky("test"); EventBus.getDefault().postSticky("test"); } @Test public void testSticky() { BusUtils.postSticky(TAG_NO_PARAM_STICKY); System.out.println("----"); BusUtilsTest test = new BusUtilsTest(); BusUtils.register(new BusUtilsTest()); BusUtils.register(new BusUtilsTest()); BusUtils.register(new BusUtilsTest()); System.out.println("----"); BusUtils.post(TAG_NO_PARAM_STICKY); // BusUtils.post(TAG_NO_PARAM_STICKY); } @Test public void testMultiThread() { final BusUtilsTest test = new BusUtilsTest(); // for (int i = 0; i < 100; i++) { // new Thread(new Runnable() { // @Override // public void run() { // BusUtils.register(test); // } // }).start(); // } // CountDownLatch countDownLatch = new CountDownLatch(1); // BusUtils.register(test); // for (int i = 0; i < 100; i++) { // new Thread(new Runnable() { // @Override // public void run() { // BusUtils.post(TAG_NO_PARAM); // } // }).start(); // } // try { // countDownLatch.await(1, TimeUnit.SECONDS); // } catch (InterruptedException e) { // e.printStackTrace(); // } // BusUtils.unregister(test); // for (int i = 0; i < 100; i++) { // new Thread(new Runnable() { // @Override // public void run() { // BusUtils.unregister(test); // } // }).start(); // } // for (int i = 0; i < 100; i++) { // final int finalI = i; // new Thread(new Runnable() { // @Override // public void run() { // BusUtils.register(test); // BusUtils.post(TAG_ONE_PARAM, "" + finalI); // BusUtils.unregister(test); // } // }).start(); // } } @Test public void registerAndUnregister() { BusUtilsTest test = new BusUtilsTest(); BusUtils.post(TAG_NO_PARAM); BusUtils.post(TAG_ONE_PARAM, "post to one param fun."); BusUtils.register(test); BusUtils.post(TAG_NO_PARAM); BusUtils.post(TAG_ONE_PARAM, "Post to one param fun."); BusUtils.unregister(test); BusUtils.post(TAG_NO_PARAM); BusUtils.post(TAG_ONE_PARAM, "Post to one param fun."); } @Test public void post() { BusUtilsTest test0 = new BusUtilsTest(); BusUtilsTest test1 = new BusUtilsTest(); BusUtils.register(test0); BusUtils.register(test1); BusUtils.post(TAG_NO_PARAM); BusUtils.post(TAG_ONE_PARAM, "post to one param fun."); BusUtils.unregister(test0); BusUtils.unregister(test1); } @Test public void postSticky() { System.out.println("-----not sticky bus postSticky will be failed.-----"); BusUtils.postSticky(TAG_NO_PARAM); BusUtils.postSticky(TAG_ONE_PARAM, "post to one param fun."); System.out.println("\n-----sticky bus postSticky will be successful.-----"); BusUtils.postSticky(TAG_NO_PARAM_STICKY); BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() { @Override public String call() { return "post to one param sticky fun."; } }); BusUtilsTest test = new BusUtilsTest(); System.out.println("\n-----register.-----"); BusUtils.register(test); System.out.println("\n-----sticky post.-----"); BusUtils.postSticky(TAG_NO_PARAM); BusUtils.postSticky(TAG_ONE_PARAM, "post to one param fun."); BusUtils.postSticky(TAG_NO_PARAM_STICKY); BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() { @Override public String call() { return "post to one param sticky fun."; } }); BusUtils.removeSticky(TAG_NO_PARAM_STICKY); BusUtils.removeSticky(TAG_ONE_PARAM_STICKY); BusUtils.unregister(test); } @Test public void removeSticky() { BusUtils.postSticky(TAG_NO_PARAM_STICKY); BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() { @Override public String call() { return "post to one param sticky fun."; } }); BusUtilsTest test = new BusUtilsTest(); System.out.println("-----register.-----"); BusUtils.register(test); BusUtils.unregister(test); System.out.println("\n-----register.-----"); BusUtils.register(test); System.out.println("\n-----remove sticky bus.-----"); BusUtils.removeSticky(TAG_NO_PARAM_STICKY); BusUtils.removeSticky(TAG_ONE_PARAM_STICKY); BusUtils.unregister(test); System.out.println("\n-----register.-----"); BusUtils.register(test); BusUtils.unregister(test); } @Test public void testThreadMode() throws InterruptedException { BusUtilsTest test = new BusUtilsTest(); CountDownLatch latch = new CountDownLatch(4); BusUtils.register(test); BusUtils.post(TAG_IO, latch); BusUtils.post(TAG_CPU, latch); BusUtils.post(TAG_CACHED, latch); BusUtils.post(TAG_SINGLE, latch); latch.await(); BusUtils.unregister(test); } @Test public void toString_() { System.out.println("BusUtils.toString_() = " + BusUtils.toString_()); } @Test public void testBase() { BusUtils.registerBus4Test("base", BaseTest.class.getName(), "noParamFun", "int", "i", false, "POSTING", 0); BaseTest t = new BusUtilsTest(); BusUtils.register(t); BusUtils.post("base", 1); BusUtils.unregister(t); } @Test public void testSameTag() { BusUtils.registerBus4Test(TAG_NO_PARAM, BusUtilsTest.class.getName(), "noParamSameTagFun", "", "", false, "POSTING", 2); BusUtilsTest test = new BusUtilsTest(); BusUtils.register(test); BusUtils.post(TAG_NO_PARAM); BusUtils.unregister(test); } public interface Callback { String call(); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
2,561
```java package com.blankj.utilcode.util; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONObject; import java.io.Serializable; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/01/04 * desc : utils about disk cache * </pre> */ public final class CacheDiskStaticUtils { private static CacheDiskUtils sDefaultCacheDiskUtils; /** * Set the default instance of {@link CacheDiskUtils}. * * @param cacheDiskUtils The default instance of {@link CacheDiskUtils}. */ public static void setDefaultCacheDiskUtils(@Nullable final CacheDiskUtils cacheDiskUtils) { sDefaultCacheDiskUtils = cacheDiskUtils; } /** * Put bytes in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final byte[] value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put bytes in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final byte[] value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the bytes in cache. * * @param key The key of cache. * @return the bytes if cache exists or null otherwise */ public static byte[] getBytes(@NonNull final String key) { return getBytes(key, getDefaultCacheDiskUtils()); } /** * Return the bytes in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the bytes if cache exists or defaultValue otherwise */ public static byte[] getBytes(@NonNull final String key, @Nullable final byte[] defaultValue) { return getBytes(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about String /////////////////////////////////////////////////////////////////////////// /** * Put string value in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final String value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put string value in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final String value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the string value in cache. * * @param key The key of cache. * @return the string value if cache exists or null otherwise */ public static String getString(@NonNull final String key) { return getString(key, getDefaultCacheDiskUtils()); } /** * Return the string value in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the string value if cache exists or defaultValue otherwise */ public static String getString(@NonNull final String key, @Nullable final String defaultValue) { return getString(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about JSONObject /////////////////////////////////////////////////////////////////////////// /** * Put JSONObject in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final JSONObject value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put JSONObject in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final JSONObject value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the JSONObject in cache. * * @param key The key of cache. * @return the JSONObject if cache exists or null otherwise */ public static JSONObject getJSONObject(@NonNull final String key) { return getJSONObject(key, getDefaultCacheDiskUtils()); } /** * Return the JSONObject in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the JSONObject if cache exists or defaultValue otherwise */ public static JSONObject getJSONObject(@NonNull final String key, @Nullable final JSONObject defaultValue) { return getJSONObject(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about JSONArray /////////////////////////////////////////////////////////////////////////// /** * Put JSONArray in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final JSONArray value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put JSONArray in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final JSONArray value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the JSONArray in cache. * * @param key The key of cache. * @return the JSONArray if cache exists or null otherwise */ public static JSONArray getJSONArray(@NonNull final String key) { return getJSONArray(key, getDefaultCacheDiskUtils()); } /** * Return the JSONArray in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the JSONArray if cache exists or defaultValue otherwise */ public static JSONArray getJSONArray(@NonNull final String key, @Nullable final JSONArray defaultValue) { return getJSONArray(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about Bitmap /////////////////////////////////////////////////////////////////////////// /** * Put bitmap in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final Bitmap value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put bitmap in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final Bitmap value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the bitmap in cache. * * @param key The key of cache. * @return the bitmap if cache exists or null otherwise */ public static Bitmap getBitmap(@NonNull final String key) { return getBitmap(key, getDefaultCacheDiskUtils()); } /** * Return the bitmap in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the bitmap if cache exists or defaultValue otherwise */ public static Bitmap getBitmap(@NonNull final String key, @Nullable final Bitmap defaultValue) { return getBitmap(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about Drawable /////////////////////////////////////////////////////////////////////////// /** * Put drawable in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final Drawable value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put drawable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final Drawable value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the drawable in cache. * * @param key The key of cache. * @return the drawable if cache exists or null otherwise */ public static Drawable getDrawable(@NonNull final String key) { return getDrawable(key, getDefaultCacheDiskUtils()); } /** * Return the drawable in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the drawable if cache exists or defaultValue otherwise */ public static Drawable getDrawable(@NonNull final String key, final @Nullable Drawable defaultValue) { return getDrawable(key, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about Parcelable /////////////////////////////////////////////////////////////////////////// /** * Put parcelable in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final Parcelable value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put parcelable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final Parcelable value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the parcelable in cache. * * @param key The key of cache. * @param creator The creator. * @param <T> The value type. * @return the parcelable if cache exists or null otherwise */ public static <T> T getParcelable(@NonNull final String key, @NonNull final Parcelable.Creator<T> creator) { return getParcelable(key, creator, getDefaultCacheDiskUtils()); } /** * Return the parcelable in cache. * * @param key The key of cache. * @param creator The creator. * @param defaultValue The default value if the cache doesn't exist. * @param <T> The value type. * @return the parcelable if cache exists or defaultValue otherwise */ public static <T> T getParcelable(@NonNull final String key, @NonNull final Parcelable.Creator<T> creator, @Nullable final T defaultValue) { return getParcelable(key, creator, defaultValue, getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // about Serializable /////////////////////////////////////////////////////////////////////////// /** * Put serializable in cache. * * @param key The key of cache. * @param value The value of cache. */ public static void put(@NonNull final String key, @Nullable final Serializable value) { put(key, value, getDefaultCacheDiskUtils()); } /** * Put serializable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. */ public static void put(@NonNull final String key, @Nullable final Serializable value, final int saveTime) { put(key, value, saveTime, getDefaultCacheDiskUtils()); } /** * Return the serializable in cache. * * @param key The key of cache. * @return the bitmap if cache exists or null otherwise */ public static Object getSerializable(@NonNull final String key) { return getSerializable(key, getDefaultCacheDiskUtils()); } /** * Return the serializable in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @return the bitmap if cache exists or defaultValue otherwise */ public static Object getSerializable(@NonNull final String key, @Nullable final Object defaultValue) { return getSerializable(key, defaultValue, getDefaultCacheDiskUtils()); } /** * Return the size of cache, in bytes. * * @return the size of cache, in bytes */ public static long getCacheSize() { return getCacheSize(getDefaultCacheDiskUtils()); } /** * Return the count of cache. * * @return the count of cache */ public static int getCacheCount() { return getCacheCount(getDefaultCacheDiskUtils()); } /** * Remove the cache by key. * * @param key The key of cache. * @return {@code true}: success<br>{@code false}: fail */ public static boolean remove(@NonNull final String key) { return remove(key, getDefaultCacheDiskUtils()); } /** * Clear all of the cache. * * @return {@code true}: success<br>{@code false}: fail */ public static boolean clear() { return clear(getDefaultCacheDiskUtils()); } /////////////////////////////////////////////////////////////////////////// // dividing line /////////////////////////////////////////////////////////////////////////// /** * Put bytes in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final byte[] value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put bytes in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final byte[] value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the bytes in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bytes if cache exists or null otherwise */ public static byte[] getBytes(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getBytes(key); } /** * Return the bytes in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bytes if cache exists or defaultValue otherwise */ public static byte[] getBytes(@NonNull final String key, @Nullable final byte[] defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getBytes(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about String /////////////////////////////////////////////////////////////////////////// /** * Put string value in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final String value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put string value in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final String value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the string value in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the string value if cache exists or null otherwise */ public static String getString(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getString(key); } /** * Return the string value in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the string value if cache exists or defaultValue otherwise */ public static String getString(@NonNull final String key, @Nullable final String defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getString(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about JSONObject /////////////////////////////////////////////////////////////////////////// /** * Put JSONObject in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final JSONObject value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put JSONObject in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final JSONObject value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the JSONObject in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the JSONObject if cache exists or null otherwise */ public static JSONObject getJSONObject(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getJSONObject(key); } /** * Return the JSONObject in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the JSONObject if cache exists or defaultValue otherwise */ public static JSONObject getJSONObject(@NonNull final String key, @Nullable final JSONObject defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getJSONObject(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about JSONArray /////////////////////////////////////////////////////////////////////////// /** * Put JSONArray in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final JSONArray value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put JSONArray in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final JSONArray value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the JSONArray in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the JSONArray if cache exists or null otherwise */ public static JSONArray getJSONArray(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getJSONArray(key); } /** * Return the JSONArray in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the JSONArray if cache exists or defaultValue otherwise */ public static JSONArray getJSONArray(@NonNull final String key, @Nullable final JSONArray defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getJSONArray(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about Bitmap /////////////////////////////////////////////////////////////////////////// /** * Put bitmap in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Bitmap value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put bitmap in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Bitmap value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the bitmap in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bitmap if cache exists or null otherwise */ public static Bitmap getBitmap(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getBitmap(key); } /** * Return the bitmap in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bitmap if cache exists or defaultValue otherwise */ public static Bitmap getBitmap(@NonNull final String key, @Nullable final Bitmap defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getBitmap(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about Drawable /////////////////////////////////////////////////////////////////////////// /** * Put drawable in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Drawable value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put drawable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Drawable value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the drawable in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the drawable if cache exists or null otherwise */ public static Drawable getDrawable(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getDrawable(key); } /** * Return the drawable in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the drawable if cache exists or defaultValue otherwise */ public static Drawable getDrawable(@NonNull final String key, @Nullable final Drawable defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getDrawable(key, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about Parcelable /////////////////////////////////////////////////////////////////////////// /** * Put parcelable in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Parcelable value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put parcelable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Parcelable value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the parcelable in cache. * * @param key The key of cache. * @param creator The creator. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @param <T> The value type. * @return the parcelable if cache exists or null otherwise */ public static <T> T getParcelable(@NonNull final String key, @NonNull final Parcelable.Creator<T> creator, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getParcelable(key, creator); } /** * Return the parcelable in cache. * * @param key The key of cache. * @param creator The creator. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @param <T> The value type. * @return the parcelable if cache exists or defaultValue otherwise */ public static <T> T getParcelable(@NonNull final String key, @NonNull final Parcelable.Creator<T> creator, @Nullable final T defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getParcelable(key, creator, defaultValue); } /////////////////////////////////////////////////////////////////////////// // about Serializable /////////////////////////////////////////////////////////////////////////// /** * Put serializable in cache. * * @param key The key of cache. * @param value The value of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Serializable value, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value); } /** * Put serializable in cache. * * @param key The key of cache. * @param value The value of cache. * @param saveTime The save time of cache, in seconds. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. */ public static void put(@NonNull final String key, @Nullable final Serializable value, final int saveTime, @NonNull final CacheDiskUtils cacheDiskUtils) { cacheDiskUtils.put(key, value, saveTime); } /** * Return the serializable in cache. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bitmap if cache exists or null otherwise */ public static Object getSerializable(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getSerializable(key); } /** * Return the serializable in cache. * * @param key The key of cache. * @param defaultValue The default value if the cache doesn't exist. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the bitmap if cache exists or defaultValue otherwise */ public static Object getSerializable(@NonNull final String key, @Nullable final Object defaultValue, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getSerializable(key, defaultValue); } /** * Return the size of cache, in bytes. * * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the size of cache, in bytes */ public static long getCacheSize(@NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getCacheSize(); } /** * Return the count of cache. * * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return the count of cache */ public static int getCacheCount(@NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.getCacheCount(); } /** * Remove the cache by key. * * @param key The key of cache. * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return {@code true}: success<br>{@code false}: fail */ public static boolean remove(@NonNull final String key, @NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.remove(key); } /** * Clear all of the cache. * * @param cacheDiskUtils The instance of {@link CacheDiskUtils}. * @return {@code true}: success<br>{@code false}: fail */ public static boolean clear(@NonNull final CacheDiskUtils cacheDiskUtils) { return cacheDiskUtils.clear(); } @NonNull private static CacheDiskUtils getDefaultCacheDiskUtils() { return sDefaultCacheDiskUtils != null ? sDefaultCacheDiskUtils : CacheDiskUtils.getInstance(); } } ```
/content/code_sandbox/lib/utilcode/src/main/java/com/blankj/utilcode/util/CacheDiskStaticUtils.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
6,797
```java package com.blankj.utilcode.util; import com.blankj.utilcode.constant.MemoryConstants; import com.blankj.utilcode.constant.TimeConstants; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/13 * desc : test ConvertUtils * </pre> */ public class ConvertUtilsTest extends BaseTest { private byte[] mBytes = new byte[]{0x00, 0x08, (byte) 0xdb, 0x33, 0x45, (byte) 0xab, 0x02, 0x23}; private String hexString = "0008DB3345AB0223"; private char[] mChars1 = new char[]{'0', '1', '2'}; private byte[] mBytes1 = new byte[]{48, 49, 50}; @Test public void bytes2HexString() { assertEquals( hexString, ConvertUtils.bytes2HexString(mBytes) ); } @Test public void hexString2Bytes() { assertTrue( Arrays.equals( mBytes, ConvertUtils.hexString2Bytes(hexString) ) ); } @Test public void chars2Bytes() { assertTrue( Arrays.equals( mBytes1, ConvertUtils.chars2Bytes(mChars1) ) ); } @Test public void bytes2Chars() { assertTrue( Arrays.equals( mChars1, ConvertUtils.bytes2Chars(mBytes1) ) ); } @Test public void byte2MemorySize() { assertEquals( 1024, ConvertUtils.byte2MemorySize(MemoryConstants.GB, MemoryConstants.MB), 0.001 ); } @Test public void byte2FitMemorySize() { assertEquals( "3.098MB", ConvertUtils.byte2FitMemorySize(1024 * 1024 * 3 + 1024 * 100) ); } @Test public void millis2FitTimeSpan() { long millis = 6 * TimeConstants.DAY + 6 * TimeConstants.HOUR + 6 * TimeConstants.MIN + 6 * TimeConstants.SEC + 6; assertEquals( "66666", ConvertUtils.millis2FitTimeSpan(millis, 7) ); assertEquals( "6666", ConvertUtils.millis2FitTimeSpan(millis, 4) ); assertEquals( "666", ConvertUtils.millis2FitTimeSpan(millis, 3) ); assertEquals( "25242424", ConvertUtils.millis2FitTimeSpan(millis * 4, 5) ); } @Test public void bytes2Bits_bits2Bytes() { assertEquals( "0111111111111010", ConvertUtils.bytes2Bits(new byte[]{0x7F, (byte) 0xFA}) ); assertEquals( "0111111111111010", ConvertUtils.bytes2Bits(ConvertUtils.bits2Bytes("111111111111010")) ); } @Test public void inputStream2Bytes_bytes2InputStream() throws Exception { String string = "this is test string"; assertTrue( Arrays.equals( string.getBytes("UTF-8"), ConvertUtils.inputStream2Bytes(ConvertUtils.bytes2InputStream(string.getBytes("UTF-8"))) ) ); } @Test public void inputStream2String_string2InputStream() { String string = "this is test string"; assertEquals( string, ConvertUtils.inputStream2String(ConvertUtils.string2InputStream(string, "UTF-8"), "UTF-8") ); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ConvertUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
848
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/25 * desc : test ImageUtils * </pre> */ public class ImageUtilsTest extends BaseTest { @Test public void getImageType() { Assert.assertEquals(ImageUtils.ImageType.TYPE_JPG, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.jpg")); Assert.assertEquals(ImageUtils.ImageType.TYPE_PNG, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.png")); Assert.assertEquals(ImageUtils.ImageType.TYPE_GIF, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.gif")); Assert.assertEquals(ImageUtils.ImageType.TYPE_TIFF, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.tif")); Assert.assertEquals(ImageUtils.ImageType.TYPE_BMP, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.bmp")); Assert.assertEquals(ImageUtils.ImageType.TYPE_WEBP, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.webp")); Assert.assertEquals(ImageUtils.ImageType.TYPE_ICO, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.ico")); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ImageUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
273
```java package com.blankj.utilcode.util; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.Serializable; import static com.blankj.utilcode.util.TestConfig.FILE_SEP; import static com.blankj.utilcode.util.TestConfig.PATH_CACHE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/01/04 * desc : test CacheDiskStaticUtils * </pre> */ public class CacheDiskStaticUtilsTest extends BaseTest { private static final String DISK1_PATH = PATH_CACHE + "disk1" + FILE_SEP; private static final String DISK2_PATH = PATH_CACHE + "disk2" + FILE_SEP; private static final File DISK1_FILE = new File(DISK1_PATH); private static final File DISK2_FILE = new File(DISK2_PATH); private static final CacheDiskUtils CACHE_DISK_UTILS1 = CacheDiskUtils.getInstance(DISK1_FILE); private static final CacheDiskUtils CACHE_DISK_UTILS2 = CacheDiskUtils.getInstance(DISK2_FILE); private static final byte[] BYTES = "CacheDiskUtils".getBytes(); private static final String STRING = "CacheDiskUtils"; private static final JSONObject JSON_OBJECT = new JSONObject(); private static final JSONArray JSON_ARRAY = new JSONArray(); private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDiskUtils"); private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDiskUtils"); private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP); static { try { JSON_OBJECT.put("class", "CacheDiskUtils"); JSON_OBJECT.put("author", "Blankj"); JSON_ARRAY.put(0, JSON_OBJECT); } catch (JSONException e) { e.printStackTrace(); } } @Before public void setUp() { CacheDiskStaticUtils.put("bytes1", BYTES, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("string1", STRING, 60 * CacheDiskUtils.MIN, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("jsonObject1", JSON_OBJECT, 24 * CacheDiskUtils.HOUR, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("jsonArray1", JSON_ARRAY, 365 * CacheDiskUtils.DAY, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("bitmap1", BITMAP, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("drawable1", DRAWABLE, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("parcelable1", PARCELABLE_TEST, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("serializable1", SERIALIZABLE_TEST, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1); CacheDiskStaticUtils.put("bytes2", BYTES, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("string2", STRING, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("jsonObject2", JSON_OBJECT, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("jsonArray2", JSON_ARRAY, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("bitmap2", BITMAP, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("drawable2", DRAWABLE, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("parcelable2", PARCELABLE_TEST, CACHE_DISK_UTILS2); CacheDiskStaticUtils.put("serializable2", SERIALIZABLE_TEST, CACHE_DISK_UTILS2); } @Test public void getBytes() { assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1))); assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes1", null, CACHE_DISK_UTILS1))); assertNull(CacheDiskStaticUtils.getBytes("bytes2", null, CACHE_DISK_UTILS1)); assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2))); assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes2", null, CACHE_DISK_UTILS2))); assertNull(CacheDiskStaticUtils.getBytes("bytes1", null, CACHE_DISK_UTILS2)); } @Test public void getString() { assertEquals(STRING, CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1)); assertEquals(STRING, CacheDiskStaticUtils.getString("string1", null, CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getString("string2", null, CACHE_DISK_UTILS1)); assertEquals(STRING, CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2)); assertEquals(STRING, CacheDiskStaticUtils.getString("string2", null, CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getString("string1", null, CACHE_DISK_UTILS2)); } @Test public void getJSONObject() { assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1).toString()); assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject1", null, CACHE_DISK_UTILS1).toString()); assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", null, CACHE_DISK_UTILS1)); assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2).toString()); assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject2", null, CACHE_DISK_UTILS2).toString()); assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", null, CACHE_DISK_UTILS2)); } @Test public void getJSONArray() { assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1).toString()); assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray1", null, CACHE_DISK_UTILS1).toString()); assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", null, CACHE_DISK_UTILS1)); assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2).toString()); assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray2", null, CACHE_DISK_UTILS2).toString()); assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", null, CACHE_DISK_UTILS2)); } @Test public void getBitmap() { assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap1", null, CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100) ); assertNull(CacheDiskStaticUtils.getBitmap("bitmap2", null, CACHE_DISK_UTILS1)); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap2", null, CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100) ); assertNull(CacheDiskStaticUtils.getBitmap("bitmap1", null, CACHE_DISK_UTILS2)); } @Test public void getDrawable() { assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable1", null, CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100) ); assertNull(CacheDiskStaticUtils.getDrawable("drawable2", null, CACHE_DISK_UTILS1)); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable2", null, CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100) ); assertNull(CacheDiskStaticUtils.getDrawable("drawable1", null, CACHE_DISK_UTILS2)); } @Test public void getParcel() { assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1)); assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS1)); assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2)); assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS2)); } @Test public void getSerializable() { assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1)); assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable1", null, CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getSerializable("parcelable2", null, CACHE_DISK_UTILS1)); assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2)); assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable2", null, CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getSerializable("parcelable1", null, CACHE_DISK_UTILS2)); } @Test public void getCacheSize() { assertEquals(FileUtils.getLength(DISK1_FILE), CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS1)); assertEquals(FileUtils.getLength(DISK2_FILE), CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS2)); } @Test public void getCacheCount() { assertEquals(8, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS1)); assertEquals(8, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS2)); } @Test public void remove() { assertNotNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1)); CacheDiskStaticUtils.remove("string1", CACHE_DISK_UTILS1); assertNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2)); CacheDiskStaticUtils.remove("string2", CACHE_DISK_UTILS2); assertNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2)); } @Test public void clear() { assertNotNull(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1)); CacheDiskStaticUtils.clear(CACHE_DISK_UTILS1); assertNull(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1)); assertNull(CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1)); assertEquals(0, CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS1)); assertEquals(0, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS1)); assertNotNull(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2)); assertNotNull(CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2)); CacheDiskStaticUtils.clear(CACHE_DISK_UTILS2); assertNull(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2)); assertNull(CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2)); assertEquals(0, CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS2)); assertEquals(0, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS2)); } @After public void tearDown() { CacheDiskStaticUtils.clear(CACHE_DISK_UTILS1); CacheDiskStaticUtils.clear(CACHE_DISK_UTILS2); } static class ParcelableTest implements Parcelable { String author; String className; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } ParcelableTest(String author, String className) { this.author = author; this.className = className; } ParcelableTest(Parcel in) { author = in.readString(); className = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(author); dest.writeString(className); } @Override public int describeContents() { return 0; } public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() { @Override public ParcelableTest createFromParcel(Parcel in) { return new ParcelableTest(in); } @Override public ParcelableTest[] newArray(int size) { return new ParcelableTest[size]; } }; @Override public boolean equals(Object obj) { return obj instanceof ParcelableTest && ((ParcelableTest) obj).author.equals(author) && ((ParcelableTest) obj).className.equals(className); } } static class SerializableTest implements Serializable { private static final long serialVersionUID = -5806706668736895024L; String author; String className; SerializableTest(String author, String className) { this.author = author; this.className = className; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public boolean equals(Object obj) { return obj instanceof SerializableTest && ((SerializableTest) obj).author.equals(author) && ((SerializableTest) obj).className.equals(className); } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskStaticUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,802
```java package com.blankj.utilcode.util; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import java.util.concurrent.Executor; import androidx.annotation.NonNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/08/03 * desc : * </pre> */ @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowLog.class}) public class BaseTest { @BusUtils.Bus(tag = "base") public void noParamFun(int i) { System.out.println("base" + i); } public BaseTest() { ShadowLog.stream = System.out; ThreadUtils.setDeliver(new Executor() { @Override public void execute(@NonNull Runnable command) { command.run(); } }); Utils.init(RuntimeEnvironment.application); } @Test public void test() throws Exception { } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/BaseTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
243
```java package com.blankj.utilcode.util; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/05/21 * desc : * </pre> */ public class ThreadUtilsTest extends BaseTest { @Test public void executeByFixed() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { new ThreadGroup("name"); Thread.sleep(500 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByFixed(3, task); } }); } @Test public void executeByFixedWithDelay() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByFixedWithDelay(3, task, 500 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeByFixedAtFixRate() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) { @Override public String doInBackground() throws Throwable { Thread.sleep(500 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByFixedAtFixRate(3, task, 3000 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeBySingle() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(200); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeBySingle(task); } }); } @Test public void executeBySingleWithDelay() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeBySingleWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeBySingleAtFixRate() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) { @Override public String doInBackground() throws Throwable { Thread.sleep(100 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeBySingleAtFixRate(task, 2000 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeByIo() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByIo(task); } }); } @Test public void executeByIoWithDelay() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByIoWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeByIoAtFixRate() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) { @Override public String doInBackground() throws Throwable { Thread.sleep(100 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByIoAtFixRate(task, 1000, TimeUnit.MILLISECONDS); } }); } @Test public void executeByCpu() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByCpu(task); } }); } @Test public void executeByCpuWithDelay() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestTask<String> task = new TestTask<String>(latch) { @Override public String doInBackground() throws Throwable { Thread.sleep(500); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByCpuWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS); } }); } @Test public void executeByCpuAtFixRate() throws Exception { asyncTest(10, new TestRunnable<String>() { @Override public void run(final int index, CountDownLatch latch) { final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) { @Override public String doInBackground() throws Throwable { Thread.sleep(100 + index * 10); if (index < 4) { return Thread.currentThread() + " :" + index; } else if (index < 7) { cancel(); return null; } else { throw new NullPointerException(String.valueOf(index)); } } @Override void onTestSuccess(String result) { System.out.println(result); } }; ThreadUtils.executeByCpuAtFixRate(task, 1000, TimeUnit.MILLISECONDS); } }); } @Test public void cancelPoolTask() throws InterruptedException { int count = 300; final CountDownLatch countDownLatch = new CountDownLatch(count); for (int i = 0; i < count; i++) { final int finalI = i; ThreadUtils.executeByCached(new ThreadUtils.Task<Integer>() { @Override public Integer doInBackground() throws Throwable { Thread.sleep(10 * finalI); return finalI; } @Override public void onSuccess(Integer result) { System.out.println(result); if (result == 10) { ThreadUtils.cancel(ThreadUtils.getCachedPool()); } countDownLatch.countDown(); } @Override public void onCancel() { System.out.println("onCancel: " + finalI); countDownLatch.countDown(); } @Override public void onFail(Throwable t) { countDownLatch.countDown(); } }); } countDownLatch.await(); } @Test public void testTimeout() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); ThreadUtils.Task<Boolean> task = new ThreadUtils.SimpleTask<Boolean>() { @Override public Boolean doInBackground() throws Throwable { System.out.println("doInBackground start"); Thread.sleep(2000); System.out.println("doInBackground end"); return null; } @Override public void onSuccess(Boolean result) { System.out.println("onSuccess"); } }.setTimeout(1000, new ThreadUtils.Task.OnTimeoutListener() { @Override public void onTimeout() { System.out.println("onTimeout"); } }); ThreadUtils.executeByCached(task); latch.await(3, TimeUnit.SECONDS); } abstract static class TestScheduledTask<T> extends ThreadUtils.Task<T> { private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(); private int mTimes; CountDownLatch mLatch; TestScheduledTask(final CountDownLatch latch, final int times) { mLatch = latch; mTimes = times; } abstract void onTestSuccess(T result); @Override public void onSuccess(T result) { onTestSuccess(result); if (ATOMIC_INTEGER.addAndGet(1) % mTimes == 0) { mLatch.countDown(); } } @Override public void onCancel() { System.out.println(Thread.currentThread() + " onCancel: "); mLatch.countDown(); } @Override public void onFail(Throwable t) { System.out.println(Thread.currentThread() + " onFail: " + t); mLatch.countDown(); } } abstract static class TestTask<T> extends ThreadUtils.Task<T> { CountDownLatch mLatch; TestTask(final CountDownLatch latch) { mLatch = latch; } abstract void onTestSuccess(T result); @Override public void onSuccess(T result) { onTestSuccess(result); mLatch.countDown(); } @Override public void onCancel() { System.out.println(Thread.currentThread() + " onCancel: "); mLatch.countDown(); } @Override public void onFail(Throwable t) { System.out.println(Thread.currentThread() + " onFail: " + t); mLatch.countDown(); } } private <T> void asyncTest(int threadCount, TestRunnable<T> runnable) throws Exception { CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { runnable.run(i, latch); } latch.await(); } interface TestRunnable<T> { void run(final int index, CountDownLatch latch); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ThreadUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,108
```java package com.blankj.utilcode.util; import org.junit.Before; import org.junit.Test; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/07/11 * desc : * </pre> */ public class ApiUtilsTest extends BaseTest { @Before public void setUp() throws Exception { ApiUtils.register(TestApiImpl.class); } @Test public void getApi() { System.out.println("ApiUtils.getApi(TestApi.class).test(\"hehe\") = " + ApiUtils.getApi(TestApi.class).test("hehe")); } @Test public void toString_() { System.out.println("ApiUtils.toString_() = " + ApiUtils.toString_()); } @ApiUtils.Api public static class TestApiImpl extends TestApi { @Override public String test(String param) { System.out.println("param = " + param); return "haha"; } } public static abstract class TestApi extends ApiUtils.BaseApi { public abstract String test(String name); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ApiUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
247
```java package com.blankj.utilcode.util; import com.blankj.utilcode.constant.TimeConstants; import org.junit.Test; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/12 * desc : test TimeUtils * </pre> */ public class TimeUtilsTest extends BaseTest { private final DateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); private final DateFormat mFormat = new SimpleDateFormat("yyyy MM dd HH:mm:ss", Locale.getDefault()); private final long timeMillis = 1493887049000L;// 2017-05-04 16:37:29 private final Date timeDate = new Date(timeMillis); private final String timeString = defaultFormat.format(timeDate); private final String timeStringFormat = mFormat.format(timeDate); private final long tomorrowTimeMillis = 1493973449000L; private final Date tomorrowTimeDate = new Date(tomorrowTimeMillis); private final String tomorrowTimeString = defaultFormat.format(tomorrowTimeDate); private final String tomorrowTimeStringFormat = mFormat.format(tomorrowTimeDate); private final long delta = 20;// 10ms @Test public void millis2String() { assertEquals(timeString, TimeUtils.millis2String(timeMillis)); assertEquals(timeStringFormat, TimeUtils.millis2String(timeMillis, mFormat)); assertEquals(timeStringFormat, TimeUtils.millis2String(timeMillis, "yyyy MM dd HH:mm:ss")); } @Test public void string2Millis() { assertEquals(timeMillis, TimeUtils.string2Millis(timeString)); assertEquals(timeMillis, TimeUtils.string2Millis(timeStringFormat, mFormat)); assertEquals(timeMillis, TimeUtils.string2Millis(timeStringFormat, "yyyy MM dd HH:mm:ss")); } @Test public void string2Date() { assertEquals(timeDate, TimeUtils.string2Date(timeString)); assertEquals(timeDate, TimeUtils.string2Date(timeStringFormat, mFormat)); assertEquals(timeDate, TimeUtils.string2Date(timeStringFormat, "yyyy MM dd HH:mm:ss")); } @Test public void date2String() { assertEquals(timeString, TimeUtils.date2String(timeDate)); assertEquals(timeStringFormat, TimeUtils.date2String(timeDate, mFormat)); assertEquals(timeStringFormat, TimeUtils.date2String(timeDate, "yyyy MM dd HH:mm:ss")); } @Test public void date2Millis() { assertEquals(timeMillis, TimeUtils.date2Millis(timeDate)); } @Test public void millis2Date() { assertEquals(timeDate, TimeUtils.millis2Date(timeMillis)); } @Test public void getTimeSpan() { long testTimeMillis = timeMillis + 120 * TimeConstants.SEC; String testTimeString = TimeUtils.millis2String(testTimeMillis); String testTimeStringFormat = TimeUtils.millis2String(testTimeMillis, mFormat); Date testTimeDate = TimeUtils.millis2Date(testTimeMillis); assertEquals(-120, TimeUtils.getTimeSpan(timeString, testTimeString, TimeConstants.SEC)); assertEquals(2, TimeUtils.getTimeSpan(testTimeStringFormat, timeStringFormat, mFormat, TimeConstants.MIN)); assertEquals(-2, TimeUtils.getTimeSpan(timeDate, testTimeDate, TimeConstants.MIN)); assertEquals(120, TimeUtils.getTimeSpan(testTimeMillis, timeMillis, TimeConstants.SEC)); } @Test public void getFitTimeSpan() { long testTimeMillis = timeMillis + 10 * TimeConstants.DAY + 10 * TimeConstants.MIN + 10 * TimeConstants.SEC; String testTimeString = TimeUtils.millis2String(testTimeMillis); String testTimeStringFormat = TimeUtils.millis2String(testTimeMillis, mFormat); Date testTimeDate = TimeUtils.millis2Date(testTimeMillis); assertEquals("-101010", TimeUtils.getFitTimeSpan(timeString, testTimeString, 5)); assertEquals("101010", TimeUtils.getFitTimeSpan(testTimeStringFormat, timeStringFormat, mFormat, 5)); assertEquals("-101010", TimeUtils.getFitTimeSpan(timeDate, testTimeDate, 5)); assertEquals("101010", TimeUtils.getFitTimeSpan(testTimeMillis, timeMillis, 5)); } @Test public void getNowMills() { assertEquals(System.currentTimeMillis(), TimeUtils.getNowMills(), delta); } @Test public void getNowString() { assertEquals(System.currentTimeMillis(), TimeUtils.string2Millis(TimeUtils.getNowString()), delta); assertEquals(System.currentTimeMillis(), TimeUtils.string2Millis(TimeUtils.getNowString(mFormat), mFormat), delta); } @Test public void getNowDate() { assertEquals(System.currentTimeMillis(), TimeUtils.date2Millis(TimeUtils.getNowDate()), delta); } @Test public void getTimeSpanByNow() { assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(), TimeConstants.MSEC), delta); assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(mFormat), mFormat, TimeConstants.MSEC), delta); assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowDate(), TimeConstants.MSEC), delta); assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowMills(), TimeConstants.MSEC), delta); } @Test public void getFitTimeSpanByNow() { // long spanMillis = 6 * TimeConstants.DAY + 6 * TimeConstants.HOUR + 6 * TimeConstants.MIN + 6 * TimeConstants.SEC; // assertEquals("6666", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2String(System.currentTimeMillis() + spanMillis), 4)); // assertEquals("6666", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2String(System.currentTimeMillis() + spanMillis, mFormat), mFormat, 4)); // assertEquals("6666", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2Date(System.currentTimeMillis() + spanMillis), 4)); // assertEquals("6666", TimeUtils.getFitTimeSpanByNow(System.currentTimeMillis() + spanMillis, 4)); } @Test public void getFriendlyTimeSpanByNow() { assertEquals("", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowString())); assertEquals("", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowString(mFormat), mFormat)); assertEquals("", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowDate())); assertEquals("", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills())); assertEquals("1", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills() - TimeConstants.SEC)); assertEquals("1", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills() - TimeConstants.MIN)); } @Test public void getMillis() { assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeMillis, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeString, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeStringFormat, mFormat, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeDate, 1, TimeConstants.DAY)); } @Test public void getString() { assertEquals(tomorrowTimeString, TimeUtils.getString(timeMillis, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeMillis, mFormat, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeString, TimeUtils.getString(timeString, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeStringFormat, mFormat, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeString, TimeUtils.getString(timeDate, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeDate, mFormat, 1, TimeConstants.DAY)); } @Test public void getDate() { assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeMillis, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeString, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeStringFormat, mFormat, 1, TimeConstants.DAY)); assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeDate, 1, TimeConstants.DAY)); } @Test public void getMillisByNow() { assertEquals(System.currentTimeMillis() + TimeConstants.DAY, TimeUtils.getMillisByNow(1, TimeConstants.DAY), delta); } @Test public void getStringByNow() { long tomorrowMillis = TimeUtils.string2Millis(TimeUtils.getStringByNow(1, TimeConstants.DAY)); assertEquals(System.currentTimeMillis() + TimeConstants.DAY, tomorrowMillis, delta); tomorrowMillis = TimeUtils.string2Millis(TimeUtils.getStringByNow(1, mFormat, TimeConstants.DAY), mFormat); assertEquals(System.currentTimeMillis() + TimeConstants.DAY, tomorrowMillis, delta); } @Test public void getDateByNow() { long tomorrowMillis = TimeUtils.date2Millis(TimeUtils.getDateByNow(1, TimeConstants.DAY)); assertEquals(System.currentTimeMillis() + TimeConstants.DAY, TimeUtils.getMillisByNow(1, TimeConstants.DAY), delta); } @Test public void isToday() { long todayTimeMillis = System.currentTimeMillis(); String todayTimeString = TimeUtils.millis2String(todayTimeMillis); String todayTimeStringFormat = TimeUtils.millis2String(todayTimeMillis, mFormat); Date todayTimeDate = TimeUtils.millis2Date(todayTimeMillis); long tomorrowTimeMillis = todayTimeMillis + TimeConstants.DAY; String tomorrowTimeString = TimeUtils.millis2String(tomorrowTimeMillis); Date tomorrowTimeDate = TimeUtils.millis2Date(tomorrowTimeMillis); assertTrue(TimeUtils.isToday(todayTimeString)); assertTrue(TimeUtils.isToday(todayTimeStringFormat, mFormat)); assertTrue(TimeUtils.isToday(todayTimeDate)); assertTrue(TimeUtils.isToday(todayTimeMillis)); assertFalse(TimeUtils.isToday(tomorrowTimeString)); assertFalse(TimeUtils.isToday(tomorrowTimeStringFormat, mFormat)); assertFalse(TimeUtils.isToday(tomorrowTimeDate)); assertFalse(TimeUtils.isToday(tomorrowTimeMillis)); } @Test public void isLeapYear() { assertFalse(TimeUtils.isLeapYear(timeString)); assertFalse(TimeUtils.isLeapYear(timeStringFormat, mFormat)); assertFalse(TimeUtils.isLeapYear(timeDate)); assertFalse(TimeUtils.isLeapYear(timeMillis)); assertTrue(TimeUtils.isLeapYear(2016)); assertFalse(TimeUtils.isLeapYear(2017)); } @Test public void getChineseWeek() { assertEquals("", TimeUtils.getChineseWeek(timeString)); assertEquals("", TimeUtils.getChineseWeek(timeStringFormat, mFormat)); assertEquals("", TimeUtils.getChineseWeek(timeDate)); assertEquals("", TimeUtils.getChineseWeek(timeMillis)); } @Test public void getUSWeek() { assertEquals("Thursday", TimeUtils.getUSWeek(timeString)); assertEquals("Thursday", TimeUtils.getUSWeek(timeStringFormat, mFormat)); assertEquals("Thursday", TimeUtils.getUSWeek(timeDate)); assertEquals("Thursday", TimeUtils.getUSWeek(timeMillis)); } //@Test //public void isAm() { // assertFalse(TimeUtils.isAm(timeMillis)); //} // //@Test //public void isPm() { // assertTrue(TimeUtils.isPm(timeMillis)); //} @Test public void getWeekIndex() { assertEquals(5, TimeUtils.getValueByCalendarField(timeString, Calendar.DAY_OF_WEEK)); assertEquals(5, TimeUtils.getValueByCalendarField(timeString, Calendar.DAY_OF_WEEK)); assertEquals(5, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.DAY_OF_WEEK)); assertEquals(5, TimeUtils.getValueByCalendarField(timeDate, Calendar.DAY_OF_WEEK)); assertEquals(5, TimeUtils.getValueByCalendarField(timeMillis, Calendar.DAY_OF_WEEK)); } @Test public void getWeekOfMonth() { assertEquals(1, TimeUtils.getValueByCalendarField(timeString, Calendar.WEEK_OF_MONTH)); assertEquals(1, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.WEEK_OF_MONTH)); assertEquals(1, TimeUtils.getValueByCalendarField(timeDate, Calendar.WEEK_OF_MONTH)); assertEquals(1, TimeUtils.getValueByCalendarField(timeMillis, Calendar.WEEK_OF_MONTH)); } @Test public void getWeekOfYear() { assertEquals(18, TimeUtils.getValueByCalendarField(timeString, Calendar.WEEK_OF_YEAR)); assertEquals(18, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.WEEK_OF_YEAR)); assertEquals(18, TimeUtils.getValueByCalendarField(timeDate, Calendar.WEEK_OF_YEAR)); assertEquals(18, TimeUtils.getValueByCalendarField(timeMillis, Calendar.WEEK_OF_YEAR)); } @Test public void getChineseZodiac() { assertEquals("", TimeUtils.getChineseZodiac(timeString)); assertEquals("", TimeUtils.getChineseZodiac(timeStringFormat, mFormat)); assertEquals("", TimeUtils.getChineseZodiac(timeDate)); assertEquals("", TimeUtils.getChineseZodiac(timeMillis)); assertEquals("", TimeUtils.getChineseZodiac(2017)); } @Test public void getZodiac() { assertEquals("", TimeUtils.getZodiac(timeString)); assertEquals("", TimeUtils.getZodiac(timeStringFormat, mFormat)); assertEquals("", TimeUtils.getZodiac(timeDate)); assertEquals("", TimeUtils.getZodiac(timeMillis)); assertEquals("", TimeUtils.getZodiac(8, 16)); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/TimeUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,037
```java package com.blankj.utilcode.util; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/16 * desc : test StringUtils * </pre> */ public class StringUtilsTest extends BaseTest { @Test public void isEmpty() { assertTrue(StringUtils.isEmpty("")); assertTrue(StringUtils.isEmpty(null)); assertFalse(StringUtils.isEmpty(" ")); } @Test public void isTrimEmpty() { assertTrue(StringUtils.isTrimEmpty("")); assertTrue(StringUtils.isTrimEmpty(null)); assertTrue(StringUtils.isTrimEmpty(" ")); } @Test public void isSpace() { assertTrue(StringUtils.isSpace("")); assertTrue(StringUtils.isSpace(null)); assertTrue(StringUtils.isSpace(" ")); assertTrue(StringUtils.isSpace(" \n\t\r")); } @Test public void equals() { assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals("blankj", "blankj")); assertFalse(StringUtils.equals("blankj", "Blankj")); } @Test public void equalsIgnoreCase() { assertTrue(StringUtils.equalsIgnoreCase(null, null)); assertFalse(StringUtils.equalsIgnoreCase(null, "blankj")); assertTrue(StringUtils.equalsIgnoreCase("blankj", "Blankj")); assertTrue(StringUtils.equalsIgnoreCase("blankj", "blankj")); assertFalse(StringUtils.equalsIgnoreCase("blankj", "blank")); } @Test public void null2Length0() { assertEquals("", StringUtils.null2Length0(null)); } @Test public void length() { assertEquals(0, StringUtils.length(null)); assertEquals(0, StringUtils.length("")); assertEquals(6, StringUtils.length("blankj")); } @Test public void upperFirstLetter() { assertEquals("Blankj", StringUtils.upperFirstLetter("blankj")); assertEquals("Blankj", StringUtils.upperFirstLetter("Blankj")); assertEquals("1Blankj", StringUtils.upperFirstLetter("1Blankj")); } @Test public void lowerFirstLetter() { assertEquals("blankj", StringUtils.lowerFirstLetter("blankj")); assertEquals("blankj", StringUtils.lowerFirstLetter("Blankj")); assertEquals("1blankj", StringUtils.lowerFirstLetter("1blankj")); } @Test public void reverse() { assertEquals("jknalb", StringUtils.reverse("blankj")); assertEquals("knalb", StringUtils.reverse("blank")); assertEquals("", StringUtils.reverse("")); assertEquals("", StringUtils.reverse(null)); } @Test public void toDBC() { assertEquals(" ,.&", StringUtils.toDBC("")); } @Test public void toSBC() { assertEquals("", StringUtils.toSBC(" ,.&")); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/StringUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
591
```java package com.blankj.utilcode.util; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.Serializable; import static com.blankj.utilcode.util.TestConfig.FILE_SEP; import static com.blankj.utilcode.util.TestConfig.PATH_CACHE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/06/13 * desc : test CacheDoubleUtils * </pre> */ public class CacheDoubleUtilsTest extends BaseTest { private static final String CACHE_PATH = PATH_CACHE + "double" + FILE_SEP; private static final File CACHE_FILE = new File(CACHE_PATH); private static final byte[] BYTES = "CacheDoubleUtils".getBytes(); private static final String STRING = "CacheDoubleUtils"; private static final JSONObject JSON_OBJECT = new JSONObject(); private static final JSONArray JSON_ARRAY = new JSONArray(); private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDoubleUtils"); private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDoubleUtils"); private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP); private static final CacheMemoryUtils CACHE_MEMORY_UTILS = CacheMemoryUtils.getInstance(); private static final CacheDiskUtils CACHE_DISK_UTILS = CacheDiskUtils.getInstance(CACHE_FILE); private static final CacheDoubleUtils CACHE_DOUBLE_UTILS = CacheDoubleUtils.getInstance(CACHE_MEMORY_UTILS, CACHE_DISK_UTILS); static { try { JSON_OBJECT.put("class", "CacheDiskUtils"); JSON_OBJECT.put("author", "Blankj"); JSON_ARRAY.put(0, JSON_OBJECT); } catch (JSONException e) { e.printStackTrace(); } } @Before public void setUp() { CACHE_DOUBLE_UTILS.put("bytes", BYTES); CACHE_DOUBLE_UTILS.put("string", STRING); CACHE_DOUBLE_UTILS.put("jsonObject", JSON_OBJECT); CACHE_DOUBLE_UTILS.put("jsonArray", JSON_ARRAY); CACHE_DOUBLE_UTILS.put("bitmap", BITMAP); CACHE_DOUBLE_UTILS.put("drawable", DRAWABLE); CACHE_DOUBLE_UTILS.put("parcelable", PARCELABLE_TEST); CACHE_DOUBLE_UTILS.put("serializable", SERIALIZABLE_TEST); } @Test public void getBytes() { assertEquals(STRING, new String(CACHE_DOUBLE_UTILS.getBytes("bytes"))); CACHE_MEMORY_UTILS.remove("bytes"); assertEquals(STRING, new String(CACHE_DOUBLE_UTILS.getBytes("bytes"))); CACHE_DISK_UTILS.remove("bytes"); assertNull(CACHE_DOUBLE_UTILS.getBytes("bytes")); } @Test public void getString() { assertEquals(STRING, CACHE_DOUBLE_UTILS.getString("string")); CACHE_MEMORY_UTILS.remove("string"); assertEquals(STRING, CACHE_DOUBLE_UTILS.getString("string")); CACHE_DISK_UTILS.remove("string"); assertNull(CACHE_DOUBLE_UTILS.getString("string")); } @Test public void getJSONObject() { assertEquals(JSON_OBJECT.toString(), CACHE_DOUBLE_UTILS.getJSONObject("jsonObject").toString()); CACHE_MEMORY_UTILS.remove("jsonObject"); assertEquals(JSON_OBJECT.toString(), CACHE_DOUBLE_UTILS.getJSONObject("jsonObject").toString()); CACHE_DISK_UTILS.remove("jsonObject"); assertNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject")); } @Test public void getJSONArray() { assertEquals(JSON_ARRAY.toString(), CACHE_DOUBLE_UTILS.getJSONArray("jsonArray").toString()); CACHE_MEMORY_UTILS.remove("jsonArray"); assertEquals(JSON_ARRAY.toString(), CACHE_DOUBLE_UTILS.getJSONArray("jsonArray").toString()); CACHE_DISK_UTILS.remove("jsonArray"); assertNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray")); } @Test public void getBitmap() { String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100"; assertEquals(BITMAP, CACHE_DOUBLE_UTILS.getBitmap("bitmap")); CACHE_MEMORY_UTILS.remove("bitmap"); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CACHE_DOUBLE_UTILS.getBitmap("bitmap"), Bitmap.CompressFormat.PNG, 100) ); CACHE_DISK_UTILS.remove("bitmap"); assertNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap")); } @Test public void getDrawable() { String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100"; assertEquals(DRAWABLE, CACHE_DOUBLE_UTILS.getDrawable("drawable")); CACHE_MEMORY_UTILS.remove("drawable"); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CACHE_DOUBLE_UTILS.getDrawable("drawable"), Bitmap.CompressFormat.PNG, 100) ); CACHE_DISK_UTILS.remove("drawable"); assertNull(CACHE_DOUBLE_UTILS.getDrawable("drawable")); } @Test public void getParcel() { assertEquals(PARCELABLE_TEST, CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR)); CACHE_MEMORY_UTILS.remove("parcelable"); assertEquals(PARCELABLE_TEST, CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR)); CACHE_DISK_UTILS.remove("parcelable"); assertNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR)); } @Test public void getSerializable() { assertEquals(SERIALIZABLE_TEST, CACHE_DOUBLE_UTILS.getSerializable("serializable")); CACHE_MEMORY_UTILS.remove("serializable"); assertEquals(SERIALIZABLE_TEST, CACHE_DOUBLE_UTILS.getSerializable("serializable")); CACHE_DISK_UTILS.remove("serializable"); assertNull(CACHE_DOUBLE_UTILS.getSerializable("serializable")); } @Test public void getCacheDiskSize() { assertEquals(FileUtils.getLength(CACHE_FILE), CACHE_DOUBLE_UTILS.getCacheDiskSize()); } @Test public void getCacheDiskCount() { assertEquals(8, CACHE_DOUBLE_UTILS.getCacheDiskCount()); } @Test public void getCacheMemoryCount() { assertEquals(8, CACHE_DOUBLE_UTILS.getCacheMemoryCount()); } @Test public void remove() { assertNotNull(CACHE_DOUBLE_UTILS.getString("string")); CACHE_DOUBLE_UTILS.remove("string"); assertNull(CACHE_DOUBLE_UTILS.getString("string")); } @Test public void clear() { assertNotNull(CACHE_DOUBLE_UTILS.getBytes("bytes")); assertNotNull(CACHE_DOUBLE_UTILS.getString("string")); assertNotNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject")); assertNotNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray")); assertNotNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap")); assertNotNull(CACHE_DOUBLE_UTILS.getDrawable("drawable")); assertNotNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR)); assertNotNull(CACHE_DOUBLE_UTILS.getSerializable("serializable")); CACHE_DOUBLE_UTILS.clear(); assertNull(CACHE_DOUBLE_UTILS.getBytes("bytes")); assertNull(CACHE_DOUBLE_UTILS.getString("string")); assertNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject")); assertNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray")); assertNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap")); assertNull(CACHE_DOUBLE_UTILS.getDrawable("drawable")); assertNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR)); assertNull(CACHE_DOUBLE_UTILS.getSerializable("serializable")); assertEquals(0, CACHE_DOUBLE_UTILS.getCacheDiskSize()); assertEquals(0, CACHE_DOUBLE_UTILS.getCacheDiskCount()); assertEquals(0, CACHE_DOUBLE_UTILS.getCacheMemoryCount()); } @After public void tearDown() { CACHE_DOUBLE_UTILS.clear(); } static class ParcelableTest implements Parcelable { String author; String className; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } ParcelableTest(String author, String className) { this.author = author; this.className = className; } ParcelableTest(Parcel in) { author = in.readString(); className = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(author); dest.writeString(className); } @Override public int describeContents() { return 0; } public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() { @Override public ParcelableTest createFromParcel(Parcel in) { return new ParcelableTest(in); } @Override public ParcelableTest[] newArray(int size) { return new ParcelableTest[size]; } }; @Override public boolean equals(Object obj) { return obj instanceof ParcelableTest && ((ParcelableTest) obj).author.equals(author) && ((ParcelableTest) obj).className.equals(className); } } static class SerializableTest implements Serializable { private static final long serialVersionUID = -5806706668736895024L; String author; String className; SerializableTest(String author, String className) { this.author = author; this.className = className; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public boolean equals(Object obj) { return obj instanceof SerializableTest && ((SerializableTest) obj).author.equals(author) && ((SerializableTest) obj).className.equals(className); } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
2,140
```java package com.blankj.utilcode.util; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * <pre> * author: blankj * blog : path_to_url * time : 2020/04/09 * desc : * </pre> */ public class PathUtilsTest extends BaseTest { @Test public void join() { assertEquals(PathUtils.join("", ""), ""); assertEquals(PathUtils.join("", "data"), "/data"); assertEquals(PathUtils.join("", "//data"), "/data"); assertEquals(PathUtils.join("", "data//"), "/data"); assertEquals(PathUtils.join("", "//data//"), "/data"); assertEquals(PathUtils.join("/sdcard", "data"), "/sdcard/data"); assertEquals(PathUtils.join("/sdcard/", "data"), "/sdcard/data"); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/PathUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
179
```java package com.blankj.utilcode.util; import org.junit.Test; import java.io.File; import java.io.FileFilter; import static com.blankj.utilcode.util.TestConfig.FILE_SEP; import static com.blankj.utilcode.util.TestConfig.PATH_FILE; import static com.blankj.utilcode.util.TestConfig.PATH_TEMP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/19 * desc : test FileUtils * </pre> */ public class FileUtilsTest extends BaseTest { private FileFilter mFilter = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith("8.txt"); } }; private FileUtils.OnReplaceListener mListener = new FileUtils.OnReplaceListener() { @Override public boolean onReplace(File srcFile, File destFile) { return true; } }; @Test public void getFileByPath() { assertNull(FileUtils.getFileByPath(" ")); assertNotNull(FileUtils.getFileByPath(PATH_FILE)); } @Test public void isFileExists() { assertTrue(FileUtils.isFileExists(PATH_FILE + "UTF8.txt")); assertFalse(FileUtils.isFileExists(PATH_FILE + "UTF8")); } @Test public void rename() { assertTrue(FileUtils.rename(PATH_FILE + "GBK.txt", "GBK1.txt")); assertTrue(FileUtils.rename(PATH_FILE + "GBK1.txt", "GBK.txt")); } @Test public void isDir() { assertFalse(FileUtils.isDir(PATH_FILE + "UTF8.txt")); assertTrue(FileUtils.isDir(PATH_FILE)); } @Test public void isFile() { assertTrue(FileUtils.isFile(PATH_FILE + "UTF8.txt")); assertFalse(FileUtils.isFile(PATH_FILE)); } @Test public void createOrExistsDir() { assertTrue(FileUtils.createOrExistsDir(PATH_FILE + "new Dir")); assertTrue(FileUtils.createOrExistsDir(PATH_FILE)); assertTrue(FileUtils.delete(PATH_FILE + "new Dir")); } @Test public void createOrExistsFile() { assertTrue(FileUtils.createOrExistsFile(PATH_FILE + "new File")); assertFalse(FileUtils.createOrExistsFile(PATH_FILE)); assertTrue(FileUtils.delete(PATH_FILE + "new File")); } @Test public void createFileByDeleteOldFile() { assertTrue(FileUtils.createFileByDeleteOldFile(PATH_FILE + "new File")); assertFalse(FileUtils.createFileByDeleteOldFile(PATH_FILE)); assertTrue(FileUtils.delete(PATH_FILE + "new File")); } @Test public void copyDir() { assertFalse(FileUtils.copy(PATH_FILE, PATH_FILE, mListener)); assertFalse(FileUtils.copy(PATH_FILE, PATH_FILE + "new Dir", mListener)); assertTrue(FileUtils.copy(PATH_FILE, PATH_TEMP, mListener)); assertTrue(FileUtils.delete(PATH_TEMP)); } @Test public void copyFile() { assertFalse(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_FILE + "GBK.txt", mListener)); assertTrue(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_FILE + "new Dir" + FILE_SEP + "GBK.txt", mListener)); assertTrue(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_TEMP + "GBK.txt", mListener)); assertTrue(FileUtils.delete(PATH_FILE + "new Dir")); assertTrue(FileUtils.delete(PATH_TEMP)); } @Test public void moveDir() { assertFalse(FileUtils.move(PATH_FILE, PATH_FILE, mListener)); assertFalse(FileUtils.move(PATH_FILE, PATH_FILE + "new Dir", mListener)); assertTrue(FileUtils.move(PATH_FILE, PATH_TEMP, mListener)); assertTrue(FileUtils.move(PATH_TEMP, PATH_FILE, mListener)); } @Test public void moveFile() { assertFalse(FileUtils.move(PATH_FILE + "GBK.txt", PATH_FILE + "GBK.txt", mListener)); assertTrue(FileUtils.move(PATH_FILE + "GBK.txt", PATH_TEMP + "GBK.txt", mListener)); assertTrue(FileUtils.move(PATH_TEMP + "GBK.txt", PATH_FILE + "GBK.txt", mListener)); FileUtils.delete(PATH_TEMP); } @Test public void listFilesInDir() { System.out.println(FileUtils.listFilesInDir(PATH_FILE, false).toString()); System.out.println(FileUtils.listFilesInDir(PATH_FILE, true).toString()); } @Test public void listFilesInDirWithFilter() { System.out.println(FileUtils.listFilesInDirWithFilter(PATH_FILE, mFilter, false).toString()); System.out.println(FileUtils.listFilesInDirWithFilter(PATH_FILE, mFilter, true).toString()); } @Test public void getFileLastModified() { System.out.println(TimeUtils.millis2String(FileUtils.getFileLastModified(PATH_FILE))); } @Test public void getFileCharsetSimple() { assertEquals("GBK", FileUtils.getFileCharsetSimple(PATH_FILE + "GBK.txt")); assertEquals("Unicode", FileUtils.getFileCharsetSimple(PATH_FILE + "Unicode.txt")); assertEquals("UTF-8", FileUtils.getFileCharsetSimple(PATH_FILE + "UTF8.txt")); assertEquals("UTF-16BE", FileUtils.getFileCharsetSimple(PATH_FILE + "UTF16BE.txt")); } @Test public void isUtf8() { assertTrue(FileUtils.isUtf8(PATH_FILE + "UTF8.txt")); assertFalse(FileUtils.isUtf8(PATH_FILE + "UTF16BE.txt")); assertFalse(FileUtils.isUtf8(PATH_FILE + "Unicode.txt")); } @Test public void getFileLines() { assertEquals(7, FileUtils.getFileLines(PATH_FILE + "UTF8.txt")); } @Test public void getDirSize() { System.out.println(FileUtils.getSize(PATH_FILE)); } @Test public void getFileSize() { System.out.println(FileUtils.getSize(PATH_FILE + "UTF8.txt")); } @Test public void getDirLength() { System.out.println(FileUtils.getLength(PATH_FILE)); } @Test public void getFileLength() { System.out.println(FileUtils.getFileLength(PATH_FILE + "UTF8.txt")); // System.out.println(FileUtils.getFileLength("path_to_url")); } @Test public void getFileMD5ToString() { assertEquals("249D3E76851DCC56C945994DE9DAC406", FileUtils.getFileMD5ToString(PATH_FILE + "UTF8.txt")); } @Test public void getDirName() { assertEquals(PATH_FILE, FileUtils.getDirName(new File(PATH_FILE + "UTF8.txt"))); assertEquals(PATH_FILE, FileUtils.getDirName(PATH_FILE + "UTF8.txt")); } @Test public void getFileName() { assertEquals("UTF8.txt", FileUtils.getFileName(PATH_FILE + "UTF8.txt")); assertEquals("UTF8.txt", FileUtils.getFileName(new File(PATH_FILE + "UTF8.txt"))); } @Test public void getFileNameNoExtension() { assertEquals("UTF8", FileUtils.getFileNameNoExtension(PATH_FILE + "UTF8.txt")); assertEquals("UTF8", FileUtils.getFileNameNoExtension(new File(PATH_FILE + "UTF8.txt"))); } @Test public void getFileExtension() { assertEquals("txt", FileUtils.getFileExtension(new File(PATH_FILE + "UTF8.txt"))); assertEquals("txt", FileUtils.getFileExtension(PATH_FILE + "UTF8.txt")); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/FileUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,592
```java package com.blankj.utilcode.util; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.Serializable; import static com.blankj.utilcode.util.TestConfig.FILE_SEP; import static com.blankj.utilcode.util.TestConfig.PATH_CACHE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2017/05/26 * desc : test CacheDiskUtils * </pre> */ public class CacheDiskUtilsTest extends BaseTest { private static final String DISK1_PATH = PATH_CACHE + "disk1" + FILE_SEP; private static final String DISK2_PATH = PATH_CACHE + "disk2" + FILE_SEP; private static final File DISK1_FILE = new File(DISK1_PATH); private static final File DISK2_FILE = new File(DISK2_PATH); private static final CacheDiskUtils CACHE_DISK_UTILS1 = CacheDiskUtils.getInstance(DISK1_FILE); private static final CacheDiskUtils CACHE_DISK_UTILS2 = CacheDiskUtils.getInstance(DISK2_FILE); private static final byte[] BYTES = "CacheDiskUtils".getBytes(); private static final String STRING = "CacheDiskUtils"; private static final JSONObject JSON_OBJECT = new JSONObject(); private static final JSONArray JSON_ARRAY = new JSONArray(); private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDiskUtils"); private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDiskUtils"); private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP); static { try { JSON_OBJECT.put("class", "CacheDiskUtils"); JSON_OBJECT.put("author", "Blankj"); JSON_ARRAY.put(0, JSON_OBJECT); } catch (JSONException e) { e.printStackTrace(); } } @Before public void setUp() { CACHE_DISK_UTILS1.put("bytes1", BYTES, 60 * CacheDiskUtils.SEC); CACHE_DISK_UTILS1.put("string1", STRING, 60 * CacheDiskUtils.MIN); CACHE_DISK_UTILS1.put("jsonObject1", JSON_OBJECT, 24 * CacheDiskUtils.HOUR); CACHE_DISK_UTILS1.put("jsonArray1", JSON_ARRAY, 365 * CacheDiskUtils.DAY); CACHE_DISK_UTILS1.put("bitmap1", BITMAP, 60 * CacheDiskUtils.SEC); CACHE_DISK_UTILS1.put("drawable1", DRAWABLE, 60 * CacheDiskUtils.SEC); CACHE_DISK_UTILS1.put("parcelable1", PARCELABLE_TEST, 60 * CacheDiskUtils.SEC); CACHE_DISK_UTILS1.put("serializable1", SERIALIZABLE_TEST, 60 * CacheDiskUtils.SEC); CACHE_DISK_UTILS2.put("bytes2", BYTES); CACHE_DISK_UTILS2.put("string2", STRING); CACHE_DISK_UTILS2.put("jsonObject2", JSON_OBJECT); CACHE_DISK_UTILS2.put("jsonArray2", JSON_ARRAY); CACHE_DISK_UTILS2.put("bitmap2", BITMAP); CACHE_DISK_UTILS2.put("drawable2", DRAWABLE); CACHE_DISK_UTILS2.put("parcelable2", PARCELABLE_TEST); CACHE_DISK_UTILS2.put("serializable2", SERIALIZABLE_TEST); } @Test public void getBytes() { assertEquals(STRING, new String(CACHE_DISK_UTILS1.getBytes("bytes1"))); assertEquals(STRING, new String(CACHE_DISK_UTILS1.getBytes("bytes1", null))); assertNull(CACHE_DISK_UTILS1.getBytes("bytes2", null)); assertEquals(STRING, new String(CACHE_DISK_UTILS2.getBytes("bytes2"))); assertEquals(STRING, new String(CACHE_DISK_UTILS2.getBytes("bytes2", null))); assertNull(CACHE_DISK_UTILS2.getBytes("bytes1", null)); } @Test public void getString() { assertEquals(STRING, CACHE_DISK_UTILS1.getString("string1")); assertEquals(STRING, CACHE_DISK_UTILS1.getString("string1", null)); assertNull(CACHE_DISK_UTILS1.getString("string2", null)); assertEquals(STRING, CACHE_DISK_UTILS2.getString("string2")); assertEquals(STRING, CACHE_DISK_UTILS2.getString("string2", null)); assertNull(CACHE_DISK_UTILS2.getString("string1", null)); } @Test public void getJSONObject() { assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS1.getJSONObject("jsonObject1").toString()); assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS1.getJSONObject("jsonObject1", null).toString()); assertNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject2", null)); assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS2.getJSONObject("jsonObject2").toString()); assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS2.getJSONObject("jsonObject2", null).toString()); assertNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject1", null)); } @Test public void getJSONArray() { assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS1.getJSONArray("jsonArray1").toString()); assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS1.getJSONArray("jsonArray1", null).toString()); assertNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray2", null)); assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS2.getJSONArray("jsonArray2").toString()); assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS2.getJSONArray("jsonArray2", null).toString()); assertNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray1", null)); } @Test public void getBitmap() { assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS1.getBitmap("bitmap1"), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS1.getBitmap("bitmap1", null), Bitmap.CompressFormat.PNG, 100) ); assertNull(CACHE_DISK_UTILS1.getBitmap("bitmap2", null)); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS2.getBitmap("bitmap2"), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS2.getBitmap("bitmap2", null), Bitmap.CompressFormat.PNG, 100) ); assertNull(CACHE_DISK_UTILS2.getBitmap("bitmap1", null)); } @Test public void getDrawable() { String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100"; assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CACHE_DISK_UTILS1.getDrawable("drawable1"), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CACHE_DISK_UTILS1.getDrawable("drawable1", null), Bitmap.CompressFormat.PNG, 100) ); assertNull(CACHE_DISK_UTILS1.getDrawable("drawable2", null)); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CACHE_DISK_UTILS2.getDrawable("drawable2"), Bitmap.CompressFormat.PNG, 100) ); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CACHE_DISK_UTILS2.getDrawable("drawable2", null), Bitmap.CompressFormat.PNG, 100) ); assertNull(CACHE_DISK_UTILS2.getDrawable("drawable1", null)); } @Test public void getParcel() { assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR)); assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR, null)); assertNull(CACHE_DISK_UTILS1.getParcelable("parcelable2", ParcelableTest.CREATOR, null)); assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR)); assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR, null)); assertNull(CACHE_DISK_UTILS2.getParcelable("parcelable1", ParcelableTest.CREATOR, null)); } @Test public void getSerializable() { assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS1.getSerializable("serializable1")); assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS1.getSerializable("serializable1", null)); assertNull(CACHE_DISK_UTILS1.getSerializable("parcelable2", null)); assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS2.getSerializable("serializable2")); assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS2.getSerializable("serializable2", null)); assertNull(CACHE_DISK_UTILS2.getSerializable("parcelable1", null)); } @Test public void getCacheSize() { System.out.println(FileUtils.getLength(DISK1_FILE)); assertEquals(FileUtils.getLength(DISK1_FILE), CACHE_DISK_UTILS1.getCacheSize()); System.out.println(FileUtils.getLength(DISK2_FILE)); assertEquals(FileUtils.getLength(DISK2_FILE), CACHE_DISK_UTILS2.getCacheSize()); } @Test public void getCacheCount() { assertEquals(8, CACHE_DISK_UTILS1.getCacheCount()); assertEquals(8, CACHE_DISK_UTILS2.getCacheCount()); } @Test public void remove() { assertNotNull(CACHE_DISK_UTILS1.getString("string1")); assertTrue(CACHE_DISK_UTILS1.remove("string1")); assertNull(CACHE_DISK_UTILS1.getString("string1")); assertNotNull(CACHE_DISK_UTILS2.getString("string2")); CACHE_DISK_UTILS2.remove("string2"); assertNull(CACHE_DISK_UTILS2.getString("string2")); } @Test public void clear() { assertNotNull(CACHE_DISK_UTILS1.getBytes("bytes1")); assertNotNull(CACHE_DISK_UTILS1.getString("string1")); assertNotNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject1")); assertNotNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray1")); assertNotNull(CACHE_DISK_UTILS1.getBitmap("bitmap1")); assertNotNull(CACHE_DISK_UTILS1.getDrawable("drawable1")); assertNotNull(CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR)); assertNotNull(CACHE_DISK_UTILS1.getSerializable("serializable1")); CACHE_DISK_UTILS1.clear(); assertNull(CACHE_DISK_UTILS1.getBytes("bytes1")); assertNull(CACHE_DISK_UTILS1.getString("string1")); assertNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject1")); assertNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray1")); assertNull(CACHE_DISK_UTILS1.getBitmap("bitmap1")); assertNull(CACHE_DISK_UTILS1.getDrawable("drawable1")); assertNull(CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR)); assertNull(CACHE_DISK_UTILS1.getSerializable("serializable1")); assertEquals(0, CACHE_DISK_UTILS1.getCacheSize()); assertEquals(0, CACHE_DISK_UTILS1.getCacheCount()); assertNotNull(CACHE_DISK_UTILS2.getBytes("bytes2")); assertNotNull(CACHE_DISK_UTILS2.getString("string2")); assertNotNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject2")); assertNotNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray2")); assertNotNull(CACHE_DISK_UTILS2.getBitmap("bitmap2")); assertNotNull(CACHE_DISK_UTILS2.getDrawable("drawable2")); assertNotNull(CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR)); assertNotNull(CACHE_DISK_UTILS2.getSerializable("serializable2")); CACHE_DISK_UTILS2.clear(); assertNull(CACHE_DISK_UTILS2.getBytes("bytes2")); assertNull(CACHE_DISK_UTILS2.getString("string2")); assertNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject2")); assertNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray2")); assertNull(CACHE_DISK_UTILS2.getBitmap("bitmap2")); assertNull(CACHE_DISK_UTILS2.getDrawable("drawable2")); assertNull(CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR)); assertNull(CACHE_DISK_UTILS2.getSerializable("serializable2")); assertEquals(0, CACHE_DISK_UTILS2.getCacheSize()); assertEquals(0, CACHE_DISK_UTILS2.getCacheCount()); } @After public void tearDown() { CACHE_DISK_UTILS1.clear(); CACHE_DISK_UTILS2.clear(); } static class ParcelableTest implements Parcelable { String author; String className; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } ParcelableTest(String author, String className) { this.author = author; this.className = className; } ParcelableTest(Parcel in) { author = in.readString(); className = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(author); dest.writeString(className); } @Override public int describeContents() { return 0; } public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() { @Override public ParcelableTest createFromParcel(Parcel in) { return new ParcelableTest(in); } @Override public ParcelableTest[] newArray(int size) { return new ParcelableTest[size]; } }; @Override public boolean equals(Object obj) { return obj instanceof ParcelableTest && ((ParcelableTest) obj).author.equals(author) && ((ParcelableTest) obj).className.equals(className); } } static class SerializableTest implements Serializable { private static final long serialVersionUID = -5806706668736895024L; String author; String className; SerializableTest(String author, String className) { this.author = author; this.className = className; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public boolean equals(Object obj) { return obj instanceof SerializableTest && ((SerializableTest) obj).author.equals(author) && ((SerializableTest) obj).className.equals(className); } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,284
```java package com.blankj.utilcode.util; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.Serializable; import static com.blankj.utilcode.util.TestConfig.FILE_SEP; import static com.blankj.utilcode.util.TestConfig.PATH_CACHE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/06/13 * desc : test CacheDoubleStaticUtils * </pre> */ public class CacheDoubleStaticUtilsTest extends BaseTest { private static final String CACHE_PATH = PATH_CACHE + "double" + FILE_SEP; private static final File CACHE_FILE = new File(CACHE_PATH); private static final byte[] BYTES = "CacheDoubleUtils".getBytes(); private static final String STRING = "CacheDoubleUtils"; private static final JSONObject JSON_OBJECT = new JSONObject(); private static final JSONArray JSON_ARRAY = new JSONArray(); private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDoubleUtils"); private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDoubleUtils"); private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP); private static final CacheMemoryUtils CACHE_MEMORY_UTILS = CacheMemoryUtils.getInstance(); private static final CacheDiskUtils CACHE_DISK_UTILS = CacheDiskUtils.getInstance(CACHE_FILE); private static final CacheDoubleUtils CACHE_DOUBLE_UTILS = CacheDoubleUtils.getInstance(CACHE_MEMORY_UTILS, CACHE_DISK_UTILS); static { try { JSON_OBJECT.put("class", "CacheDoubleUtils"); JSON_OBJECT.put("author", "Blankj"); JSON_ARRAY.put(0, JSON_OBJECT); } catch (JSONException e) { e.printStackTrace(); } } @Before public void setUp() { CacheDoubleStaticUtils.setDefaultCacheDoubleUtils(CACHE_DOUBLE_UTILS); CacheDoubleStaticUtils.put("bytes", BYTES); CacheDoubleStaticUtils.put("string", STRING); CacheDoubleStaticUtils.put("jsonObject", JSON_OBJECT); CacheDoubleStaticUtils.put("jsonArray", JSON_ARRAY); CacheDoubleStaticUtils.put("bitmap", BITMAP); CacheDoubleStaticUtils.put("drawable", DRAWABLE); CacheDoubleStaticUtils.put("parcelable", PARCELABLE_TEST); CacheDoubleStaticUtils.put("serializable", SERIALIZABLE_TEST); } @Test public void getBytes() { assertEquals(STRING, new String(CacheDoubleStaticUtils.getBytes("bytes"))); CACHE_MEMORY_UTILS.remove("bytes"); assertEquals(STRING, new String(CacheDoubleStaticUtils.getBytes("bytes"))); CACHE_DISK_UTILS.remove("bytes"); assertNull(CacheDoubleStaticUtils.getBytes("bytes")); } @Test public void getString() { assertEquals(STRING, CacheDoubleStaticUtils.getString("string")); CACHE_MEMORY_UTILS.remove("string"); assertEquals(STRING, CacheDoubleStaticUtils.getString("string")); CACHE_DISK_UTILS.remove("string"); assertNull(CacheDoubleStaticUtils.getString("string")); } @Test public void getJSONObject() { assertEquals(JSON_OBJECT.toString(), CacheDoubleStaticUtils.getJSONObject("jsonObject").toString()); CACHE_MEMORY_UTILS.remove("jsonObject"); assertEquals(JSON_OBJECT.toString(), CacheDoubleStaticUtils.getJSONObject("jsonObject").toString()); CACHE_DISK_UTILS.remove("jsonObject"); assertNull(CacheDoubleStaticUtils.getJSONObject("jsonObject")); } @Test public void getJSONArray() { assertEquals(JSON_ARRAY.toString(), CacheDoubleStaticUtils.getJSONArray("jsonArray").toString()); CACHE_MEMORY_UTILS.remove("jsonArray"); assertEquals(JSON_ARRAY.toString(), CacheDoubleStaticUtils.getJSONArray("jsonArray").toString()); CACHE_DISK_UTILS.remove("jsonArray"); assertNull(CacheDoubleStaticUtils.getJSONArray("jsonArray")); } @Test public void getBitmap() { assertEquals(BITMAP, CacheDoubleStaticUtils.getBitmap("bitmap")); CACHE_MEMORY_UTILS.remove("bitmap"); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.bitmap2Bytes(CacheDoubleStaticUtils.getBitmap("bitmap"), Bitmap.CompressFormat.PNG, 100) ); CACHE_DISK_UTILS.remove("bitmap"); assertNull(CacheDoubleStaticUtils.getBitmap("bitmap")); } @Test public void getDrawable() { assertEquals(DRAWABLE, CacheDoubleStaticUtils.getDrawable("drawable")); CACHE_MEMORY_UTILS.remove("drawable"); assertArrayEquals( ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100), ImageUtils.drawable2Bytes(CacheDoubleStaticUtils.getDrawable("drawable"), Bitmap.CompressFormat.PNG, 100) ); CACHE_DISK_UTILS.remove("drawable"); assertNull(CacheDoubleStaticUtils.getDrawable("drawable")); } @Test public void getParcel() { assertEquals(PARCELABLE_TEST, CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR)); CACHE_MEMORY_UTILS.remove("parcelable"); assertEquals(PARCELABLE_TEST, CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR)); CACHE_DISK_UTILS.remove("parcelable"); assertNull(CacheDoubleStaticUtils.getParcelable("parcelable", PARCELABLE_TEST.CREATOR)); } @Test public void getSerializable() { assertEquals(SERIALIZABLE_TEST, CacheDoubleStaticUtils.getSerializable("serializable")); CACHE_MEMORY_UTILS.remove("serializable"); assertEquals(SERIALIZABLE_TEST, CacheDoubleStaticUtils.getSerializable("serializable")); CACHE_DISK_UTILS.remove("serializable"); assertNull(CacheDoubleStaticUtils.getSerializable("serializable")); } @Test public void getCacheDiskSize() { assertEquals(FileUtils.getLength(CACHE_FILE), CacheDoubleStaticUtils.getCacheDiskSize()); } @Test public void getCacheDiskCount() { assertEquals(8, CacheDoubleStaticUtils.getCacheDiskCount()); } @Test public void getCacheMemoryCount() { assertEquals(8, CacheDoubleStaticUtils.getCacheMemoryCount()); } @Test public void remove() { assertNotNull(CacheDoubleStaticUtils.getString("string")); CacheDoubleStaticUtils.remove("string"); assertNull(CacheDoubleStaticUtils.getString("string")); } @Test public void clear() { assertNotNull(CacheDoubleStaticUtils.getBytes("bytes")); assertNotNull(CacheDoubleStaticUtils.getString("string")); assertNotNull(CacheDoubleStaticUtils.getJSONObject("jsonObject")); assertNotNull(CacheDoubleStaticUtils.getJSONArray("jsonArray")); assertNotNull(CacheDoubleStaticUtils.getBitmap("bitmap")); assertNotNull(CacheDoubleStaticUtils.getDrawable("drawable")); assertNotNull(CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR)); assertNotNull(CacheDoubleStaticUtils.getSerializable("serializable")); CacheDoubleStaticUtils.clear(); assertNull(CacheDoubleStaticUtils.getBytes("bytes")); assertNull(CacheDoubleStaticUtils.getString("string")); assertNull(CacheDoubleStaticUtils.getJSONObject("jsonObject")); assertNull(CacheDoubleStaticUtils.getJSONArray("jsonArray")); assertNull(CacheDoubleStaticUtils.getBitmap("bitmap")); assertNull(CacheDoubleStaticUtils.getDrawable("drawable")); assertNull(CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR)); assertNull(CacheDoubleStaticUtils.getSerializable("serializable")); assertEquals(0, CacheDoubleStaticUtils.getCacheDiskSize()); assertEquals(0, CacheDoubleStaticUtils.getCacheDiskCount()); assertEquals(0, CacheDoubleStaticUtils.getCacheMemoryCount()); } @After public void tearDown() { CacheDoubleStaticUtils.clear(); } static class ParcelableTest implements Parcelable { String author; String className; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } ParcelableTest(String author, String className) { this.author = author; this.className = className; } ParcelableTest(Parcel in) { author = in.readString(); className = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(author); dest.writeString(className); } @Override public int describeContents() { return 0; } public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() { @Override public ParcelableTest createFromParcel(Parcel in) { return new ParcelableTest(in); } @Override public ParcelableTest[] newArray(int size) { return new ParcelableTest[size]; } }; @Override public boolean equals(Object obj) { return obj instanceof ParcelableTest && ((ParcelableTest) obj).author.equals(author) && ((ParcelableTest) obj).className.equals(className); } } static class SerializableTest implements Serializable { private static final long serialVersionUID = -5806706668736895024L; String author; String className; SerializableTest(String author, String className) { this.author = author; this.className = className; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public boolean equals(Object obj) { return obj instanceof SerializableTest && ((SerializableTest) obj).author.equals(author) && ((SerializableTest) obj).className.equals(className); } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleStaticUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
2,175
```java package com.blankj.utilcode.util; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/07/14 * desc : * </pre> */ public class BusUtilsVsEventBusTest extends BaseTest { @Subscribe public void eventBusFun(String param) { } @BusUtils.Bus(tag = "busUtilsFun") public void busUtilsFun(String param) { } @Before public void setUp() throws Exception { // AOP busUtilsFun ReflectUtils getInstance = ReflectUtils.reflect(BusUtils.class).method("getInstance"); getInstance.method("registerBus", "busUtilsFun", BusUtilsVsEventBusTest.class.getName(), "busUtilsFun", String.class.getName(), "param", false, "POSTING"); } /** * 10000 10 */ // @Test public void compareRegister10000Times() { final List<BusUtilsVsEventBusTest> eventBusTests = new ArrayList<>(); final List<BusUtilsVsEventBusTest> busUtilsTests = new ArrayList<>(); compareWithEventBus("Register 10000 times.", 10, 10000, new CompareCallback() { @Override public void runEventBus() { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); EventBus.getDefault().register(test); eventBusTests.add(test); } @Override public void runBusUtils() { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); BusUtils.register(test); busUtilsTests.add(test); } @Override public void restState() { for (BusUtilsVsEventBusTest test : eventBusTests) { EventBus.getDefault().unregister(test); } eventBusTests.clear(); for (BusUtilsVsEventBusTest test : busUtilsTests) { BusUtils.unregister(test); } busUtilsTests.clear(); } }); } /** * 1 * 1000000 10 */ // @Test public void comparePostTo1Subscriber1000000Times() { comparePostTemplate("Post to 1 subscriber 1000000 times.", 1, 1000000); } /** * 100 * 100000 10 */ // @Test public void comparePostTo100Subscribers100000Times() { comparePostTemplate("Post to 100 subscribers 100000 times.", 100, 100000); } private void comparePostTemplate(String name, int subscribeNum, int postTimes) { final List<BusUtilsVsEventBusTest> tests = new ArrayList<>(); for (int i = 0; i < subscribeNum; i++) { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); EventBus.getDefault().register(test); BusUtils.register(test); tests.add(test); } compareWithEventBus(name, 10, postTimes, new CompareCallback() { @Override public void runEventBus() { EventBus.getDefault().post("EventBus"); } @Override public void runBusUtils() { BusUtils.post("busUtilsFun", "BusUtils"); } @Override public void restState() { } }); for (BusUtilsVsEventBusTest test : tests) { EventBus.getDefault().unregister(test); BusUtils.unregister(test); } } /** * 10000 10 */ // @Test public void compareUnregister10000Times() { final List<BusUtilsVsEventBusTest> tests = new ArrayList<>(); for (int i = 0; i < 10000; i++) { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); EventBus.getDefault().register(test); BusUtils.register(test); tests.add(test); } compareWithEventBus("Unregister 10000 times.", 10, 1, new CompareCallback() { @Override public void runEventBus() { for (BusUtilsVsEventBusTest test : tests) { EventBus.getDefault().unregister(test); } } @Override public void runBusUtils() { for (BusUtilsVsEventBusTest test : tests) { BusUtils.unregister(test); } } @Override public void restState() { for (BusUtilsVsEventBusTest test : tests) { EventBus.getDefault().register(test); BusUtils.register(test); } } }); for (BusUtilsVsEventBusTest test : tests) { EventBus.getDefault().unregister(test); BusUtils.unregister(test); } } /** * @param name * @param sampleSize * @param times * @param callback */ private void compareWithEventBus(String name, int sampleSize, int times, CompareCallback callback) { long[][] dur = new long[2][sampleSize]; for (int i = 0; i < sampleSize; i++) { long cur = System.currentTimeMillis(); for (int j = 0; j < times; j++) { callback.runEventBus(); } dur[0][i] = System.currentTimeMillis() - cur; cur = System.currentTimeMillis(); for (int j = 0; j < times; j++) { callback.runBusUtils(); } dur[1][i] = System.currentTimeMillis() - cur; callback.restState(); } long eventBusAverageTime = 0; long busUtilsAverageTime = 0; for (int i = 0; i < sampleSize; i++) { eventBusAverageTime += dur[0][i]; busUtilsAverageTime += dur[1][i]; } System.out.println( name + "\nEventBusCostTime: " + eventBusAverageTime / sampleSize + "\nBusUtilsCostTime: " + busUtilsAverageTime / sampleSize ); } public interface CompareCallback { void runEventBus(); void runBusUtils(); void restState(); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsVsEventBusTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,396
```java package com.blankj.utilcode.util; import android.util.SparseArray; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.util.SparseLongArray; import org.junit.Test; import java.util.HashMap; import java.util.LinkedList; import androidx.collection.LongSparseArray; import androidx.collection.SimpleArrayMap; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2017/12/24 * desc : test ObjectUtils * </pre> */ public class ObjectUtilsTest extends BaseTest { @Test public void isEmpty() { StringBuilder sb = new StringBuilder(""); StringBuilder sb1 = new StringBuilder(" "); String string = ""; String string1 = " "; int[][] arr = new int[][]{}; LinkedList<Integer> list = new LinkedList<>(); HashMap<String, Integer> map = new HashMap<>(); SimpleArrayMap<String, Integer> sam = new SimpleArrayMap<>(); SparseArray<String> sa = new SparseArray<>(); SparseBooleanArray sba = new SparseBooleanArray(); SparseIntArray sia = new SparseIntArray(); SparseLongArray sla = new SparseLongArray(); LongSparseArray<String> lsa = new LongSparseArray<>(); android.util.LongSparseArray<String> lsaV4 = new android.util.LongSparseArray<>(); assertTrue(ObjectUtils.isEmpty(sb)); assertFalse(ObjectUtils.isEmpty(sb1)); assertTrue(ObjectUtils.isEmpty(string)); assertFalse(ObjectUtils.isEmpty(string1)); assertTrue(ObjectUtils.isEmpty(arr)); assertTrue(ObjectUtils.isEmpty(list)); assertTrue(ObjectUtils.isEmpty(map)); assertTrue(ObjectUtils.isEmpty(sam)); assertTrue(ObjectUtils.isEmpty(sa)); assertTrue(ObjectUtils.isEmpty(sba)); assertTrue(ObjectUtils.isEmpty(sia)); assertTrue(ObjectUtils.isEmpty(sla)); assertTrue(ObjectUtils.isEmpty(lsa)); assertTrue(ObjectUtils.isEmpty(lsaV4)); assertTrue(!ObjectUtils.isNotEmpty(sb)); assertFalse(!ObjectUtils.isNotEmpty(sb1)); assertTrue(!ObjectUtils.isNotEmpty(string)); assertFalse(!ObjectUtils.isNotEmpty(string1)); assertTrue(!ObjectUtils.isNotEmpty(arr)); assertTrue(!ObjectUtils.isNotEmpty(list)); assertTrue(!ObjectUtils.isNotEmpty(map)); assertTrue(!ObjectUtils.isNotEmpty(sam)); assertTrue(!ObjectUtils.isNotEmpty(sa)); assertTrue(!ObjectUtils.isNotEmpty(sba)); assertTrue(!ObjectUtils.isNotEmpty(sia)); assertTrue(!ObjectUtils.isNotEmpty(sla)); assertTrue(!ObjectUtils.isNotEmpty(lsa)); assertTrue(!ObjectUtils.isNotEmpty(lsaV4)); } @Test public void equals() { assertTrue(ObjectUtils.equals(1, 1)); assertTrue(ObjectUtils.equals("str", "str")); assertTrue(ObjectUtils.equals(null, null)); assertFalse(ObjectUtils.equals(null, 1)); assertFalse(ObjectUtils.equals(null, "")); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ObjectUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
594
```java package com.blankj.utilcode.util; import android.util.Pair; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import static com.blankj.utilcode.util.TestConfig.PATH_ENCRYPT; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/06 * desc : test EncryptUtils * </pre> */ public class EncryptUtilsTest extends BaseTest { @Test public void encryptMD2() { String blankjMD2 = "15435017570D8A73449E25C4622E17A4"; Assert.assertEquals( blankjMD2, EncryptUtils.encryptMD2ToString("blankj") ); assertEquals( blankjMD2, EncryptUtils.encryptMD2ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjMD2), EncryptUtils.encryptMD2("blankj".getBytes()) ); } @Test public void encryptMD5() { String blankjMD5 = "AAC25CD336E01C8655F4EC7875445A60"; assertEquals( blankjMD5, EncryptUtils.encryptMD5ToString("blankj") ); assertEquals( blankjMD5, EncryptUtils.encryptMD5ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjMD5), EncryptUtils.encryptMD5("blankj".getBytes()) ); } @Test public void encryptMD5File() { String fileMd5 = "7f138a09169b250e9dcb378140907378"; assertEquals( fileMd5.toUpperCase(), EncryptUtils.encryptMD5File2String(new File(PATH_ENCRYPT + "MD5.txt")) ); } @Test public void encryptSHA1() { String blankjSHA1 = "C606ACCB1FEB669E19D080ADDDDBB8E6CDA5F43C"; assertEquals( blankjSHA1, EncryptUtils.encryptSHA1ToString("blankj") ); assertEquals( blankjSHA1, EncryptUtils.encryptSHA1ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjSHA1), EncryptUtils.encryptSHA1("blankj".getBytes()) ); } @Test public void encryptSHA224() { String blankjSHA224 = "F4C5C0E8CF56CAC4D06DB6B523F67621859A9D79BDA4B2AC03097D5F"; assertEquals( blankjSHA224, EncryptUtils.encryptSHA224ToString("blankj") ); assertEquals( blankjSHA224, EncryptUtils.encryptSHA224ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjSHA224), EncryptUtils.encryptSHA224("blankj".getBytes()) ); } @Test public void encryptSHA256() { String blankjSHA256 = your_sha256_hash; assertEquals( blankjSHA256, EncryptUtils.encryptSHA256ToString("blankj") ); assertEquals( blankjSHA256, EncryptUtils.encryptSHA256ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjSHA256), EncryptUtils.encryptSHA256("blankj".getBytes())); } @Test public void encryptSHA384() { String blankjSHA384 = your_sha256_hash2B85E0D461101C74BAEDA895BD422557"; assertEquals( blankjSHA384, EncryptUtils.encryptSHA384ToString("blankj") ); assertEquals( blankjSHA384, EncryptUtils.encryptSHA384ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjSHA384), EncryptUtils.encryptSHA384("blankj".getBytes()) ); } @Test public void encryptSHA512() { String blankjSHA512 = your_sha256_hashyour_sha256_hash; assertEquals( blankjSHA512, EncryptUtils.encryptSHA512ToString("blankj") ); assertEquals( blankjSHA512, EncryptUtils.encryptSHA512ToString("blankj".getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjSHA512), EncryptUtils.encryptSHA512("blankj".getBytes()) ); } private String blankjHmacSHA512 = your_sha256_hashyour_sha256_hash; private String blankjHmackey = "blankj"; @Test public void encryptHmacMD5() { String blankjHmacMD5 = "2BA3FDABEE222522044BEC0CE5D6B490"; assertEquals( blankjHmacMD5, EncryptUtils.encryptHmacMD5ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacMD5, EncryptUtils.encryptHmacMD5ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacMD5), EncryptUtils.encryptHmacMD5("blankj".getBytes(), blankjHmackey.getBytes()) ); } @Test public void encryptHmacSHA1() { String blankjHmacSHA1 = "88E83EFD915496860C83739BE2CF4752B2AC105F"; assertEquals( blankjHmacSHA1, EncryptUtils.encryptHmacSHA1ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacSHA1, EncryptUtils.encryptHmacSHA1ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacSHA1), EncryptUtils.encryptHmacSHA1("blankj".getBytes(), blankjHmackey.getBytes()) ); } @Test public void encryptHmacSHA224() { String blankjHmacSHA224 = "E392D83D1030323FB2E062E8165A3AD38366E53DF19EA3290961E153"; assertEquals( blankjHmacSHA224, EncryptUtils.encryptHmacSHA224ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacSHA224, EncryptUtils.encryptHmacSHA224ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacSHA224), EncryptUtils.encryptHmacSHA224("blankj".getBytes(), blankjHmackey.getBytes()) ); } @Test public void encryptHmacSHA256() { String blankjHmacSHA256 = your_sha256_hash; assertEquals( blankjHmacSHA256, EncryptUtils.encryptHmacSHA256ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacSHA256, EncryptUtils.encryptHmacSHA256ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacSHA256), EncryptUtils.encryptHmacSHA256("blankj".getBytes(), blankjHmackey.getBytes()) ); } @Test public void encryptHmacSHA384() { String blankjHmacSHA384 = your_sha256_hashC428AB42F6A962CF79AFAD1302C3223D"; assertEquals( blankjHmacSHA384, EncryptUtils.encryptHmacSHA384ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacSHA384, EncryptUtils.encryptHmacSHA384ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacSHA384), EncryptUtils.encryptHmacSHA384("blankj".getBytes(), blankjHmackey.getBytes()) ); } @Test public void encryptHmacSHA512() { assertEquals( blankjHmacSHA512, EncryptUtils.encryptHmacSHA512ToString("blankj", blankjHmackey) ); assertEquals( blankjHmacSHA512, EncryptUtils.encryptHmacSHA512ToString("blankj".getBytes(), blankjHmackey.getBytes()) ); assertArrayEquals( UtilsBridge.hexString2Bytes(blankjHmacSHA512), EncryptUtils.encryptHmacSHA512("blankj".getBytes(), blankjHmackey.getBytes()) ); } private String dataDES = "0008DB3345AB0223"; private String keyDES = "6801020304050607"; private String resDES = "1F7962581118F360"; private byte[] bytesDataDES = UtilsBridge.hexString2Bytes(dataDES); private byte[] bytesKeyDES = UtilsBridge.hexString2Bytes(keyDES); private byte[] bytesResDES = UtilsBridge.hexString2Bytes(resDES); @Test public void encryptDES() { assertArrayEquals( bytesResDES, EncryptUtils.encryptDES(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null) ); assertEquals( resDES, EncryptUtils.encryptDES2HexString(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null) ); assertArrayEquals( UtilsBridge.base64Encode(bytesResDES), EncryptUtils.encryptDES2Base64(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null) ); } @Test public void decryptDES() { assertArrayEquals( bytesDataDES, EncryptUtils.decryptDES(bytesResDES, bytesKeyDES, "DES/ECB/NoPadding", null) ); assertArrayEquals( bytesDataDES, EncryptUtils.decryptHexStringDES(resDES, bytesKeyDES, "DES/ECB/NoPadding", null) ); assertArrayEquals( bytesDataDES, EncryptUtils.decryptBase64DES(UtilsBridge.base64Encode(bytesResDES), bytesKeyDES, "DES/ECB/NoPadding", null) ); } private String data3DES = "1111111111111111"; private String key3DES = "111111111111111111111111111111111111111111111111"; private String res3DES = "F40379AB9E0EC533"; private byte[] bytesDataDES3 = UtilsBridge.hexString2Bytes(data3DES); private byte[] bytesKeyDES3 = UtilsBridge.hexString2Bytes(key3DES); private byte[] bytesResDES3 = UtilsBridge.hexString2Bytes(res3DES); @Test public void encrypt3DES() { assertArrayEquals( bytesResDES3, EncryptUtils.encrypt3DES(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null) ); assertEquals( res3DES, EncryptUtils.encrypt3DES2HexString(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null) ); assertArrayEquals( UtilsBridge.base64Encode(bytesResDES3), EncryptUtils.encrypt3DES2Base64(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null) ); } @Test public void decrypt3DES() { assertArrayEquals( bytesDataDES3, EncryptUtils.decrypt3DES(bytesResDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null) ); assertArrayEquals( bytesDataDES3, EncryptUtils.decryptHexString3DES(res3DES, bytesKeyDES3, "DESede/ECB/NoPadding", null) ); assertArrayEquals( bytesDataDES3, EncryptUtils.decryptBase64_3DES(UtilsBridge.base64Encode(bytesResDES3), bytesKeyDES3, "DESede/ECB/NoPadding", null) ); } private String dataAES = "111111111111111111111111111111111"; private String keyAES = "11111111111111111111111111111111"; private String resAES = your_sha256_hash; private byte[] bytesDataAES = UtilsBridge.hexString2Bytes(dataAES); private byte[] bytesKeyAES = UtilsBridge.hexString2Bytes(keyAES); private byte[] bytesResAES = UtilsBridge.hexString2Bytes(resAES); @Test public void encryptAES() { assertArrayEquals( bytesResAES, EncryptUtils.encryptAES(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); assertEquals( resAES, EncryptUtils.encryptAES2HexString(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); assertArrayEquals( UtilsBridge.base64Encode(bytesResAES), EncryptUtils.encryptAES2Base64(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); } @Test public void decryptAES() { assertArrayEquals( bytesDataAES, EncryptUtils.decryptAES(bytesResAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); assertArrayEquals( bytesDataAES, EncryptUtils.decryptHexStringAES(resAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); assertArrayEquals(bytesDataAES, EncryptUtils.decryptBase64AES(UtilsBridge.base64Encode(bytesResAES), bytesKeyAES, "AES/ECB/PKCS5Padding", null) ); } @Test public void encryptDecryptRSA() throws Exception { int keySize = 1024; Pair<String, String> publicPrivateKey = genKeyPair(keySize); String publicKey = publicPrivateKey.first; String privateKey = publicPrivateKey.second; String dataRSA = your_sha256_hashyour_sha256_hash; System.out.println("publicKeyBase64:" + publicKey); System.out.println("privateKeyBase64:" + privateKey); System.out.println(EncryptUtils.encryptRSA2HexString( dataRSA.getBytes(), UtilsBridge.base64Decode(publicKey.getBytes()), keySize, "RSA/None/PKCS1Padding" )); assertArrayEquals(EncryptUtils.decryptRSA( EncryptUtils.encryptRSA( dataRSA.getBytes(), UtilsBridge.base64Decode(publicKey.getBytes()), keySize, "RSA/None/PKCS1Padding" ), UtilsBridge.base64Decode(privateKey.getBytes()), keySize, "RSA/None/PKCS1Padding" ), dataRSA.getBytes()); } private String dataRc4 = "111111111111111111111"; private String keyRc4 = "111111111111"; @Test public void rc4() throws Exception { System.out.println(new String(EncryptUtils.rc4(EncryptUtils.rc4(dataRc4.getBytes(), keyRc4.getBytes()), keyRc4.getBytes()))); } private Pair<String, String> genKeyPair(int size) throws NoSuchAlgorithmException { if (size == 1024) { return Pair.create( "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYHGvdORdwsK5i+s9rKaMPL1O5eDK2XwNHRUWaxmGB/cxLxeinJrrqdANyour_sha512_hashPcb5XVEvpNKL0HaWjN8pu/Dzf8gZwIDAQAB", your_sha256_hashyour_sha256_hashWdYif8hTSmcglj0Ok9NVzvH7XMVvxRSrU3QEGj82lQbmiXG5BQu4AAdk6Dbymc/89xvldUS+k0ovQdpaM3ym78PN/yBnAgMBAAECgYAFdXyour_sha512_hash/ezPq9pmRPriHfWQQ3/J3ASf1O9F9CkYbq/s/qqkXEFcl8PdYQV0xU/kS4jZPP+60Lv3sPkLg2DpkhM+AQJBANTl+/your_sha256_hashhev9W7qFayjci0ztcCQQC25/kkFbeMEWT6/kyV8wcPIog1mKy8RVB9+your_sha256_hashMwaAeSn6your_sha512_hashyxQ81fdKMYfUCfiPBPiRbSv5imf/Eyl8oOGdWrLW1d5HaxVttZgHHe60NcoRce0la3oSRAkAe8OqLsm9ryXNvBtZxSG+1JUvePVxpRSlJdZIAUKxN6XQE0S9aEe/IkNDBgVeiUEtop76R2NkkGtGTwzbzl0gm" ); } else if (size == 2048) { return Pair.create( "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjLLeJZIO7dfQKb6tHE+TlhvD1m3UdTefKvl4uNQboDXy2ztgPcksjLDXxsT+znxMBh4RpXxfVPgnrcSLewGVhTb3uXh9sWo6tvvshNaMKBTebaZePhE7grq+LHH3NILscVssK24rDSvIquZ4nUbDipF/Iscge4LwnypcCuunyour_sha512_hash+your_sha256_hashjlRftVWPj0OQXE7vRUsrrawIDAQAB", your_sha256_hashvq0cT5OWG8PWbdR1N58q+Xi41BugNfLbO2A9ySyMsNfGxP7OfEwGHhGlfF9U+CetxIt7AZWFNve5eH2xajq2++yE1owoFN5tpl4+your_sha512_hash+BmUCW+4Pq1PvpS6jmQPxvfrJg0Asj5lK06PbzfCUvw+your_sha256_hashkO7Xw5ry/25KOVF+1VY+your_sha256_hashVedyx+KAnngqVaZzmEmtto5ohY6OUysGqS8q91X9aMfm/T7zs7FnFjFqZ9Rq3lXRY3YezbQWqJuhHGBMfp2R1NGV1+your_sha256_hashyour_sha256_hash48KYErb2ktowngAQKBgQDL9FEumMMagPy4+EjR1puFHNvADlAi8tIUNt1W5zKKnd+T6gYGn8nqiiy5pvwLLUp8JISmq50tMC3cgAPw+G4kIe5zoBO2EU9X6aPhMd/your_sha256_hashE3wKBgQCwmkL6rJDrNo1GNUsjw+WIsXkuS3PYJahbg/your_sha256_hashYWZC5TvEA839q39Uakyour_sha512_hashCpHuUOmUqXpLRkZljiSVT+PGar1J8AZhfxaVxfSZzeoUxCxzm4UxIEKK9DFTfG7gKHKrj0LWfpM5siB0A/nlzBflHIAiLCF+s8/lx+mGMB5dBVnH5HwaTsXCHFB66pwgAa+your_sha256_hashlNC3EhXx99Of+gwH9OIFxljeRxhXuTgFfwcXT+AceTdplExrBuvr/qJbDK7hNsu/oDBBCjlyu/BQQc4CZEtCOJZjJTNGF5avWjrh/your_sha256_hash7XUww6bRpL2fEAqBIcDVgsS565ihxDSbUjgQgg/Ckh2+your_sha512_hash+sE=" ); } SecureRandom secureRandom = new SecureRandom(); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(size, secureRandom); KeyPair keyPair = keyPairGenerator.generateKeyPair(); Key publicKey = keyPair.getPublic(); Key privateKey = keyPair.getPrivate(); byte[] publicKeyBytes = publicKey.getEncoded(); byte[] privateKeyBytes = privateKey.getEncoded(); String publicKeyBase64 = EncodeUtils.base64Encode2String(publicKeyBytes); String privateKeyBase64 = EncodeUtils.base64Encode2String(privateKeyBytes); return Pair.create(publicKeyBase64, privateKeyBase64); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/EncryptUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
4,787
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/12 * desc : test ArrayUtils * </pre> */ public class ArrayUtilsTest extends BaseTest { @Test public void newArray() { // System.out.println(ArrayUtils.toString(ArrayUtils.newArray(null))); System.out.println(ArrayUtils.toString(ArrayUtils.newArray((String) null))); System.out.println(ArrayUtils.toString(ArrayUtils.newArray(0, 1, 2, 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newLongArray(0, 1, 2, 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newIntArray(0, 1, 2, 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newShortArray((short) 0, (short) 1, (short) 2, (short) 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newCharArray('0', '1', '2', '3'))); System.out.println(ArrayUtils.toString(ArrayUtils.newByteArray((byte) 0, (byte) 1, (byte) 2, (byte) 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newDoubleArray(0, 1, 2, 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newFloatArray(0, 1, 2, 3))); System.out.println(ArrayUtils.toString(ArrayUtils.newBooleanArray(false, true, false, true))); } @Test public void isEmpty() { Object nullArr = null; Object emptyArr = new int[]{}; Assert.assertTrue(ArrayUtils.isEmpty(nullArr)); Assert.assertTrue(ArrayUtils.isEmpty(emptyArr)); Assert.assertFalse(ArrayUtils.isEmpty(new int[]{1})); } @Test public void getLength() { Object nullArr = null; Object emptyArr = new int[]{}; Assert.assertEquals(0, ArrayUtils.getLength(nullArr)); Assert.assertEquals(0, ArrayUtils.getLength(emptyArr)); Assert.assertEquals(1, ArrayUtils.getLength(new int[]{1})); } @Test public void isSameLength() { Object emptyArr1 = new int[]{}; Assert.assertTrue(ArrayUtils.isSameLength(null, emptyArr1)); Assert.assertTrue(ArrayUtils.isSameLength(new boolean[0], emptyArr1)); } @Test public void get() { Object emptyArr1 = new int[]{0, 1, 2}; Assert.assertEquals(0, ArrayUtils.get(emptyArr1, 0)); Assert.assertEquals(1, ArrayUtils.get(emptyArr1, 1)); ArrayUtils.get(emptyArr1, 4); } @Test public void getOrDefault() { Object array = new int[]{0, 1, 2}; Assert.assertEquals(0, ArrayUtils.get(array, 0)); Assert.assertEquals(1, ArrayUtils.get(array, 1)); Assert.assertEquals(-1, ArrayUtils.get(array, 4, -1)); Assert.assertNull(ArrayUtils.get(array, 4)); } @Test public void set() { int[] array = new int[]{0, -1, 2}; ArrayUtils.set(array, 1, 1); Assert.assertArrayEquals(new int[]{0, 1, 2}, array); } @Test public void equals() { Assert.assertTrue(ArrayUtils.equals(null, (Object[]) null)); } @Test public void reverse() { int[] array = new int[]{0, 1, 2, 3}; ArrayUtils.reverse(array); Assert.assertArrayEquals(new int[]{3, 2, 1, 0}, array); } @Test public void copy() { int[] array = new int[]{0, 1, 2, 3}; int[] copy = ArrayUtils.copy(array); Assert.assertArrayEquals(array, copy); Assert.assertNotSame(array, copy); } @Test public void subArray() { int[] array = new int[]{0, 1, 2, 3}; int[] subArray = ArrayUtils.subArray(array, 1, 3); Assert.assertArrayEquals(new int[]{1, 2}, subArray); } @Test public void add() { int[] array = new int[]{0, 1, 2, 3}; int[] addLastOne = ArrayUtils.add(array, 4); int[] addFirstOne = ArrayUtils.add(array, 0, -1); int[] addArr = ArrayUtils.add(array, new int[]{4, 5}); int[] addFirstArr = ArrayUtils.add(array, 0, new int[]{-2, -1}); int[] addMidArr = ArrayUtils.add(array, 2, new int[]{1, 2}); Assert.assertArrayEquals(new int[]{0, 1, 2, 3, 4}, addLastOne); Assert.assertArrayEquals(new int[]{-1, 0, 1, 2, 3}, addFirstOne); Assert.assertArrayEquals(new int[]{0, 1, 2, 3, 4, 5}, addArr); Assert.assertArrayEquals(new int[]{-2, -1, 0, 1, 2, 3}, addFirstArr); Assert.assertArrayEquals(new int[]{0, 1, 1, 2, 2, 3}, addMidArr); } @Test public void remove() { int[] array = new int[]{0, 1, 2, 3}; int[] remove = ArrayUtils.remove(array, 0); Assert.assertArrayEquals(new int[]{1, 2, 3}, remove); } @Test public void removeElement() { int[] array = new int[]{0, 1, 2, 3}; int[] remove = ArrayUtils.removeElement(array, 0); Assert.assertArrayEquals(new int[]{1, 2, 3}, remove); } @Test public void indexOf() { int[] array = new int[]{0, 1, 2, 3}; int i = ArrayUtils.indexOf(array, 0); int i1 = ArrayUtils.indexOf(array, -1); int i2 = ArrayUtils.indexOf(array, 0, 1); Assert.assertEquals(0, i); Assert.assertEquals(-1, i1); Assert.assertEquals(-1, i2); } @Test public void lastIndexOf() { int[] array = new int[]{0, 1, 2, 3, 0}; int i = ArrayUtils.lastIndexOf(array, 0); int i1 = ArrayUtils.lastIndexOf(array, -1); int i2 = ArrayUtils.lastIndexOf(array, 0, 1); Assert.assertEquals(4, i); Assert.assertEquals(-1, i1); Assert.assertEquals(0, i2); } @Test public void contains() { int[] array = new int[]{0, 1, 2, 3}; Assert.assertTrue(ArrayUtils.contains(array, 0)); Assert.assertFalse(ArrayUtils.contains(array, 4)); } @Test public void toPrimitive() { int[] primitiveArray = new int[]{0, 1, 2, 3}; Integer[] array = new Integer[]{0, 1, 2, 3}; Assert.assertArrayEquals(primitiveArray, ArrayUtils.toPrimitive(array)); int[] primitiveArray1 = new int[]{0, 1, 2, 3, 0}; Integer[] array1 = new Integer[]{0, 1, 2, 3, null}; Assert.assertArrayEquals(primitiveArray1, ArrayUtils.toPrimitive(array1, 0)); } @Test public void toObject() { int[] primitiveArray = new int[]{0, 1, 2, 3}; Integer[] array = new Integer[]{0, 1, 2, 3}; Assert.assertArrayEquals(array, ArrayUtils.toObject(primitiveArray)); } @Test public void asList() { // Assert.assertEquals(0, ArrayUtils.asList(null).size()); List<Integer> list = ArrayUtils.asList(1, 2, 3, 4); System.out.println(list); } @Test public void sort() { int[] ints = {2, 1, 0, 1, 2, 3}; ArrayUtils.sort(ints); System.out.println(ArrayUtils.toString(ints)); } @Test public void forAllDo() { ArrayUtils.forAllDo(null, null); int[] array = new int[]{0, 1, 2, 3}; ArrayUtils.forAllDo(array, new ArrayUtils.Closure<Integer>() { @Override public void execute(int index, Integer item) { System.out.println(index + ", " + item); } }); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ArrayUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,999
```java package com.blankj.utilcode.util; import org.junit.Test; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/21 * desc : test UiMessageUtils * </pre> */ public class UiMessageUtilsTest extends BaseTest { @Test public void singleMessageTest() { UiMessageUtils.UiMessageCallback listener = new UiMessageUtils.UiMessageCallback() { @Override public void handleMessage(@NonNull UiMessageUtils.UiMessage localMessage) { System.out.println("receive -> " + localMessage.getId() + ": " + localMessage.getObject()); } }; UiMessageUtils.getInstance().addListener(listener); UiMessageUtils.getInstance().send(1, "msg"); UiMessageUtils.getInstance().removeListener(listener); UiMessageUtils.getInstance().send(1, "msg"); } @Test public void multiMessageTest() { UiMessageUtils.UiMessageCallback listener = new UiMessageUtils.UiMessageCallback() { @Override public void handleMessage(@NonNull UiMessageUtils.UiMessage localMessage) { switch (localMessage.getId()) { case 1: System.out.println("receive -> 1: " + localMessage.getObject()); break; case 2: System.out.println("receive -> 2: " + localMessage.getObject()); break; case 4: System.out.println("receive -> 4: " + localMessage.getObject()); break; } } }; UiMessageUtils.getInstance().addListener(listener); UiMessageUtils.getInstance().send(1, "msg1"); UiMessageUtils.getInstance().send(2, "msg2"); UiMessageUtils.getInstance().send(4, "msg4"); UiMessageUtils.getInstance().removeListener(listener); UiMessageUtils.getInstance().send(1, "msg1"); UiMessageUtils.getInstance().send(2, "msg2"); UiMessageUtils.getInstance().send(4, "msg4"); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/UiMessageUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
440
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/04/08 * desc : test CloneUtils * </pre> */ public class CloneUtilsTest extends BaseTest { @Test public void deepClone() { Result<Person> result = new Result<>(new Person("Blankj")); Result<Person> cloneResult = CloneUtils.deepClone(result, GsonUtils.getType(Result.class, Person.class)); System.out.println(result); System.out.println(cloneResult); Assert.assertNotEquals(result, cloneResult); } static class Result<T> { int code; String message; T data; Result(T data) { this.code = 200; this.message = "success"; this.data = data; } @Override public String toString() { return "{\"code\":" + primitive2String(code) + ",\"message\":" + primitive2String(message) + ",\"data\":" + primitive2String(data) + "}"; } } static class Person { String name; int gender; String address; Person(String name) { this.name = name; } @Override public String toString() { return "{\"name\":" + primitive2String(name) + ",\"gender\":" + primitive2String(gender) + ",\"address\":" + primitive2String(address) + "}"; } } private static String primitive2String(final Object obj) { if (obj == null) return "null"; if (obj instanceof CharSequence) return "\"" + obj.toString() + "\""; return obj.toString(); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CloneUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
385
```java package com.blankj.utilcode.util; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.blankj.utilcode.util.TestConfig.PATH_TEMP; import static com.blankj.utilcode.util.TestConfig.PATH_ZIP; import static junit.framework.TestCase.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/09/10 * desc : test ZipUtils * </pre> */ public class ZipUtilsTest extends BaseTest { private String zipFile = PATH_TEMP + "zipFile.zip"; private String zipFiles = PATH_TEMP + "zipFiles.zip"; @Before public void setUp() throws Exception { FileUtils.createOrExistsDir(PATH_TEMP); assertTrue(ZipUtils.zipFile(PATH_ZIP, zipFile, "zip")); } @Test public void zipFiles() throws Exception { List<String> files = new ArrayList<>(); files.add(PATH_ZIP + "test.txt"); files.add(PATH_ZIP); files.add(PATH_ZIP + "testDir"); assertTrue(ZipUtils.zipFiles(files, zipFiles)); } @Test public void unzipFile() throws Exception { System.out.println(ZipUtils.unzipFile(zipFile, PATH_TEMP)); } @Test public void unzipFileByKeyword() throws Exception { System.out.println((ZipUtils.unzipFileByKeyword(zipFile, PATH_TEMP, null)).toString()); } @Test public void getFilesPath() throws Exception { System.out.println(ZipUtils.getFilesPath(zipFile)); } @Test public void getComments() throws Exception { System.out.println(ZipUtils.getComments(zipFile)); } @After public void tearDown() { FileUtils.deleteAllInDir(PATH_TEMP); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ZipUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
409
```java package com.blankj.utilcode.util; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/09/26 * desc : test LogUtils * </pre> */ public class LogUtilsTest extends BaseTest { private static final String JSON = "\r\n{\"tools\": [{ \"name\":\"css format\" , \"site\":\"path_to_url" },{ \"name\":\"JSON format\" , \"site\":\"path_to_url" },{ \"name\":\"pwd check\" , \"site\":\"path_to_url" }]}"; private static final String XML = "<books><book><author>Jack Herrington</author><title>PHP Hacks</title><publisher>O'Reilly</publisher></book><book><author>Jack Herrington</author><title>Podcasting Hacks</title><publisher>O'Reilly</publisher></book></books>"; private static final int[] ONE_D_ARRAY = new int[]{1, 2, 3}; private static final int[][] TWO_D_ARRAY = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; private static final ArrayList<String> LIST = new ArrayList<>(); private static final Map<String, Object> MAP = new HashMap<>(); @Test public void testV() { LogUtils.v(); LogUtils.v(""); LogUtils.v((Object) null); LogUtils.v("hello"); LogUtils.v("hello\nworld"); LogUtils.v("hello", "world"); } @Test public void testVTag() { LogUtils.vTag(""); LogUtils.vTag("", ""); LogUtils.vTag("TAG", (Object) null); LogUtils.vTag("TAG", "hello"); LogUtils.vTag("TAG", "hello\nworld"); LogUtils.vTag("TAG", "hello", "world"); } @Test public void testD() { LogUtils.d(); LogUtils.d(""); LogUtils.d((Object) null); LogUtils.d("hello"); LogUtils.d("hello\nworld"); LogUtils.d("hello", "world"); } @Test public void testDTag() { LogUtils.dTag(""); LogUtils.dTag("", ""); LogUtils.dTag("TAG", (Object) null); LogUtils.dTag("TAG", "hello"); LogUtils.dTag("TAG", "hello\nworld"); LogUtils.dTag("TAG", "hello", "world"); } @Test public void testI() { LogUtils.i(); LogUtils.i(""); LogUtils.i((Object) null); LogUtils.i("hello"); LogUtils.i("hello\nworld"); LogUtils.i("hello", "world"); } @Test public void testITag() { LogUtils.iTag(""); LogUtils.iTag("", ""); LogUtils.iTag("TAG", (Object) null); LogUtils.iTag("TAG", "hello"); LogUtils.iTag("TAG", "hello\nworld"); LogUtils.iTag("TAG", "hello", "world"); } @Test public void testW() { LogUtils.w(); LogUtils.w(""); LogUtils.w((Object) null); LogUtils.w("hello"); LogUtils.w("hello\nworld"); LogUtils.w("hello", "world"); } @Test public void testWTag() { LogUtils.wTag(""); LogUtils.wTag("", ""); LogUtils.wTag("TAG", (Object) null); LogUtils.wTag("TAG", "hello"); LogUtils.wTag("TAG", "hello\nworld"); LogUtils.wTag("TAG", "hello", "world"); } @Test public void testE() { LogUtils.e(); LogUtils.e(""); LogUtils.e((Object) null); LogUtils.e("hello"); LogUtils.e("hello\nworld"); LogUtils.e("hello", "world"); } @Test public void testETag() { LogUtils.eTag(""); LogUtils.eTag("", ""); LogUtils.eTag("TAG", (Object) null); LogUtils.eTag("TAG", "hello"); LogUtils.eTag("TAG", "hello\nworld"); LogUtils.eTag("TAG", "hello", "world"); } @Test public void testA() { LogUtils.a(); LogUtils.a(""); LogUtils.a((Object) null); LogUtils.a("hello"); LogUtils.a("hello\nworld"); LogUtils.a("hello", "world"); } @Test public void testATag() { LogUtils.aTag(""); LogUtils.aTag("", ""); LogUtils.aTag("TAG", (Object) null); LogUtils.aTag("TAG", "hello"); LogUtils.aTag("TAG", "hello\nworld"); LogUtils.aTag("TAG", "hello", "world"); } @Test public void testJson() { LogUtils.json(JSON); LogUtils.json(new Person("Blankj")); } @Test public void testXml() { LogUtils.xml(XML); } @Test public void testObject() { LIST.add("hello"); LIST.add("log"); LIST.add("utils"); MAP.put("name", "AndroidUtilCode"); MAP.put("class", "LogUtils"); LogUtils.d((Object) ONE_D_ARRAY); LogUtils.d((Object) TWO_D_ARRAY); LogUtils.d(LIST); LogUtils.d(MAP); } static class Person { String name; int gender; String address; public Person(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Person)) return false; Person p = (Person) obj; return equals(name, p.name) && p.gender == gender && equals(address, p.address); } private static boolean equals(final Object o1, final Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } @Override public String toString() { return "{\"name\":" + primitive2String(name) + ",\"gender\":" + primitive2String(gender) + ",\"address\":" + primitive2String(address) + "}"; } } private static String primitive2String(final Object obj) { if (obj == null) return "null"; if (obj instanceof CharSequence) return "\"" + obj.toString() + "\""; return obj.toString(); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/LogUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,498
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/12 * desc : test CollectionUtils * </pre> */ public class CollectionUtilsTest extends BaseTest { @Test public void union() { ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02"); ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12"); Collection unionNullNull = CollectionUtils.union(null, null); Collection unionL0Null = CollectionUtils.union(l0, null); Collection unionNullL1 = CollectionUtils.union(null, l1); Collection unionL0L1 = CollectionUtils.union(l0, l1); System.out.println(unionNullNull); System.out.println(unionL0Null); System.out.println(unionNullL1); System.out.println(unionL0L1); Assert.assertNotSame(l0, unionL0Null); Assert.assertNotSame(l1, unionNullL1); } @Test public void intersection() { ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02"); ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12"); Collection intersectionNullNull = CollectionUtils.intersection(null, null); Collection intersectionL0Null = CollectionUtils.intersection(l0, null); Collection intersectionNullL1 = CollectionUtils.intersection(null, l1); Collection intersectionL0L1 = CollectionUtils.intersection(l0, l1); System.out.println(intersectionNullNull); System.out.println(intersectionL0Null); System.out.println(intersectionNullL1); System.out.println(intersectionL0L1); } @Test public void disjunction() { ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02"); ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12"); Collection disjunctionNullNull = CollectionUtils.disjunction(null, null); Collection disjunctionL0Null = CollectionUtils.disjunction(l0, null); Collection disjunctionNullL1 = CollectionUtils.disjunction(null, l1); Collection disjunctionL0L1 = CollectionUtils.disjunction(l0, l1); System.out.println(disjunctionNullNull); System.out.println(disjunctionL0Null); System.out.println(disjunctionNullL1); System.out.println(disjunctionL0L1); Assert.assertNotSame(l0, disjunctionL0Null); Assert.assertNotSame(l1, disjunctionNullL1); } @Test public void subtract() { ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02"); ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12"); Collection subtractNullNull = CollectionUtils.subtract(null, null); Collection subtractL0Null = CollectionUtils.subtract(l0, null); Collection subtractNullL1 = CollectionUtils.subtract(null, l1); Collection subtractL0L1 = CollectionUtils.subtract(l0, l1); System.out.println(subtractNullNull); System.out.println(subtractL0Null); System.out.println(subtractNullL1); System.out.println(subtractL0L1); Assert.assertNotSame(l0, subtractL0Null); } @Test public void containsAny() { ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02"); ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12"); Assert.assertFalse(CollectionUtils.containsAny(null, null)); Assert.assertFalse(CollectionUtils.containsAny(l0, null)); Assert.assertFalse(CollectionUtils.containsAny(null, l1)); Assert.assertTrue(CollectionUtils.containsAny(l0, l1)); } @Test public void getCardinalityMap() { System.out.println(CollectionUtils.getCardinalityMap(null)); ArrayList<String> l0 = CollectionUtils.newArrayList("0", "0", "1", "1", "2"); System.out.println(CollectionUtils.getCardinalityMap(l0)); } @Test public void isSubCollection() { ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2"); ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2"); Assert.assertFalse(CollectionUtils.isSubCollection(null, null)); Assert.assertFalse(CollectionUtils.isSubCollection(l0, null)); Assert.assertFalse(CollectionUtils.isSubCollection(null, l0)); Assert.assertTrue(CollectionUtils.isSubCollection(l0, l1)); Assert.assertTrue(CollectionUtils.isSubCollection(l0, l0)); Assert.assertFalse(CollectionUtils.isSubCollection(l1, l0)); } @Test public void isProperSubCollection() { ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2"); ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2"); Assert.assertFalse(CollectionUtils.isProperSubCollection(null, null)); Assert.assertFalse(CollectionUtils.isProperSubCollection(l0, null)); Assert.assertFalse(CollectionUtils.isProperSubCollection(null, l0)); Assert.assertTrue(CollectionUtils.isProperSubCollection(l0, l1)); Assert.assertFalse(CollectionUtils.isProperSubCollection(l0, l0)); Assert.assertFalse(CollectionUtils.isProperSubCollection(l1, l0)); } @Test public void isEqualCollection() { ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2"); ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2"); Assert.assertFalse(CollectionUtils.isEqualCollection(null, null)); Assert.assertFalse(CollectionUtils.isEqualCollection(l0, null)); Assert.assertFalse(CollectionUtils.isEqualCollection(null, l0)); Assert.assertTrue(CollectionUtils.isEqualCollection(l0, l0)); Assert.assertFalse(CollectionUtils.isEqualCollection(l0, l1)); } @Test public void cardinality() { ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2"); Assert.assertEquals(0, CollectionUtils.cardinality(null, null)); Assert.assertEquals(0, CollectionUtils.cardinality(null, list)); list.add(null); Assert.assertEquals(1, CollectionUtils.cardinality(null, list)); Assert.assertEquals(2, CollectionUtils.cardinality("1", list)); } @Test public void find() { ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2"); Assert.assertNull(CollectionUtils.find(null, null)); Assert.assertNull(CollectionUtils.find(list, null)); Assert.assertNull(CollectionUtils.find(null, new CollectionUtils.Predicate<String>() { @Override public boolean evaluate(String item) { return true; } })); Assert.assertEquals("1", CollectionUtils.find(list, new CollectionUtils.Predicate<String>() { @Override public boolean evaluate(String item) { return "1".equals(item); } })); } @Test public void forAllDo() { ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2"); CollectionUtils.forAllDo(null, null); CollectionUtils.forAllDo(list, null); CollectionUtils.forAllDo(null, new CollectionUtils.Closure<Object>() { @Override public void execute(int index, Object item) { System.out.println(index + ": " + index); } }); CollectionUtils.forAllDo(list, new CollectionUtils.Closure<String>() { @Override public void execute(int index, String item) { System.out.println(index + ": " + index); } }); } @Test public void filter() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); CollectionUtils.filter(l0, null); Assert.assertNull(l0); CollectionUtils.filter(l0, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } }); Assert.assertNull(l0); CollectionUtils.filter(l1, null); Assert.assertEquals(l1, l1); CollectionUtils.filter(l1, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } }); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(2, 3), l1)); } @Test public void select() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.select(null, null).size()); Assert.assertEquals(0, CollectionUtils.select(list, null).size()); Assert.assertEquals(0, CollectionUtils.select(null, new CollectionUtils.Predicate<Object>() { @Override public boolean evaluate(Object item) { return true; } }).size()); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(2, 3), CollectionUtils.select(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } }))); Collection<Integer> list1 = CollectionUtils.select(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return true; } }); Assert.assertTrue(CollectionUtils.isEqualCollection(list, list1)); Assert.assertNotSame(list, list1); } @Test public void selectRejected() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.selectRejected(null, null).size()); Assert.assertEquals(0, CollectionUtils.selectRejected(list, null).size()); Assert.assertEquals(0, CollectionUtils.selectRejected(null, new CollectionUtils.Predicate<Object>() { @Override public boolean evaluate(Object item) { return true; } }).size()); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(0, 1), CollectionUtils.selectRejected(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } }))); Collection<Integer> list1 = CollectionUtils.selectRejected(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return false; } }); Assert.assertTrue(CollectionUtils.isEqualCollection(list, list1)); Assert.assertNotSame(list, list1); } @Test public void transform() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); CollectionUtils.transform(l0, null); Assert.assertNull(l0); CollectionUtils.transform(l0, new CollectionUtils.Transformer<Integer, Object>() { @Override public Object transform(Integer input) { return "int: " + input; } }); Assert.assertNull(l0); CollectionUtils.transform(l1, null); Assert.assertEquals(l1, l1); CollectionUtils.transform(l1, new CollectionUtils.Transformer<Integer, String>() { @Override public String transform(Integer input) { return String.valueOf(input); } }); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList("0", "1", "2", "3"), l1)); } @Test public void collect() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(null, null))); Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(list, null))); Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(null, new CollectionUtils.Transformer() { @Override public Object transform(Object input) { return null; } }))); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList("0", "1", "2", "3"), CollectionUtils.collect(list, new CollectionUtils.Transformer<Integer, String>() { @Override public String transform(Integer input) { return String.valueOf(input); } }))); } @Test public void countMatches() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.countMatches(null, null)); Assert.assertEquals(0, CollectionUtils.countMatches(list, null)); Assert.assertEquals(0, CollectionUtils.countMatches(null, new CollectionUtils.Predicate<Object>() { @Override public boolean evaluate(Object item) { return false; } })); Assert.assertEquals(2, CollectionUtils.countMatches(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } })); } @Test public void exists() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertFalse(CollectionUtils.exists(null, null)); Assert.assertFalse(CollectionUtils.exists(list, null)); Assert.assertFalse(CollectionUtils.exists(null, new CollectionUtils.Predicate<Object>() { @Override public boolean evaluate(Object item) { return false; } })); Assert.assertTrue(CollectionUtils.exists(list, new CollectionUtils.Predicate<Integer>() { @Override public boolean evaluate(Integer item) { return item > 1; } })); } @Test public void addIgnoreNull() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertFalse(CollectionUtils.addIgnoreNull(null, null)); Assert.assertFalse(CollectionUtils.addIgnoreNull(null, 1)); CollectionUtils.addIgnoreNull(list, null); Assert.assertEquals(CollectionUtils.newArrayList(0, 1, 2, 3), list); CollectionUtils.addIgnoreNull(list, 4); Assert.assertEquals(CollectionUtils.newArrayList(0, 1, 2, 3, 4), list); } @Test public void addAll() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); CollectionUtils.addAll(l0, (Iterator<Integer>) null); Assert.assertNull(l0); CollectionUtils.addAll(l0, (Enumeration<Integer>) null); Assert.assertNull(l0); CollectionUtils.addAll(l0, (Integer[]) null); Assert.assertNull(l0); CollectionUtils.addAll(l1, (Iterator<Integer>) null); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1)); CollectionUtils.addAll(l1, (Enumeration<Integer>) null); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1)); CollectionUtils.addAll(l1, (Integer[]) null); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1)); CollectionUtils.addAll(l1, CollectionUtils.newArrayList(4, 5).iterator()); Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3, 4, 5), l1)); } @Test public void get() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertNull(CollectionUtils.get(l0, 0)); Assert.assertEquals(0, CollectionUtils.get(l1, 0)); } @Test public void size() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.size(l0)); Assert.assertEquals(4, CollectionUtils.size(l1)); } @Test public void sizeIsEmpty() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertTrue(CollectionUtils.sizeIsEmpty(l0)); Assert.assertFalse(CollectionUtils.sizeIsEmpty(l1)); } @Test public void isEmpty() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertTrue(CollectionUtils.isEmpty(l0)); Assert.assertFalse(CollectionUtils.isEmpty(l1)); } @Test public void isNotEmpty() { ArrayList<Integer> l0 = null; ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertFalse(CollectionUtils.isNotEmpty(l0)); Assert.assertTrue(CollectionUtils.isNotEmpty(l1)); } @Test public void retainAll() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.retainAll(null, null).size()); Assert.assertEquals(0, CollectionUtils.retainAll(list, null).size()); Assert.assertEquals(0, CollectionUtils.retainAll(null, list).size()); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(0, 1, 2, 3), CollectionUtils.retainAll(list, list) )); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(0, 1), CollectionUtils.retainAll(list, CollectionUtils.newArrayList(0, 1, 6)) )); } @Test public void removeAll() { ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3); Assert.assertEquals(0, CollectionUtils.removeAll(null, null).size()); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(0, 1, 2, 3), CollectionUtils.removeAll(list, null) )); Assert.assertEquals(0, CollectionUtils.removeAll(null, list).size()); Assert.assertTrue(CollectionUtils.isEqualCollection( CollectionUtils.newArrayList(2, 3), CollectionUtils.removeAll(list, CollectionUtils.newArrayList(0, 1, 6)) )); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CollectionUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
3,975
```java package com.blankj.utilcode.util; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/06/13 * desc : test CacheMemoryUtils * </pre> */ public class CacheMemoryUtilsTest extends BaseTest { private CacheMemoryUtils mCacheMemoryUtils1 = CacheMemoryUtils.getInstance(); private CacheMemoryUtils mCacheMemoryUtils2 = CacheMemoryUtils.getInstance(3); @Before public void setUp() { for (int i = 0; i < 10; i++) { mCacheMemoryUtils1.put(String.valueOf(i), i); } for (int i = 0; i < 10; i++) { mCacheMemoryUtils2.put(String.valueOf(i), i); } } @Test public void get() { for (int i = 0; i < 10; i++) { assertEquals(i, mCacheMemoryUtils1.get(String.valueOf(i))); } for (int i = 0; i < 10; i++) { if (i < 7) { assertNull(mCacheMemoryUtils2.get(String.valueOf(i))); } else { assertEquals(i, mCacheMemoryUtils2.get(String.valueOf(i))); } } } @Test public void getExpired() throws Exception { mCacheMemoryUtils1.put("10", 10, 2 * CacheMemoryUtils.SEC); assertEquals(10, mCacheMemoryUtils1.get("10")); Thread.sleep(1500); assertEquals(10, mCacheMemoryUtils1.get("10")); Thread.sleep(1500); assertNull(mCacheMemoryUtils1.get("10")); } @Test public void getDefault() { assertNull(mCacheMemoryUtils1.get("10")); assertEquals("10", mCacheMemoryUtils1.get("10", "10")); } @Test public void getCacheCount() { assertEquals(10, mCacheMemoryUtils1.getCacheCount()); assertEquals(3, mCacheMemoryUtils2.getCacheCount()); } @Test public void remove() { assertEquals(0, mCacheMemoryUtils1.remove("0")); assertNull(mCacheMemoryUtils1.get("0")); assertNull(mCacheMemoryUtils1.remove("0")); } @Test public void clear() { mCacheMemoryUtils1.clear(); mCacheMemoryUtils2.clear(); for (int i = 0; i < 10; i++) { assertNull(mCacheMemoryUtils1.get(String.valueOf(i))); } for (int i = 0; i < 10; i++) { assertNull(mCacheMemoryUtils2.get(String.valueOf(i))); } assertEquals(0, mCacheMemoryUtils1.getCacheCount()); assertEquals(0, mCacheMemoryUtils2.getCacheCount()); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
646
```java package com.blankj.utilcode.util; /** * <pre> * author: Blankj * blog : path_to_url * time : 2017/09/10 * desc : config of test * </pre> */ public class TestConfig { static final String FILE_SEP = System.getProperty("file.separator"); static final String LINE_SEP = System.getProperty("line.separator"); static final String TEST_PATH; static { String projectPath = System.getProperty("user.dir"); if (!projectPath.contains("utilcode")) { projectPath += FILE_SEP + "utilcode"; } TEST_PATH = projectPath + FILE_SEP + "src" + FILE_SEP + "test" + FILE_SEP + "res" + FILE_SEP; } static final String PATH_TEMP = TEST_PATH + "temp" + FILE_SEP; static final String PATH_CACHE = TEST_PATH + "cache" + FILE_SEP; static final String PATH_ENCRYPT = TEST_PATH + "encrypt" + FILE_SEP; static final String PATH_FILE = TEST_PATH + "file" + FILE_SEP; static final String PATH_IMAGE = TEST_PATH + "image" + FILE_SEP; static final String PATH_ZIP = TEST_PATH + "zip" + FILE_SEP; } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/TestConfig.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
271
```java package com.blankj.utilcode.util; import com.blankj.utilcode.constant.RegexConstants; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/16 * desc : test RegexUtils * </pre> */ public class RegexUtilsTest extends BaseTest { @Test public void isMobileSimple() { assertTrue(RegexUtils.isMobileSimple("11111111111")); } @Test public void isMobileExact() { assertFalse(RegexUtils.isMobileExact("11111111111")); assertTrue(RegexUtils.isMobileExact("13888880000")); assertTrue(RegexUtils.isMobileExact("12088880000", CollectionUtils.newArrayList("120"))); } @Test public void isTel() { assertTrue(RegexUtils.isTel("033-88888888")); assertTrue(RegexUtils.isTel("033-7777777")); assertTrue(RegexUtils.isTel("0444-88888888")); assertTrue(RegexUtils.isTel("0444-7777777")); assertTrue(RegexUtils.isTel("033 88888888")); assertTrue(RegexUtils.isTel("033 7777777")); assertTrue(RegexUtils.isTel("0444 88888888")); assertTrue(RegexUtils.isTel("0444 7777777")); assertTrue(RegexUtils.isTel("03388888888")); assertTrue(RegexUtils.isTel("0337777777")); assertTrue(RegexUtils.isTel("044488888888")); assertTrue(RegexUtils.isTel("04447777777")); assertFalse(RegexUtils.isTel("133-88888888")); assertFalse(RegexUtils.isTel("033-666666")); assertFalse(RegexUtils.isTel("0444-999999999")); } @Test public void isIDCard18() { assertTrue(RegexUtils.isIDCard18("33698418400112523x")); assertTrue(RegexUtils.isIDCard18("336984184001125233")); assertFalse(RegexUtils.isIDCard18("336984184021125233")); } @Test public void isIDCard18Exact() { assertFalse(RegexUtils.isIDCard18Exact("33698418400112523x")); assertTrue(RegexUtils.isIDCard18Exact("336984184001125233")); assertFalse(RegexUtils.isIDCard18Exact("336984184021125233")); } @Test public void isEmail() { assertTrue(RegexUtils.isEmail("blankj@qq.com")); assertFalse(RegexUtils.isEmail("blankj@qq")); } @Test public void isURL() { assertTrue(RegexUtils.isURL("path_to_url")); assertFalse(RegexUtils.isURL("https:blank")); } @Test public void isZh() { assertTrue(RegexUtils.isZh("")); assertFalse(RegexUtils.isZh("wo")); } @Test public void isUsername() { assertTrue(RegexUtils.isUsername("233333")); assertFalse(RegexUtils.isUsername("")); assertFalse(RegexUtils.isUsername("233333_")); } @Test public void isDate() { assertTrue(RegexUtils.isDate("2016-08-16")); assertTrue(RegexUtils.isDate("2016-02-29")); assertFalse(RegexUtils.isDate("2015-02-29")); assertFalse(RegexUtils.isDate("2016-8-16")); } @Test public void isIP() { assertTrue(RegexUtils.isIP("255.255.255.0")); assertFalse(RegexUtils.isIP("256.255.255.0")); } @Test public void isMatch() { assertTrue(RegexUtils.isMatch("\\d?", "1")); assertFalse(RegexUtils.isMatch("\\d?", "a")); } @Test public void getMatches() { // System.out.println(RegexUtils.getMatches("b.*j", "blankj blankj")); // System.out.println(RegexUtils.getMatches("b.*?j", "blankj blankj")); } @Test public void getSplits() { System.out.println(Arrays.asList(RegexUtils.getSplits("1 2 3", " "))); } @Test public void getReplaceFirst() { System.out.println(RegexUtils.getReplaceFirst("1 2 3", " ", ", ")); } @Test public void getReplaceAll() { System.out.println(RegexUtils.getReplaceAll("1 2 3", " ", ", ")); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/RegexUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,024
```java package com.blankj.utilcode.util; import android.util.Pair; import org.junit.Assert; import org.junit.Test; import java.util.Comparator; import java.util.Map; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/14 * desc : test MapUtils * </pre> */ public class MapUtilsTest extends BaseTest { @Test public void newUnmodifiableMap() { System.out.println(MapUtils.newUnmodifiableMap( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") )); } @Test public void newHashMap() { System.out.println(MapUtils.newHashMap( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") )); } @Test public void newLinkedHashMap() { System.out.println(MapUtils.newLinkedHashMap( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") )); } @Test public void newTreeMap() { System.out.println(MapUtils.newTreeMap( new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }, Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") )); } @Test public void newHashTable() { System.out.println(MapUtils.newHashTable( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") )); } @Test public void isEmpty() { Assert.assertTrue(MapUtils.isEmpty(null)); Assert.assertTrue(MapUtils.isEmpty(MapUtils.newHashMap())); Assert.assertFalse(MapUtils.isEmpty(MapUtils.newHashMap(Pair.create(0, 0)))); } @Test public void isNotEmpty() { Assert.assertFalse(MapUtils.isNotEmpty(null)); Assert.assertFalse(MapUtils.isNotEmpty(MapUtils.newHashMap())); Assert.assertTrue(MapUtils.isNotEmpty(MapUtils.newHashMap(Pair.create(0, 0)))); } @Test public void size() { Assert.assertEquals(0, MapUtils.size(null)); Assert.assertEquals(0, MapUtils.size(MapUtils.newHashMap())); Assert.assertEquals(1, MapUtils.size(MapUtils.newHashMap(Pair.create(0, 0)))); } @Test public void forAllDo() { MapUtils.forAllDo( MapUtils.newHashMap( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") ), new MapUtils.Closure<Integer, String>() { @Override public void execute(Integer key, String value) { System.out.println(key + "=" + value); } }); } @Test public void transform() { Map<String, String> transform = MapUtils.transform( MapUtils.newHashMap( Pair.create(0, "0"), Pair.create(1, "1"), Pair.create(2, "2"), Pair.create(3, "3") ), new MapUtils.Transformer<Integer, String, String, String>() { @Override public Pair<String, String> transform(Integer integer, String s) { return Pair.create("StringKey" + integer, s); } } ); System.out.println(transform); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/MapUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
827
```java package com.blankj.utilcode.util; import org.junit.After; import org.junit.Test; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static com.blankj.utilcode.util.TestConfig.PATH_TEMP; /** * <pre> * author: Blankj * blog : path_to_url * time : 2017/05/24 * desc : test FileIOUtils * </pre> */ public class FileIOUtilsTest extends BaseTest { @Test public void writeFileFromIS() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.append(String.format("%5dFileIOUtilsTest\n", i)); } InputStream is = ConvertUtils.string2InputStream(sb.toString(), "UTF-8"); FileIOUtils.writeFileFromIS(PATH_TEMP + "writeFileFromIS.txt", is, new FileIOUtils.OnProgressUpdateListener() { @Override public void onProgressUpdate(double progress) { System.out.println(String.format("%.2f", progress)); } }); } @Test public void writeFileFromBytesByStream() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.append(String.format("%5dFileIOUtilsTest\n", i)); } byte[] bytes = sb.toString().getBytes(StandardCharsets.UTF_8); FileIOUtils.writeFileFromBytesByStream(PATH_TEMP + "writeFileFromBytesByStream.txt", bytes, new FileIOUtils.OnProgressUpdateListener() { @Override public void onProgressUpdate(double progress) { System.out.println(String.format("%.2f", progress)); } }); } @Test public void writeFileFromString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.append(i).append("FileIOUtilsTest\n"); } FileIOUtils.writeFileFromString(PATH_TEMP + "writeFileFromString.txt", sb.toString()); } @Test public void readFile2List() { writeFileFromString(); for (String s : FileIOUtils.readFile2List(PATH_TEMP + "writeFileFromString.txt")) { System.out.println(s); } } @Test public void readFile2String() { writeFileFromString(); System.out.println(FileIOUtils.readFile2String(PATH_TEMP + "writeFileFromString.txt")); } @Test public void readFile2Bytes() throws Exception { writeFileFromBytesByStream(); FileIOUtils.readFile2BytesByStream(PATH_TEMP + "writeFileFromIS.txt", new FileIOUtils.OnProgressUpdateListener() { @Override public void onProgressUpdate(double progress) { System.out.println(String.format("%.2f", progress)); } }); } @After public void tearDown() { FileUtils.deleteAllInDir(PATH_TEMP); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/FileIOUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
638
```java package com.blankj.utilcode.util; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * <pre> * author: Blankj * blog : path_to_url * time : 2016/08/12 * desc : test EncodeUtils * </pre> */ public class EncodeUtilsTest extends BaseTest { @Test public void urlEncode_urlDecode() { String urlEncodeString = "%E5%93%88%E5%93%88%E5%93%88"; assertEquals(urlEncodeString, EncodeUtils.urlEncode("")); assertEquals(urlEncodeString, EncodeUtils.urlEncode("", "UTF-8")); assertEquals("", EncodeUtils.urlDecode(urlEncodeString)); assertEquals("", EncodeUtils.urlDecode(urlEncodeString, "UTF-8")); } @Test public void base64Decode_base64Encode() { assertArrayEquals("blankj".getBytes(), EncodeUtils.base64Decode(EncodeUtils.base64Encode("blankj"))); assertArrayEquals("blankj".getBytes(), EncodeUtils.base64Decode(EncodeUtils.base64Encode2String("blankj".getBytes()))); assertEquals( "Ymxhbmtq", EncodeUtils.base64Encode2String("blankj".getBytes()) ); assertArrayEquals("Ymxhbmtq".getBytes(), EncodeUtils.base64Encode("blankj".getBytes())); } @Test public void htmlEncode_htmlDecode() { String html = "<html>" + "<head>" + "<title> HTML </title>" + "</head>" + "<body>" + "<p>body </p>" + "<p>title </p>" + "</body>" + "</html>"; String encodeHtml = "&lt;html&gt;&lt;head&gt;&lt;title&gt; HTML &lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;body &lt;/p&gt;&lt;p&gt;title &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; assertEquals(encodeHtml, EncodeUtils.htmlEncode(html)); assertEquals(html, EncodeUtils.htmlDecode(encodeHtml).toString()); } @Test public void binEncode_binDecode() { String test = "test"; String binary = EncodeUtils.binaryEncode(test); assertEquals("test", EncodeUtils.binaryDecode(binary)); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/EncodeUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
519
```java package com.blankj.utilcode.util; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/01/15 * desc : test ColorUtils * </pre> */ public class ColorUtilsTest extends BaseTest { @Test public void setAlphaComponent() { assertEquals(0x80ffffff, ColorUtils.setAlphaComponent(0xffffffff, 0x80)); assertEquals(0x80ffffff, ColorUtils.setAlphaComponent(0xffffffff, 0.5f)); } @Test public void setRedComponent() { assertEquals(0xff80ffff, ColorUtils.setRedComponent(0xffffffff, 0x80)); assertEquals(0xff80ffff, ColorUtils.setRedComponent(0xffffffff, 0.5f)); } @Test public void setGreenComponent() { assertEquals(0xffff80ff, ColorUtils.setGreenComponent(0xffffffff, 0x80)); assertEquals(0xffff80ff, ColorUtils.setGreenComponent(0xffffffff, 0.5f)); } @Test public void setBlueComponent() { assertEquals(0xffffff80, ColorUtils.setBlueComponent(0xffffffff, 0x80)); assertEquals(0xffffff80, ColorUtils.setBlueComponent(0xffffffff, 0.5f)); } @Test public void string2Int() { assertEquals(0xffffffff, ColorUtils.string2Int("#ffffff")); assertEquals(0xffffffff, ColorUtils.string2Int("#ffffffff")); assertEquals(0xffffffff, ColorUtils.string2Int("white")); } @Test public void int2RgbString() { assertEquals("#000001", ColorUtils.int2RgbString(1)); assertEquals("#ffffff", ColorUtils.int2RgbString(0xffffff)); } @Test public void int2ArgbString() { assertEquals("#ff000001", ColorUtils.int2ArgbString(1)); assertEquals("#ffffffff", ColorUtils.int2ArgbString(0xffffff)); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/ColorUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
460
```java package com.blankj.utilcode.util; import org.junit.Assert; import org.junit.Test; /** * <pre> * author: blankj * blog : path_to_url * time : 2020/04/13 * desc : test NumberUtils * </pre> */ public class NumberUtilsTest { @Test public void format() { double val = Math.PI * 100000;// 314159.2653589793 Assert.assertEquals("314159.27", NumberUtils.format(val, 2)); Assert.assertEquals("314159.265", NumberUtils.format(val, 3)); Assert.assertEquals("314159.27", NumberUtils.format(val, 2, true)); Assert.assertEquals("314159.26", NumberUtils.format(val, 2, false)); Assert.assertEquals("00314159.27", NumberUtils.format(val, 8, 2, true)); Assert.assertEquals("0000314159.27", NumberUtils.format(val, 10, 2, true)); Assert.assertEquals("314,159.27", NumberUtils.format(val, true, 2)); Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2)); Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2, true)); Assert.assertEquals("314159.26", NumberUtils.format(val, false, 2, false)); Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2, true)); Assert.assertEquals("314159.265", NumberUtils.format(val, false, 3, false)); } @Test public void float2Double() { float val = 3.14f; System.out.println((double) val); System.out.println(NumberUtils.float2Double(val)); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/NumberUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
392
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class TestHierarchicalMethodsBase { public static String PUBLIC_RESULT = "PUBLIC_BASE"; public static String PRIVATE_RESULT = "PRIVATE_BASE"; private int invisibleField1; private int invisibleField2; public int visibleField1; public int visibleField2; public String pub_base_method(int number) { return PUBLIC_RESULT; } public String pub_method(int number) { return PUBLIC_RESULT; } private String priv_method(int number) { return PRIVATE_RESULT; } private String very_priv_method() { return PRIVATE_RESULT; } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsBase.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
180
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test5 { private static void s_method() { } private void i_method() { } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test5.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
79
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test7 { public final String s; public final Integer i; private Test7(int i) { this(null, i); } private Test7(String s) { this(s, null); } private Test7(String s, int i) { this(s, (Integer) i); } private Test7(String s, Integer i) { this.s = s; this.i = i; } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test7.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
152
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/05/03 * desc : * </pre> */ public interface Test10 { void setFoo(String s); void setBar(boolean b); void setBaz(String baz); void testIgnore(); String getFoo(); boolean isBar(); String getBaz(); } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test10.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
103
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/05/03 * desc : * </pre> */ public interface Test9 { String substring(int beginIndex); String substring(int beginIndex, int endIndex); String substring(Integer beginIndex); String substring(Integer beginIndex, Integer endIndex); } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test9.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
94
```java package com.blankj.utilcode.util.reflect; import java.util.HashMap; import java.util.Map; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test6 { public Map<String, String> map = new HashMap<String, String>(); public void put(String name, String value) { map.put(name, value); } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test6.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
105
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class PrivateConstructors { public final String string; private PrivateConstructors() { this(null); } private PrivateConstructors(String string) { this.string = string; } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/PrivateConstructors.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
97
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class TestHierarchicalMethodsSubclass extends TestHierarchicalMethodsBase { public static String PUBLIC_RESULT = "PUBLIC_SUB"; public static String PRIVATE_RESULT = "PRIVATE_SUB"; // Both of these are hiding fields in the super type private int invisibleField2; public int visibleField2; private int invisibleField3; public int visibleField3; private String priv_method(int number) { return PRIVATE_RESULT; } private String pub_method(Integer number) { return PRIVATE_RESULT; } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsSubclass.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
168
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test8 { public static final int SF_INT1 = new Integer(0); public static final Integer SF_INT2 = new Integer(0); public final int F_INT1 = new Integer(0); public final Integer F_INT2 = new Integer(0); public static Test8 S_DATA; public Test8 I_DATA; } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test8.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
136
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test3 { public Object n; public MethodType methodType; public void method() { this.n = null; this.methodType = MethodType.NO_ARGS; } public void method(Integer n1) { this.n = n1; this.methodType = MethodType.INTEGER; } public void method(Number n1) { this.n = n1; this.methodType = MethodType.NUMBER; } public void method(Object n1) { this.n = n1; this.methodType = MethodType.OBJECT; } public static enum MethodType { NO_ARGS, INTEGER, NUMBER, OBJECT } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test3.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
202
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test4 { public static void s_method() { } public void i_method() { } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test4.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
79
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class TestPrivateStaticFinal { private static final int I1 = new Integer(1); private static final Integer I2 = new Integer(1); } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestPrivateStaticFinal.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
89
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test2 { public final Object n; public final ConstructorType constructorType; public Test2() { this.n = null; this.constructorType = ConstructorType.NO_ARGS; } public Test2(Integer n) { this.n = n; this.constructorType = ConstructorType.INTEGER; } public Test2(Number n) { this.n = n; this.constructorType = ConstructorType.NUMBER; } public Test2(Object n) { this.n = n; this.constructorType = ConstructorType.OBJECT; } public static enum ConstructorType { NO_ARGS, INTEGER, NUMBER, OBJECT } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test2.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
198
```java package com.blankj.utilcode.util.reflect; /** * <pre> * author: Blankj * blog : path_to_url * time : 2018/01/12 * desc : * </pre> */ public class Test1 { public static int S_INT1; public static Integer S_INT2; public int I_INT1; public Integer I_INT2; public static Test1 S_DATA; public Test1 I_DATA; } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test1.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
110
```java package com.blankj.common; import com.blankj.base.BaseApplication; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/06/05 * desc : app about common * </pre> */ public class CommonApplication extends BaseApplication { @Override public void onCreate() { super.onCreate(); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/CommonApplication.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
88
```java package com.blankj.common.view; import android.animation.ObjectAnimator; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : path_to_url * time : 2020/03/28 * desc : * </pre> */ public class RotateView extends View { private ObjectAnimator headerAnimator; public RotateView(Context context) { this(context, null); } public RotateView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public RotateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (headerAnimator == null) { initAnimator(); } if (visibility == VISIBLE) { headerAnimator.start(); } else { headerAnimator.end(); } } private void initAnimator() { headerAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f); headerAnimator.setRepeatCount(ObjectAnimator.INFINITE); headerAnimator.setInterpolator(new LinearInterpolator()); headerAnimator.setRepeatMode(ObjectAnimator.RESTART); headerAnimator.setDuration(1000); headerAnimator.start(); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/view/RotateView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
319
```java package com.blankj.common.activity; import android.view.MenuItem; import android.view.View; import android.view.ViewStub; import android.widget.FrameLayout; import com.blankj.common.R; import com.blankj.utilcode.util.BarUtils; import com.blankj.utilcode.util.ColorUtils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityTitleView { public AppCompatActivity mBaseActivity; public CharSequence mTitle; public boolean mIsSupportScroll; public CoordinatorLayout baseTitleRootLayout; public Toolbar baseTitleToolbar; public FrameLayout baseTitleContentView; public ViewStub mViewStub; public CommonActivityTitleView(@NonNull AppCompatActivity activity, @StringRes int resId) { this(activity, activity.getString(resId), true); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @NonNull CharSequence title) { this(activity, title, true); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @StringRes int resId, boolean isSupportScroll) { this(activity, activity.getString(resId), isSupportScroll); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @NonNull CharSequence title, boolean isSupportScroll) { mBaseActivity = activity; mTitle = title; mIsSupportScroll = isSupportScroll; } public void setIsSupportScroll(boolean isSupportScroll) { mIsSupportScroll = isSupportScroll; } public int bindLayout() { return R.layout.common_activity_title; } public View getContentView() { baseTitleRootLayout = mBaseActivity.findViewById(R.id.baseTitleRootLayout); baseTitleToolbar = mBaseActivity.findViewById(R.id.baseTitleToolbar); if (mIsSupportScroll) { mViewStub = mBaseActivity.findViewById(R.id.baseTitleStubScroll); } else { mViewStub = mBaseActivity.findViewById(R.id.baseTitleStubNoScroll); } mViewStub.setVisibility(View.VISIBLE); baseTitleContentView = mBaseActivity.findViewById(R.id.commonTitleContentView); setTitleBar(); BarUtils.setStatusBarColor(mBaseActivity, ColorUtils.getColor(R.color.colorPrimary)); BarUtils.addMarginTopEqualStatusBarHeight(baseTitleRootLayout); return baseTitleContentView; } private void setTitleBar() { mBaseActivity.setSupportActionBar(baseTitleToolbar); ActionBar titleBar = mBaseActivity.getSupportActionBar(); if (titleBar != null) { titleBar.setDisplayHomeAsUpEnabled(true); titleBar.setTitle(mTitle); } } public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { mBaseActivity.finish(); return true; } return mBaseActivity.onOptionsItemSelected(item); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/activity/CommonActivityTitleView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
641
```java package com.blankj.common.activity; import android.content.Intent; import android.net.Uri; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import com.blankj.common.R; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.StringUtils; import com.google.android.material.navigation.NavigationView; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityDrawerView { public AppCompatActivity mBaseActivity; public DrawerLayout mBaseDrawerRootLayout; public FrameLayout mBaseDrawerContainerView; private NavigationView.OnNavigationItemSelectedListener mListener = new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == R.id.baseDrawerActionGitHub) { return goWeb(R.string.github); } else if (id == R.id.baseDrawerActionBlog) { return goWeb(R.string.blog); } return false; } }; public CommonActivityDrawerView(@NonNull AppCompatActivity activity) { mBaseActivity = activity; } public int bindLayout() { return R.layout.common_activity_drawer; } public View getContentView() { mBaseDrawerRootLayout = mBaseActivity.findViewById(R.id.baseDrawerRootLayout); mBaseDrawerContainerView = mBaseActivity.findViewById(R.id.baseDrawerContainerView); NavigationView nav = mBaseActivity.findViewById(R.id.baseDrawerNavView); nav.setNavigationItemSelectedListener(mListener); return mBaseDrawerContainerView; } private boolean goWeb(@StringRes int id) { return ActivityUtils.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(StringUtils.getString(id)))); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/activity/CommonActivityDrawerView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
413
```java package com.blankj.utilcode.util.reflect; import com.blankj.utilcode.util.ReflectUtils; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * <pre> * author: Blankj * blog : path_to_url * time : 2017/12/15 * desc : ReflectUtils * </pre> */ public class ReflectUtilsTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Test public void reflect() { Assert.assertEquals( ReflectUtils.reflect(Object.class), ReflectUtils.reflect("java.lang.Object", ClassLoader.getSystemClassLoader()) ); assertEquals( ReflectUtils.reflect(Object.class), ReflectUtils.reflect("java.lang.Object") ); assertEquals( ReflectUtils.reflect(String.class).get(), ReflectUtils.reflect("java.lang.String").get() ); assertEquals( Object.class, ReflectUtils.reflect(Object.class).get() ); assertEquals( "abc", ReflectUtils.reflect((Object) "abc").get() ); assertEquals( 1, ReflectUtils.reflect(1).get() ); } @Test public void newInstance() { assertEquals( "", ReflectUtils.reflect(String.class).newInstance().get() ); assertEquals( "abc", ReflectUtils.reflect(String.class).newInstance("abc").get() ); assertEquals( "abc", ReflectUtils.reflect(String.class).newInstance("abc".getBytes()).get() ); assertEquals( "abc", ReflectUtils.reflect(String.class).newInstance("abc".toCharArray()).get() ); assertEquals( "b", ReflectUtils.reflect(String.class).newInstance("abc".toCharArray(), 1, 1).get() ); } @Test public void newInstancePrivate() { assertNull(ReflectUtils.reflect(PrivateConstructors.class).newInstance().field("string").get()); assertEquals( "abc", ReflectUtils.reflect(PrivateConstructors.class).newInstance("abc").field("string").get() ); } @Test public void newInstanceNull() { Test2 test2 = ReflectUtils.reflect(Test2.class).newInstance((Object) null).get(); assertNull(test2.n); } @Test public void newInstanceWithPrivate() { Test7 t1 = ReflectUtils.reflect(Test7.class).newInstance(1).get(); assertEquals(1, (int) t1.i); assertNull(t1.s); Test7 t2 = ReflectUtils.reflect(Test7.class).newInstance("a").get(); assertNull(t2.i); assertEquals("a", t2.s); Test7 t3 = ReflectUtils.reflect(Test7.class).newInstance("a", 1).get(); assertEquals(1, (int) t3.i); assertEquals("a", t3.s); } @Test public void newInstanceAmbiguity() { Test2 test; test = ReflectUtils.reflect(Test2.class).newInstance().get(); assertEquals(null, test.n); assertEquals(Test2.ConstructorType.NO_ARGS, test.constructorType); test = ReflectUtils.reflect(Test2.class).newInstance("abc").get(); assertEquals("abc", test.n); assertEquals(Test2.ConstructorType.OBJECT, test.constructorType); test = ReflectUtils.reflect(Test2.class).newInstance(new Long("1")).get(); assertEquals(1L, test.n); assertEquals(Test2.ConstructorType.NUMBER, test.constructorType); test = ReflectUtils.reflect(Test2.class).newInstance(1).get(); assertEquals(1, test.n); assertEquals(Test2.ConstructorType.INTEGER, test.constructorType); test = ReflectUtils.reflect(Test2.class).newInstance('a').get(); assertEquals('a', test.n); assertEquals(Test2.ConstructorType.OBJECT, test.constructorType); } @Test public void method() { // instance methods assertEquals( "", ReflectUtils.reflect((Object) " ").method("trim").get() ); assertEquals( "12", ReflectUtils.reflect((Object) " 12 ").method("trim").get() ); assertEquals( "34", ReflectUtils.reflect((Object) "1234").method("substring", 2).get() ); assertEquals( "12", ReflectUtils.reflect((Object) "1234").method("substring", 0, 2).get() ); assertEquals( "1234", ReflectUtils.reflect((Object) "12").method("concat", "34").get() ); assertEquals( "123456", ReflectUtils.reflect((Object) "12").method("concat", "34").method("concat", "56").get() ); assertEquals( 2, ReflectUtils.reflect((Object) "1234").method("indexOf", "3").get() ); assertEquals( 2.0f, (float) ReflectUtils.reflect((Object) "1234").method("indexOf", "3").method("floatValue").get(), 0.0f ); assertEquals( "2", ReflectUtils.reflect((Object) "1234").method("indexOf", "3").method("toString").get() ); // static methods assertEquals( "true", ReflectUtils.reflect(String.class).method("valueOf", true).get() ); assertEquals( "1", ReflectUtils.reflect(String.class).method("valueOf", 1).get() ); assertEquals( "abc", ReflectUtils.reflect(String.class).method("valueOf", "abc".toCharArray()).get() ); assertEquals( "abc", ReflectUtils.reflect(String.class).method("copyValueOf", "abc".toCharArray()).get() ); assertEquals( "b", ReflectUtils.reflect(String.class).method("copyValueOf", "abc".toCharArray(), 1, 1).get() ); } @Test public void methodVoid() { // instance methods Test4 test4 = new Test4(); assertEquals( test4, ReflectUtils.reflect(test4).method("i_method").get() ); // static methods assertEquals( Test4.class, ReflectUtils.reflect(Test4.class).method("s_method").get() ); } @Test public void methodPrivate() { // instance methods Test5 test8 = new Test5(); assertEquals( test8, ReflectUtils.reflect(test8).method("i_method").get() ); // static methods assertEquals( Test5.class, ReflectUtils.reflect(Test5.class).method("s_method").get() ); } @Test public void methodNullArguments() { Test6 test9 = new Test6(); ReflectUtils.reflect(test9).method("put", "key", "value"); assertTrue(test9.map.containsKey("key")); assertEquals("value", test9.map.get("key")); ReflectUtils.reflect(test9).method("put", "key", null); assertTrue(test9.map.containsKey("key")); assertNull(test9.map.get("key")); } @Test public void methodSuper() { TestHierarchicalMethodsSubclass subclass = new TestHierarchicalMethodsSubclass(); assertEquals( TestHierarchicalMethodsBase.PUBLIC_RESULT, ReflectUtils.reflect(subclass).method("pub_base_method", 1).get() ); assertEquals( TestHierarchicalMethodsBase.PRIVATE_RESULT, ReflectUtils.reflect(subclass).method("very_priv_method").get() ); } @Test public void methodDeclaring() { TestHierarchicalMethodsSubclass subclass = new TestHierarchicalMethodsSubclass(); assertEquals( TestHierarchicalMethodsSubclass.PRIVATE_RESULT, ReflectUtils.reflect(subclass).method("priv_method", 1).get() ); TestHierarchicalMethodsBase baseClass = new TestHierarchicalMethodsBase(); assertEquals( TestHierarchicalMethodsBase.PRIVATE_RESULT, ReflectUtils.reflect(baseClass).method("priv_method", 1).get() ); } @Test public void methodAmbiguity() { Test3 test; test = ReflectUtils.reflect(Test3.class).newInstance().method("method").get(); assertEquals(null, test.n); assertEquals(Test3.MethodType.NO_ARGS, test.methodType); test = ReflectUtils.reflect(Test3.class).newInstance().method("method", "abc").get(); assertEquals("abc", test.n); assertEquals(Test3.MethodType.OBJECT, test.methodType); test = ReflectUtils.reflect(Test3.class).newInstance().method("method", new Long("1")).get(); assertEquals(1L, test.n); assertEquals(Test3.MethodType.NUMBER, test.methodType); test = ReflectUtils.reflect(Test3.class).newInstance().method("method", 1).get(); assertEquals(1, test.n); assertEquals(Test3.MethodType.INTEGER, test.methodType); test = ReflectUtils.reflect(Test3.class).newInstance().method("method", 'a').get(); assertEquals('a', test.n); assertEquals(Test3.MethodType.OBJECT, test.methodType); } @Test public void field() { // instance field Test1 test1 = new Test1(); ReflectUtils.reflect(test1).field("I_INT1", 1); assertEquals(1, ReflectUtils.reflect(test1).field("I_INT1").get()); ReflectUtils.reflect(test1).field("I_INT2", 1); assertEquals(1, ReflectUtils.reflect(test1).field("I_INT2").get()); ReflectUtils.reflect(test1).field("I_INT2", null); assertNull(ReflectUtils.reflect(test1).field("I_INT2").get()); // static field ReflectUtils.reflect(Test1.class).field("S_INT1", 1); assertEquals(1, ReflectUtils.reflect(Test1.class).field("S_INT1").get()); ReflectUtils.reflect(Test1.class).field("S_INT2", 1); assertEquals(1, ReflectUtils.reflect(Test1.class).field("S_INT2").get()); ReflectUtils.reflect(Test1.class).field("S_INT2", null); assertNull(ReflectUtils.reflect(Test1.class).field("S_INT2").get()); // hierarchies field TestHierarchicalMethodsSubclass test2 = new TestHierarchicalMethodsSubclass(); ReflectUtils.reflect(test2).field("invisibleField1", 1); assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField1").get()); ReflectUtils.reflect(test2).field("invisibleField2", 1); assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField2").get()); ReflectUtils.reflect(test2).field("invisibleField3", 1); assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField3").get()); ReflectUtils.reflect(test2).field("visibleField1", 1); assertEquals(1, ReflectUtils.reflect(test2).field("visibleField1").get()); ReflectUtils.reflect(test2).field("visibleField2", 1); assertEquals(1, ReflectUtils.reflect(test2).field("visibleField2").get()); ReflectUtils.reflect(test2).field("visibleField3", 1); assertEquals(1, ReflectUtils.reflect(test2).field("visibleField3").get()); } @Test public void fieldPrivate() { class Foo { private String bar; } Foo foo = new Foo(); ReflectUtils.reflect(foo).field("bar", "FooBar"); assertThat(foo.bar, Matchers.is("FooBar")); assertEquals("FooBar", ReflectUtils.reflect(foo).field("bar").get()); ReflectUtils.reflect(foo).field("bar", null); assertNull(foo.bar); assertNull(ReflectUtils.reflect(foo).field("bar").get()); } @Test public void fieldFinal() { // instance field Test8 test11 = new Test8(); ReflectUtils.reflect(test11).field("F_INT1", 1); assertEquals(1, ReflectUtils.reflect(test11).field("F_INT1").get()); ReflectUtils.reflect(test11).field("F_INT2", 1); assertEquals(1, ReflectUtils.reflect(test11).field("F_INT2").get()); ReflectUtils.reflect(test11).field("F_INT2", null); assertNull(ReflectUtils.reflect(test11).field("F_INT2").get()); // static field ReflectUtils.reflect(Test8.class).field("SF_INT1", 1); assertEquals(1, ReflectUtils.reflect(Test8.class).field("SF_INT1").get()); ReflectUtils.reflect(Test8.class).field("SF_INT2", 1); assertEquals(1, ReflectUtils.reflect(Test8.class).field("SF_INT2").get()); ReflectUtils.reflect(Test8.class).field("SF_INT2", null); assertNull(ReflectUtils.reflect(Test8.class).field("SF_INT2").get()); } @Test public void fieldPrivateStaticFinal() { assertEquals(1, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1").get()); assertEquals(1, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2").get()); ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1", 2); ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2", 2); assertEquals(2, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1").get()); assertEquals(2, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2").get()); } @Test public void fieldAdvanced() { ReflectUtils.reflect(Test1.class) .field("S_DATA", ReflectUtils.reflect(Test1.class).newInstance()) .field("S_DATA") .field("I_DATA", ReflectUtils.reflect(Test1.class).newInstance()) .field("I_DATA") .field("I_INT1", 1) .field("S_INT1", 2); assertEquals(2, Test1.S_INT1); assertEquals(null, Test1.S_INT2); assertEquals(0, Test1.S_DATA.I_INT1); assertEquals(null, Test1.S_DATA.I_INT2); assertEquals(1, Test1.S_DATA.I_DATA.I_INT1); assertEquals(null, Test1.S_DATA.I_DATA.I_INT2); } @Test public void fieldFinalAdvanced() { ReflectUtils.reflect(Test8.class) .field("S_DATA", ReflectUtils.reflect(Test8.class).newInstance()) .field("S_DATA") .field("I_DATA", ReflectUtils.reflect(Test8.class).newInstance()) .field("I_DATA") .field("F_INT1", 1) .field("F_INT2", 1) .field("SF_INT1", 2) .field("SF_INT2", 2); assertEquals(2, Test8.SF_INT1); assertEquals(new Integer(2), Test8.SF_INT2); assertEquals(0, Test8.S_DATA.F_INT1); assertEquals(new Integer(0), Test8.S_DATA.F_INT2); assertEquals(1, Test8.S_DATA.I_DATA.F_INT1); assertEquals(new Integer(1), Test8.S_DATA.I_DATA.F_INT2); } @Test public void _hashCode() { Object object = new Object(); assertEquals(ReflectUtils.reflect(object).hashCode(), object.hashCode()); } @Test public void _toString() { Object object = new Object() { @Override public String toString() { return "test"; } }; assertEquals(ReflectUtils.reflect(object).toString(), object.toString()); } @Test public void _equals() { Object object = new Object(); ReflectUtils a = ReflectUtils.reflect(object); ReflectUtils b = ReflectUtils.reflect(object); ReflectUtils c = ReflectUtils.reflect(object); assertTrue(b.equals(a)); assertTrue(a.equals(b)); assertTrue(b.equals(c)); assertTrue(a.equals(c)); //noinspection ObjectEqualsNull assertFalse(a.equals(null)); } @Test public void testProxy() { assertEquals("abc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0)); assertEquals("bc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1)); assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2)); assertEquals("a", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0, 1)); assertEquals("b", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1, 2)); assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2, 3)); assertEquals("abc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0)); assertEquals("bc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1)); assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2)); assertEquals("a", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0, 1)); assertEquals("b", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1, 2)); assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2, 3)); } @Test public void testMapProxy() { class MyMap extends HashMap<String, Object> { private String baz; public void setBaz(String baz) { this.baz = "MyMap: " + baz; } public String getBaz() { return baz; } } Map<String, Object> map = new MyMap(); ReflectUtils.reflect(map).proxy(Test10.class).setFoo("abc"); assertEquals(1, map.size()); assertEquals("abc", map.get("foo")); assertEquals("abc", ReflectUtils.reflect(map).proxy(Test10.class).getFoo()); ReflectUtils.reflect(map).proxy(Test10.class).setBar(true); assertEquals(2, map.size()); assertEquals(true, map.get("bar")); assertEquals(true, ReflectUtils.reflect(map).proxy(Test10.class).isBar()); ReflectUtils.reflect(map).proxy(Test10.class).setBaz("baz"); assertEquals(2, map.size()); assertEquals(null, map.get("baz")); assertEquals("MyMap: baz", ReflectUtils.reflect(map).proxy(Test10.class).getBaz()); try { ReflectUtils.reflect(map).proxy(Test10.class).testIgnore(); fail(); } catch (ReflectUtils.ReflectException ignored) { } } } ```
/content/code_sandbox/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/ReflectUtilsTest.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
4,099
```java package com.blankj.common.activity; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.item.CommonItem; import java.util.List; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityItemsView { public AppCompatActivity mBaseActivity; private List<CommonItem> mItems; public BaseItemAdapter<CommonItem> mCommonItemAdapter; public RecyclerView mCommonItemRv; public CommonActivityItemsView(@NonNull AppCompatActivity activity, @NonNull List<CommonItem> items) { mBaseActivity = activity; mItems = items; } public int bindLayout() { return R.layout.common_item; } public void initView() { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(mItems); mCommonItemRv = mBaseActivity.findViewById(R.id.commonItemRv); mCommonItemRv.setAdapter(mCommonItemAdapter); mCommonItemRv.setLayoutManager(new LinearLayoutManager(mBaseActivity)); mCommonItemRv.addItemDecoration(new RecycleViewDivider(mBaseActivity, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/activity/CommonActivityItemsView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
377
```java package com.blankj.common.activity; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.blankj.base.BaseActivity; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.dialog.CommonDialogLoading; import com.blankj.common.item.CommonItem; import com.blankj.swipepanel.SwipePanel; import com.blankj.utilcode.util.LanguageUtils; import com.blankj.utilcode.util.SizeUtils; import java.util.List; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : path_to_url * time : 2019/06/05 * desc : * </pre> */ public abstract class CommonActivity extends BaseActivity { private CommonActivityItemsView mItemsView; private CommonActivityTitleView mTitleView; private CommonActivityDrawerView mDrawerView; private CommonDialogLoading mDialogLoading; public View commonContentView; // @Override // protected void attachBaseContext(Context newBase) { // super.attachBaseContext(LanguageUtils.attachBaseContext(newBase)); // } /////////////////////////////////////////////////////////////////////////// // title view /////////////////////////////////////////////////////////////////////////// public boolean isSwipeBack() { return true; } @StringRes public int bindTitleRes() { return View.NO_ID; } public CharSequence bindTitle() { return ""; } public boolean isSupportScroll() { return true; } public CommonActivityTitleView bindTitleView() { return null; } /////////////////////////////////////////////////////////////////////////// // items view /////////////////////////////////////////////////////////////////////////// public CommonActivityItemsView bindItemsView() { return null; } public List<CommonItem> bindItems() { return null; } /////////////////////////////////////////////////////////////////////////// // drawer view /////////////////////////////////////////////////////////////////////////// public CommonActivityDrawerView bindDrawerView() { return null; } public boolean bindDrawer() { return false; } @CallSuper @Override public void initData(@Nullable Bundle bundle) { mTitleView = bindTitleView(); if (mTitleView == null) { int titleRes = bindTitleRes(); if (titleRes != View.NO_ID) { mTitleView = new CommonActivityTitleView(this, titleRes, isSupportScroll()); } else { CharSequence title = bindTitle(); if (!TextUtils.isEmpty(title)) { mTitleView = new CommonActivityTitleView(this, title, isSupportScroll()); } } } mItemsView = bindItemsView(); if (mItemsView == null) { List<CommonItem> items = bindItems(); if (items != null) { mItemsView = new CommonActivityItemsView(this, items); } } mDrawerView = bindDrawerView(); if (mDrawerView == null) { if (bindDrawer()) { mDrawerView = new CommonActivityDrawerView(this); } } if (mTitleView != null && mItemsView != null) { mTitleView.setIsSupportScroll(false); } findViewById(android.R.id.content).setBackgroundColor(getResources().getColor(R.color.lightGrayDark)); initSwipeBack(); } @Override public int bindLayout() { return View.NO_ID; } @Override public void setContentView() { if (mTitleView != null) { mContentView = LayoutInflater.from(this).inflate(mTitleView.bindLayout(), null); setContentView(mContentView); commonContentView = mTitleView.getContentView(); } else if (mDrawerView != null) { mContentView = LayoutInflater.from(this).inflate(mDrawerView.bindLayout(), null); setContentView(mContentView); commonContentView = mDrawerView.getContentView(); } else { if (mItemsView != null) { mContentView = LayoutInflater.from(this).inflate(mItemsView.bindLayout(), null); setContentView(mContentView); } else { super.setContentView(); } commonContentView = mContentView; return; } if (mItemsView != null) { LayoutInflater.from(this).inflate(mItemsView.bindLayout(), (ViewGroup) commonContentView); } else { if (bindLayout() > 0) { LayoutInflater.from(this).inflate(bindLayout(), (ViewGroup) commonContentView); } } } private void initSwipeBack() { if (isSwipeBack()) { final SwipePanel swipeLayout = new SwipePanel(this); swipeLayout.setLeftDrawable(R.drawable.common_back); swipeLayout.setLeftEdgeSize(SizeUtils.dp2px(16)); swipeLayout.setLeftSwipeColor(getResources().getColor(R.color.colorPrimary)); swipeLayout.wrapView(findViewById(android.R.id.content)); swipeLayout.setOnFullSwipeListener(new SwipePanel.OnFullSwipeListener() { @Override public void onFullSwipe(int direction) { swipeLayout.close(direction); finish(); } }); } } @CallSuper @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { if (mItemsView != null) { mItemsView.initView(); } } @Override public void doBusiness() { } @Override public void onDebouncingClick(@NonNull View view) { } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mTitleView != null) { return mTitleView.onOptionsItemSelected(item); } return super.onOptionsItemSelected(item); } public void showLoading() { showLoading(null); } public void showLoading(Runnable listener) { if (mDialogLoading != null) { return; } mDialogLoading = new CommonDialogLoading().init(this, listener); mDialogLoading.show(); } public void dismissLoading() { if (mDialogLoading != null) { mDialogLoading.dismiss(); mDialogLoading = null; } } public CommonActivityItemsView getItemsView() { return mItemsView; } public CommonActivityTitleView getTitleView() { return mTitleView; } public CommonActivityDrawerView getDrawerView() { return mDrawerView; } private BaseItemAdapter<CommonItem> mCommonItemAdapter; public void setCommonItems(RecyclerView rv, List<CommonItem> items) { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(items); rv.setAdapter(mCommonItemAdapter); rv.setLayoutManager(new LinearLayoutManager(this)); rv.addItemDecoration(new RecycleViewDivider(this, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateCommonItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateCommonItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } public BaseItemAdapter<CommonItem> getCommonItemAdapter() { return mCommonItemAdapter; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/activity/CommonActivity.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,554
```java package com.blankj.common.dialog; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.blankj.base.dialog.BaseDialogFragment; import com.blankj.base.dialog.DialogLayoutCallback; import com.blankj.common.R; import com.blankj.utilcode.util.BarUtils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/29 * desc : * </pre> */ public class CommonDialogLoading extends BaseDialogFragment { public CommonDialogLoading init(Context context, final Runnable onCancelListener) { super.init(context, new DialogLayoutCallback() { @Override public int bindTheme() { return R.style.CommonLoadingDialogStyle; } @Override public int bindLayout() { return R.layout.common_dialog_loading; } @Override public void initView(BaseDialogFragment dialog, View contentView) { if (onCancelListener == null) { setCancelable(false); } else { setCancelable(true); } } @Override public void setWindowStyle(final Window window) { window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); BarUtils.setStatusBarColor(window, Color.TRANSPARENT); } @Override public void onCancel(BaseDialogFragment dialog) { if (onCancelListener != null) { onCancelListener.run(); } } @Override public void onDismiss(BaseDialogFragment dialog) { } }); return this; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/dialog/CommonDialogLoading.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
340
```java package com.blankj.common.dialog; import android.content.Context; import android.text.TextUtils; import android.util.Pair; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TextView; import com.blankj.base.dialog.BaseDialogFragment; import com.blankj.base.dialog.DialogLayoutCallback; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/18 * desc : * </pre> */ public class CommonDialogContent extends BaseDialogFragment { private RelativeLayout cdcTitleRl; private TextView cdcTitleTv; private RelativeLayout cdcContentRl; private TextView cdcContentTv; private RelativeLayout cdcBottomRl; private TextView cdcBottomPositiveTv; private TextView cdcBottomNegativeTv; public CommonDialogContent init(Context context, final CharSequence title, final CharSequence content, final Pair<CharSequence, View.OnClickListener> positiveBtnAction, final Pair<CharSequence, View.OnClickListener> negativeBtnAction) { super.init(context, new DialogLayoutCallback() { @Override public int bindTheme() { return R.style.CommonContentDialogStyle; } @Override public int bindLayout() { return R.layout.common_dialog_content; } @Override public void initView(final BaseDialogFragment dialog, View contentView) { cdcTitleRl = contentView.findViewById(R.id.cdcTitleRl); cdcTitleTv = contentView.findViewById(R.id.cdcTitleTv); cdcContentRl = contentView.findViewById(R.id.cdcContentRl); cdcContentTv = contentView.findViewById(R.id.cdcContentTv); cdcBottomRl = contentView.findViewById(R.id.cdcBottomRl); cdcBottomPositiveTv = contentView.findViewById(R.id.cdcBottomPositiveTv); cdcBottomNegativeTv = contentView.findViewById(R.id.cdcBottomNegativeTv); if (TextUtils.isEmpty(title)) { cdcTitleRl.setVisibility(View.GONE); } else { cdcTitleTv.setText(title); } if (TextUtils.isEmpty(content)) { cdcContentRl.setVisibility(View.GONE); } else { cdcContentTv.setText(content); } if (positiveBtnAction == null && negativeBtnAction == null) { cdcBottomRl.setVisibility(View.GONE); } else { if (positiveBtnAction != null) { ClickUtils.applyPressedBgDark(cdcBottomPositiveTv); cdcBottomPositiveTv.setText(positiveBtnAction.first); cdcBottomPositiveTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); positiveBtnAction.second.onClick(v); } }); } if (negativeBtnAction != null) { ClickUtils.applyPressedBgDark(cdcBottomNegativeTv); cdcBottomNegativeTv.setText(negativeBtnAction.first); cdcBottomNegativeTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); negativeBtnAction.second.onClick(v); } }); } } } @Override public void setWindowStyle(Window window) { } @Override public void onCancel(BaseDialogFragment dialog) { } @Override public void onDismiss(BaseDialogFragment dialog) { } }); return this; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/dialog/CommonDialogContent.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
741
```java package com.blankj.common.fragment; import android.os.Bundle; import android.view.View; import com.blankj.base.BaseFragment; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.activity.CommonActivityItemsView; import com.blankj.common.item.CommonItem; import java.util.List; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/11/03 * desc : * </pre> */ public class CommonFragment extends BaseFragment { private CommonActivityItemsView mItemsView; /////////////////////////////////////////////////////////////////////////// // items view /////////////////////////////////////////////////////////////////////////// public CommonActivityItemsView bindItemsView() { return null; } public List<CommonItem> bindItems() { return null; } @CallSuper @Override public void initData(@Nullable Bundle bundle) { mItemsView = bindItemsView(); if (mItemsView == null) { List<CommonItem> items = bindItems(); if (items != null) { mItemsView = new CommonActivityItemsView(mActivity, items); } } } @Override public int bindLayout() { return View.NO_ID; } @Override public void setContentView() { if (mItemsView != null) { mContentView = mInflater.inflate(mItemsView.bindLayout(), null); } else { super.setContentView(); } } @CallSuper @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { if (mItemsView != null) { mItemsView.initView(); } } @Override public void doBusiness() { log("doBusiness"); } @Override public void onDebouncingClick(@NonNull View view) { } public CommonActivityItemsView getItemsView() { return mItemsView; } private BaseItemAdapter<CommonItem> mCommonItemAdapter; public void setCommonItems(RecyclerView rv, List<CommonItem> items) { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(items); rv.setAdapter(mCommonItemAdapter); rv.setLayoutManager(new LinearLayoutManager(mActivity)); rv.addItemDecoration(new RecycleViewDivider(mActivity, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateCommonItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateCommonItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } public BaseItemAdapter<CommonItem> getCommonItemAdapter() { return mCommonItemAdapter; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/fragment/CommonFragment.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
636
```java package com.blankj.common.item; import android.view.MotionEvent; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/31 * desc : * </pre> */ public class CommonItemSeekBar extends CommonItem { private CharSequence mTitle; private CharSequence mContent; private int mMaxProgress; private int mCurProgress; private ProgressListener mProgressListener; public CommonItemSeekBar(@StringRes int title, int maxProgress, @NonNull ProgressListener listener) { this(StringUtils.getString(title), maxProgress, listener); } public CommonItemSeekBar(@NonNull CharSequence title, int maxProgress, @NonNull ProgressListener listener) { super(R.layout.common_item_title_seekbar); mTitle = title; mMaxProgress = maxProgress; mCurProgress = listener.getCurValue(); mProgressListener = listener; mContent = String.valueOf(mCurProgress); } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); final SeekBar seekBar = holder.findViewById(R.id.commonItemSb); seekBar.setMax(mMaxProgress); seekBar.setProgress(mCurProgress); holder.itemView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return seekBar.dispatchTouchEvent(event); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mProgressListener.onProgressChanged(seekBar, progress, fromUser); int curValue = mProgressListener.getCurValue(); mCurProgress = curValue; contentTv.setText(String.valueOf(curValue)); seekBar.setProgress(curValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) { mProgressListener.onStartTrackingTouch(seekBar); } @Override public void onStopTrackingTouch(SeekBar seekBar) { mProgressListener.onStopTrackingTouch(seekBar); } }); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } public static abstract class ProgressListener implements SeekBar.OnSeekBarChangeListener { public abstract int getCurValue(); @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItemSeekBar.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
653
```java package com.blankj.common.item; import android.annotation.SuppressLint; import android.view.MotionEvent; import android.view.View; import android.widget.Switch; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/31 * desc : * </pre> */ public class CommonItemSwitch extends CommonItem { private CharSequence mTitle; private CharSequence mContent; private boolean mState; private Utils.Supplier<Boolean> mGetStateSupplier; private Utils.Consumer<Boolean> mSetStateConsumer; public CommonItemSwitch(@StringRes int title, @NonNull Utils.Supplier<Boolean> getStateSupplier, @NonNull Utils.Consumer<Boolean> setStateConsumer) { this(StringUtils.getString(title), getStateSupplier, setStateConsumer); } public CommonItemSwitch(@NonNull CharSequence title, @NonNull Utils.Supplier<Boolean> getStateSupplier, @NonNull Utils.Consumer<Boolean> setStateConsumer) { super(R.layout.common_item_title_switch); mTitle = title; mGetStateSupplier = getStateSupplier; mSetStateConsumer = setStateConsumer; mState = getStateSupplier.get(); mContent = String.valueOf(mState); } @SuppressLint("ClickableViewAccessibility") @Override public void bind(@NonNull final ItemViewHolder holder, int position) { super.bind(holder, position); ClickUtils.applyPressedBgDark(holder.itemView); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); final Switch switchView = holder.findViewById(R.id.commonItemSwitch); switchView.setChecked(mState); switchView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { holder.itemView.onTouchEvent(event); return true; } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mSetStateConsumer.accept(!mState); mState = mGetStateSupplier.get(); contentTv.setText(String.valueOf(mState)); switchView.setChecked(mState); } }); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItemSwitch.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
561
```java package com.blankj.common.item; import android.graphics.Color; import android.view.Gravity; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/31 * desc : * </pre> */ public class CommonItemTitle extends CommonItem { private CharSequence mTitle; private Utils.Supplier<CharSequence> mGetTitleSupplier; private boolean mIsTitleCenter; private CharSequence mContent; public CommonItemTitle(@NonNull Utils.Supplier<CharSequence> getTitleSupplier, boolean isTitleCenter) { super(R.layout.common_item_title_content); mTitle = mGetTitleSupplier.get(); mGetTitleSupplier = getTitleSupplier; mIsTitleCenter = isTitleCenter; } public CommonItemTitle(@StringRes int title, boolean isTitleCenter) { this(StringUtils.getString(title), isTitleCenter); } public CommonItemTitle(@NonNull CharSequence title, boolean isTitleCenter) { super(R.layout.common_item_title_content); mTitle = title; mIsTitleCenter = isTitleCenter; } public CommonItemTitle(@NonNull CharSequence title, CharSequence content) { super(R.layout.common_item_title_content); mTitle = title; mContent = content; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); if (mGetTitleSupplier != null) { mTitle = mGetTitleSupplier.get(); } final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (isViewType(R.layout.common_item_title_content)) { if (mIsTitleCenter) { holder.itemView.setBackgroundColor(Color.TRANSPARENT); titleTv.setGravity(Gravity.CENTER_HORIZONTAL); titleTv.getPaint().setFakeBoldText(true); } else { titleTv.setGravity(Gravity.START); titleTv.getPaint().setFakeBoldText(false); } } } public void setTitle(CharSequence title) { setTitle(title, true); } public void setContent(CharSequence content) { setContent(content, true); } public void setTitle(CharSequence title, boolean isUpdate) { mTitle = title; if (isUpdate) { update(); } } public void setContent(CharSequence content, boolean isUpdate) { mContent = content; if (isUpdate) { update(); } } public CharSequence getTitle() { return mTitle; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItemTitle.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
615
```java package com.blankj.common.item; import android.view.View; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/31 * desc : * </pre> */ public class CommonItemClick extends CommonItem<CommonItemClick> { private CharSequence mTitle; private CharSequence mContent; private boolean mIsJump; public CommonItemClick(@StringRes int title) { this(StringUtils.getString(title), "", false, null); } public CommonItemClick(@NonNull CharSequence title) { this(title, "", false, null); } public CommonItemClick(@StringRes int title, boolean isJump) { this(StringUtils.getString(title), "", isJump); } public CommonItemClick(@NonNull CharSequence title, boolean isJump) { this(title, "", isJump, null); } public CommonItemClick(@StringRes int title, CharSequence content) { this(StringUtils.getString(title), content, false, null); } public CommonItemClick(@NonNull CharSequence title, CharSequence content) { this(title, content, false, null); } public CommonItemClick(@StringRes int title, CharSequence content, boolean isJump) { this(StringUtils.getString(title), content, isJump); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, boolean isJump) { this(title, content, isJump, null); } public CommonItemClick(@StringRes int title, final Runnable simpleClickListener) { this(StringUtils.getString(title), "", false, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, final Runnable simpleClickListener) { this(title, "", false, simpleClickListener); } public CommonItemClick(@StringRes int title, boolean isJump, final Runnable simpleClickListener) { this(StringUtils.getString(title), "", isJump, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, boolean isJump, final Runnable simpleClickListener) { this(title, "", isJump, simpleClickListener); } public CommonItemClick(@StringRes int title, CharSequence content, final Runnable simpleClickListener) { this(StringUtils.getString(title), content, false, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, final Runnable simpleClickListener) { this(title, content, false, simpleClickListener); } public CommonItemClick(@StringRes int title, CharSequence content, boolean isJump, final Runnable simpleClickListener) { this(StringUtils.getString(title), content, isJump, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, boolean isJump, final Runnable simpleClickListener) { super(R.layout.common_item_title_click); mTitle = title; mContent = content; mIsJump = isJump; if (simpleClickListener == null) return; setOnItemClickListener(new OnItemClickListener<CommonItemClick>() { @Override public void onItemClick(ItemViewHolder holder, CommonItemClick item, int position) { if (simpleClickListener != null) { simpleClickListener.run(); } } }); } public CommonItemClick setOnClickUpdateContentListener(@NonNull final Utils.Supplier<CharSequence> supplier) { setOnItemClickListener(new OnItemClickListener<CommonItemClick>() { @Override public void onItemClick(ItemViewHolder holder, CommonItemClick item, int position) { item.mContent = supplier.get(); update(); } }); return this; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); ClickUtils.applyPressedBgDark(holder.itemView); holder.findViewById(R.id.commonItemGoIv).setVisibility(mIsJump ? View.VISIBLE : View.GONE); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItemClick.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
916
```java package com.blankj.common.item; import com.blankj.base.rv.BaseItem; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ColorUtils; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/25 * desc : * </pre> */ public class CommonItem<T extends BaseItem> extends BaseItem<T> { private int backgroundColor = ColorUtils.getColor(R.color.lightGray); public CommonItem(int layoutId) { super(layoutId); } @CallSuper @Override public void bind(@NonNull final ItemViewHolder holder, int position) { holder.itemView.setBackgroundColor(backgroundColor); } public CommonItem<T> setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; return this; } public int getBackgroundColor() { return backgroundColor; } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
214
```java package com.blankj.common.item; import android.widget.ImageView; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/10/31 * desc : * </pre> */ public class CommonItemImage extends CommonItem { private CharSequence mTitle; private Utils.Consumer<ImageView> mSetImageConsumer; public CommonItemImage(@StringRes int title, @NonNull Utils.Consumer<ImageView> setImageConsumer) { this(StringUtils.getString(title), setImageConsumer); } public CommonItemImage(@NonNull CharSequence title, @NonNull Utils.Consumer<ImageView> setImageConsumer) { super(R.layout.common_item_title_image); mTitle = title; mSetImageConsumer = setImageConsumer; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); titleTv.setText(mTitle); ImageView commonItemIv = holder.findViewById(R.id.commonItemIv); mSetImageConsumer.accept(commonItemIv); } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/item/CommonItemImage.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
290
```kotlin package com.blankj.common.helper import android.content.Context import android.util.Pair import android.view.View import com.blankj.common.R import com.blankj.common.dialog.CommonDialogContent import com.blankj.utilcode.constant.PermissionConstants import com.blankj.utilcode.util.* /** * ``` * author: Blankj * blog : path_to_url * time : 2018/01/06 * desc : helper about permission * ``` */ object PermissionHelper { fun request(context: Context, callback: PermissionUtils.SimpleCallback, @PermissionConstants.PermissionGroup vararg permissions: String) { PermissionUtils.permission(*permissions) .rationale { activity, shouldRequest -> showRationaleDialog(activity, shouldRequest) } .callback(object : PermissionUtils.SingleCallback { override fun callback(isAllGranted: Boolean, granted: MutableList<String>, deniedForever: MutableList<String>, denied: MutableList<String>) { LogUtils.d(isAllGranted, granted, deniedForever, denied) if (isAllGranted) { callback.onGranted() return } if (deniedForever.isNotEmpty()) { showOpenAppSettingDialog(context) return } val activity = ActivityUtils.getActivityByContext(context) if (activity != null) { SnackbarUtils.with(activity.findViewById(android.R.id.content)) .setMessage("Permission denied: ${permissions2String(denied)}") .showError(true) } callback.onDenied() } fun permissions2String(permissions: MutableList<String>): String { if (permissions.isEmpty()) return "[]" val sb: StringBuilder = StringBuilder() for (permission in permissions) { sb.append(", " + permission.substring(permission.lastIndexOf('.') + 1)) } return "[${sb.substring(2)}]" } }) .request() } fun showRationaleDialog(context: Context, shouldRequest: PermissionUtils.OnRationaleListener.ShouldRequest) { CommonDialogContent().init(context, StringUtils.getString(android.R.string.dialog_alert_title), StringUtils.getString(R.string.permission_rationale_message), Pair(StringUtils.getString(android.R.string.ok), View.OnClickListener { shouldRequest.again(true) }), Pair(StringUtils.getString(android.R.string.cancel), View.OnClickListener { shouldRequest.again(false) })) .show() } fun showExplainDialog(context: Context, denied: List<String>, shouldRequest: PermissionUtils.OnExplainListener.ShouldRequest) { CommonDialogContent().init(context, StringUtils.getString(android.R.string.dialog_alert_title), "We needs the permissions of $denied to test the utils of permission.", Pair(StringUtils.getString(android.R.string.ok), View.OnClickListener { shouldRequest.start(true) }), Pair(StringUtils.getString(android.R.string.cancel), View.OnClickListener { ToastUtils.showShort("request failed.") shouldRequest.start(false) })) .show() } fun showOpenAppSettingDialog(context: Context) { CommonDialogContent().init(context, StringUtils.getString(android.R.string.dialog_alert_title), StringUtils.getString(R.string.permission_denied_forever_message), Pair(StringUtils.getString(android.R.string.ok), View.OnClickListener { PermissionUtils.launchAppDetailsSettings() }), Pair(StringUtils.getString(android.R.string.cancel), View.OnClickListener { })) .show() } } ```
/content/code_sandbox/lib/common/src/main/java/com/blankj/common/helper/PermissionHelper.kt
kotlin
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
685
```java package com.blankj.utildebug; import com.blankj.utildebug.debug.IDebug; import java.util.List; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/28 * desc : utils about debug * </pre> */ public class DebugUtils { private DebugUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } public static void setIconId(final int icon) { } public static void addDebugs(final List<IDebug> debugs) { } } ```
/content/code_sandbox/lib/utildebug-no-op/src/main/java/com/blankj/utildebug/DebugUtils.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
130
```java package com.blankj.utildebug.debug; import android.content.Context; import android.view.View; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/28 * desc : * </pre> */ public interface IDebug { void onAppCreate(Context context); int getCategory(); int getIcon(); int getName(); void onClick(View view); int TOOLS = 0; int PERFORMANCE = 1; int UI = 2; int BIZ = 3; } ```
/content/code_sandbox/lib/utildebug-no-op/src/main/java/com/blankj/utildebug/debug/IDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
129
```java package com.blankj.utildebug.debug; import android.content.Context; import android.view.View; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.DrawableRes; import androidx.annotation.IntDef; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/28 * desc : * </pre> */ public interface IDebug { void onAppCreate(Context context); @Category int getCategory(); @DrawableRes int getIcon(); @StringRes int getName(); void onClick(View view); int TOOLS = 0; int PERFORMANCE = 1; int UI = 2; int BIZ = 3; @IntDef({TOOLS, PERFORMANCE, UI, BIZ}) @Retention(RetentionPolicy.SOURCE) @interface Category { } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/IDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
205
```java package com.blankj.utildebug; import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.view.ViewGroup; import android.view.ViewParent; import com.blankj.utilcode.util.Utils; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.icon.DebugIcon; import com.blankj.utildebug.menu.DebugMenu; import java.util.ArrayList; import java.util.List; import androidx.annotation.DrawableRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/28 * desc : utils about debug * </pre> */ public class DebugUtils { private DebugUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } static { List<IDebug> debugList = new ArrayList<>(); AbsToolDebug.addToolDebugs(debugList); DebugMenu.getInstance().setDebugs(debugList); getApp().registerActivityLifecycleCallbacks(ActivityLifecycleImpl.instance); } public static void setIconId(final @DrawableRes int icon) { DebugIcon.getInstance().setIconId(icon); } public static void addDebugs(final List<IDebug> debugs) { DebugMenu.getInstance().addDebugs(debugs); } public static Application getApp() { return Utils.getApp(); } static class ActivityLifecycleImpl implements Application.ActivityLifecycleCallbacks { private static ActivityLifecycleImpl instance = new ActivityLifecycleImpl(); private int mConfigCount = 0; private ViewGroup.LayoutParams mParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { if (mConfigCount < 0) { ++mConfigCount; } } @Override public void onActivityResumed(Activity activity) { ViewParent parent = DebugIcon.getInstance().getParent(); if (parent != null) { ((ViewGroup) parent).removeView(DebugIcon.getInstance()); } ((ViewGroup) activity.findViewById(android.R.id.content)).addView(DebugIcon.getInstance(), mParams); } @Override public void onActivityPaused(Activity activity) { ((ViewGroup) activity.findViewById(android.R.id.content)).removeView(DebugIcon.getInstance()); } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { --mConfigCount; } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/DebugUtils.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
589
```java package com.blankj.utildebug.debug.tool; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.debug.tool.appInfo.AppInfoDebug; import com.blankj.utildebug.debug.tool.clearCache.ClearCacheDebug; import com.blankj.utildebug.debug.tool.clearStorage.ClearStorageDebug; import com.blankj.utildebug.debug.tool.deviceInfo.DeviceInfoDebug; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerDebug; import com.blankj.utildebug.debug.tool.logcat.LogcatDebug; import com.blankj.utildebug.debug.tool.restartApp.RestartAppDebug; import java.util.List; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public abstract class AbsToolDebug implements IDebug { @Override public int getCategory() { return TOOLS; } public static void addToolDebugs(List<IDebug> debugList) { debugList.add(new AppInfoDebug()); debugList.add(new DeviceInfoDebug()); debugList.add(new FileExplorerDebug()); debugList.add(new LogcatDebug()); debugList.add(new RestartAppDebug()); debugList.add(new ClearStorageDebug()); debugList.add(new ClearCacheDebug()); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/AbsToolDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
279
```java package com.blankj.utildebug.debug.tool.fileExplorer; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public class FileExplorerDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_file_explorer; } @Override public int getName() { return R.string.du_file_explorer; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new FileExplorerFloatView().show(); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
200
```java package com.blankj.utildebug.debug.tool.fileExplorer; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.SearchEditText; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/06 * desc : * </pre> */ public class FileContentView extends BaseContentView<FileExplorerFloatView> { private FileItem mParent; private BaseItemAdapter<FileItem> mAdapter; private List<FileItem> mSrcItems; private SearchEditText fileExplorerSearchEt; private RecyclerView fileExplorerRv; public static void show(FileExplorerFloatView floatView) { new FileContentView(null).attach(floatView, true); } public static void show(FileExplorerFloatView floatView, FileItem fileItem) { new FileContentView(fileItem).attach(floatView, true); } public FileContentView(FileItem parent) { mParent = parent; mSrcItems = FileItem.getFileItems(mParent); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer; } @Override public void onAttach() { fileExplorerSearchEt = findViewById(R.id.fileExplorerSearchEt); fileExplorerRv = findViewById(R.id.fileExplorerRv); if (FileItem.isEmptyItems(mSrcItems)) { fileExplorerSearchEt.setVisibility(GONE); } mAdapter = new BaseItemAdapter<>(); mAdapter.setItems(mSrcItems); fileExplorerRv.setAdapter(mAdapter); fileExplorerRv.setLayoutManager(new LinearLayoutManager(getContext())); fileExplorerRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_file_divider)); fileExplorerSearchEt.setOnTextChangedListener(new SearchEditText.OnTextChangedListener() { @Override public void onTextChanged(String text) { mAdapter.setItems(FileItem.filterItems(mSrcItems, text)); mAdapter.notifyDataSetChanged(); } }); setOnRefreshListener(fileExplorerRv, new OnRefreshListener() { @Override public void onRefresh(BaseContentFloatView floatView) { mSrcItems = FileItem.getFileItems(mParent); mAdapter.setItems(mSrcItems); mAdapter.notifyDataSetChanged(); fileExplorerSearchEt.reset(); floatView.closeRefresh(); } }); } @Override public void onBack() { super.onBack(); if (mParent != null) { mParent.update(); } } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileContentView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
614
```java package com.blankj.utildebug.debug.tool.fileExplorer; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentFloatView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public class FileExplorerFloatView extends BaseContentFloatView<FileExplorerFloatView> { @Override public int bindTitle() { return R.string.du_file_explorer; } @Override public int bindContentLayout() { return NO_ID; } @Override public void initContentView() { FileContentView.show(this); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerFloatView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
156
```java package com.blankj.utildebug.debug.tool.fileExplorer; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.blankj.utilcode.constant.PermissionConstants; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.PathUtils; import com.blankj.utilcode.util.PermissionUtils; import com.blankj.utilcode.util.SDCardUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.TimeUtils; import com.blankj.utilcode.util.UriUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.image.ImageViewer; import com.blankj.utildebug.debug.tool.fileExplorer.sp.SpViewerContentView; import com.blankj.utildebug.helper.FileHelper; import com.blankj.utildebug.helper.ImageLoader; import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/05 * desc : * </pre> */ public class FileItem extends BaseItem<FileItem> { private static final ArrayList<FileItem> EMPTY = CollectionUtils.newArrayList(new FileItem()); private FileItem mParent; private File mFile; private String mName; private boolean isSdcard; private RelativeLayout fileContentRl; private ImageView fileTypeIv; private TextView fileNameTv; private TextView fileInfoTv; private TextView fileMenuDeleteTv; public FileItem(File file, String name) { this(file, name, false); } public FileItem(File file, String name, boolean isSdcard) { super(R.layout.du_item_file); mFile = file; mName = name; this.isSdcard = isSdcard; } public FileItem(FileItem parent, File file) { super(R.layout.du_item_file); mParent = parent; mFile = file; mName = file.getName(); } public FileItem() { super(R.layout.du_item_empty); } @Override public void bind(@NonNull ItemViewHolder holder, int position) { if (isViewType(R.layout.du_item_empty)) return; fileContentRl = holder.findViewById(R.id.fileContentRl); fileTypeIv = holder.findViewById(R.id.fileTypeIv); fileNameTv = holder.findViewById(R.id.fileNameTv); fileInfoTv = holder.findViewById(R.id.fileInfoTv); fileMenuDeleteTv = holder.findViewById(R.id.fileMenuDeleteTv); ClickUtils.applyPressedBgDark(fileContentRl); ClickUtils.applyPressedBgDark(fileMenuDeleteTv); fileNameTv.setText(mName); fileMenuDeleteTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean delete = FileUtils.delete(mFile); if (delete) { getAdapter().removeItem(FileItem.this, true); if (getAdapter().getItems().isEmpty()) { getAdapter().addItem(new FileItem()); getAdapter().notifyDataSetChanged(); v.getRootView().findViewById(R.id.fileExplorerSearchEt).setVisibility(View.GONE); } } else { FloatToast.showLong(FloatToast.WARNING, "Delete failed!"); } } }); fileMenuDeleteTv.setVisibility(mParent == null ? View.GONE : View.VISIBLE); if (mFile.isDirectory()) { fileTypeIv.setImageResource(R.drawable.du_ic_debug_file_explorer); fileInfoTv.setText(String.format("%s %s", StringUtils.getString(R.string.du_file_item_num, CollectionUtils.size(mFile.list())), TimeUtils.millis2String(mFile.lastModified(), "yyyy.MM.dd"))); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (isSdcard) { PermissionUtils.permission(PermissionConstants.STORAGE) .callback(new PermissionUtils.SimpleCallback() { @Override public void onGranted() { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); FileContentView.show(floatView, FileItem.this); } @Override public void onDenied() { FloatToast.showShort("Permission of storage denied!"); } }) .request(); } else { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); FileContentView.show(floatView, FileItem.this); } } }); } else { fileInfoTv.setText(String.format("%s %s", FileUtils.getSize(mFile), TimeUtils.millis2String(mFile.lastModified(), "yyyy.MM.dd"))); @FileHelper.FileType int fileType = FileHelper.getFileType(mFile); if (fileType == FileHelper.IMAGE) { ImageLoader.load(mFile, fileTypeIv); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); ImageViewer.show(floatView, mFile); } }); } else if (fileType == FileHelper.UTF8) { fileTypeIv.setImageResource(R.drawable.du_ic_item_file_utf8); } else if (fileType == FileHelper.SP) { fileTypeIv.setImageResource(R.drawable.du_ic_item_file_sp); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); SpViewerContentView.show(floatView, mFile); } }); } else { fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(UriUtils.file2Uri(mFile)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); ActivityUtils.startActivity(intent); } }); fileTypeIv.setImageResource(R.drawable.du_ic_item_file_default); } } } public File getFile() { return mFile; } public static List<FileItem> getFileItems(final FileItem parent) { if (parent == null) return getFileItems(); List<File> files = FileUtils.listFilesInDir(parent.getFile(), new Comparator<File>() { @Override public int compare(File o1, File o2) { if (o1.isDirectory() && o2.isFile()) { return -1; } else if (o1.isFile() && o2.isDirectory()) { return 1; } else { return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } } }); return (List<FileItem>) CollectionUtils.collect(files, new CollectionUtils.Transformer<File, FileItem>() { @Override public FileItem transform(File input) { return new FileItem(parent, input); } }); } private static List<FileItem> getFileItems() { List<FileItem> fileItems = new ArrayList<>(); String internalAppDataPath = PathUtils.getInternalAppDataPath(); if (!StringUtils.isEmpty(internalAppDataPath)) { File internalDataFile = new File(internalAppDataPath); if (internalDataFile.exists()) { fileItems.add(new FileItem(internalDataFile, "internal")); } } String externalAppDataPath = PathUtils.getExternalAppDataPath(); if (!StringUtils.isEmpty(externalAppDataPath)) { File externalDataFile = new File(externalAppDataPath); if (externalDataFile.exists()) { fileItems.add(new FileItem(externalDataFile, "external")); } } List<String> mountedSDCardPath = SDCardUtils.getMountedSDCardPath(); if (!mountedSDCardPath.isEmpty()) { for (int i = 0; i < mountedSDCardPath.size(); i++) { String path = mountedSDCardPath.get(i); File sdPath = new File(path); if (sdPath.exists()) { fileItems.add(new FileItem(sdPath, "sdcard" + i + "_" + sdPath.getName(), true)); } } } return fileItems; } public static List<FileItem> filterItems(List<FileItem> items, final String key) { return (List<FileItem>) CollectionUtils.select(items, new CollectionUtils.Predicate<FileItem>() { @Override public boolean evaluate(FileItem item) { return item.mName.toLowerCase().contains(key.toLowerCase()); } }); } public static boolean isEmptyItems(List<FileItem> items) { return EMPTY == items; } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,940
```java package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.MapUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.SpanUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.blankj.utildebug.helper.SpHelper; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/09 * desc : * </pre> */ public class SpItem extends BaseItem<SpItem> { private SPUtils mSPUtils; private String mKey; private Object mValue; private Class mClass; private RelativeLayout contentRl; private TextView titleTv; private TextView contentTv; private ImageView goIv; private Switch aSwitch; private TextView deleteTv; public SpItem() { super(R.layout.du_item_empty); } public SpItem(SPUtils spUtils, String key, Object value) { super(R.layout.du_item_sp); mSPUtils = spUtils; mKey = key; mValue = value; mClass = mValue.getClass(); } @Override public void bind(@NonNull final ItemViewHolder holder, int position) { if (isViewType(R.layout.du_item_empty)) return; contentRl = holder.findViewById(R.id.itemSpContentRl); titleTv = holder.findViewById(R.id.itemSpTitleTv); contentTv = holder.findViewById(R.id.itemSpContentTv); goIv = holder.findViewById(R.id.itemSpGoIv); aSwitch = holder.findViewById(R.id.itemSpSwitch); deleteTv = holder.findViewById(R.id.itemSpDeleteTv); SpanUtils.with(titleTv) .append(mKey) .append("(" + SpHelper.getSpClassName(mClass) + ")").setForegroundColor(ColorUtils.getColor(R.color.loveGreen)) .create(); contentTv.setText(mValue.toString()); deleteTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FloatToast.showShort("haha"); } }); if (Boolean.class.equals(mClass)) { holder.itemView.setOnTouchListener(null); aSwitch.setVisibility(View.VISIBLE); goIv.setVisibility(View.GONE); aSwitch.setChecked((Boolean) mValue); View.OnClickListener toggle = new View.OnClickListener() { @Override public void onClick(View v) { final boolean state = !(Boolean) mValue; mValue = state; mSPUtils.put(mKey, state); aSwitch.setChecked(state); contentTv.setText(mValue.toString()); } }; aSwitch.setOnClickListener(toggle); contentRl.setOnClickListener(toggle); } else if (HashSet.class.equals(mClass)) { holder.itemView.setOnTouchListener(null); aSwitch.setVisibility(View.GONE); goIv.setVisibility(View.GONE); contentRl.setOnClickListener(null); } else { ClickUtils.applyPressedBgDark(holder.itemView); aSwitch.setVisibility(View.GONE); goIv.setVisibility(View.VISIBLE); contentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); SpModifyContentView.show(floatView, mSPUtils, mKey, mValue); } }); } } public static List<SpItem> getSpItems(SPUtils spUtils) { Map<String, ?> spMap = spUtils.getAll(); if (MapUtils.isEmpty(spMap)) { return CollectionUtils.newArrayList(new SpItem()); } List<SpItem> items = new ArrayList<>(); for (Map.Entry<String, ?> entry : spMap.entrySet()) { items.add(new SpItem(spUtils, entry.getKey(), entry.getValue())); } return items; } public static List<SpItem> filterItems(List<SpItem> items, final String key) { return (List<SpItem>) CollectionUtils.select(items, new CollectionUtils.Predicate<SpItem>() { @Override public boolean evaluate(SpItem item) { return item.mKey.toLowerCase().contains(key.toLowerCase()); } }); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,028
```java package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.widget.TextView; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.SearchEditText; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import java.io.File; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/09 * desc : * </pre> */ public class SpViewerContentView extends BaseContentView<FileExplorerFloatView> { private File mFile; private BaseItemAdapter<SpItem> mAdapter; private List<SpItem> mSrcItems; private String mSpName; private SPUtils mSPUtils; private TextView spViewTitle; private SearchEditText spViewSearchEt; private RecyclerView spViewRv; public static void show(FileExplorerFloatView floatView, File file) { new SpViewerContentView(file).attach(floatView, true); } public SpViewerContentView(File file) { mFile = file; mSpName = FileUtils.getFileNameNoExtension(mFile); mSPUtils = SPUtils.getInstance(mSpName); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_sp; } @Override public void onAttach() { spViewTitle = findViewById(R.id.spViewTitle); spViewSearchEt = findViewById(R.id.spViewSearchEt); spViewRv = findViewById(R.id.spViewRv); spViewTitle.setText(mSpName); mAdapter = new BaseItemAdapter<>(); mSrcItems = SpItem.getSpItems(mSPUtils); mAdapter.setItems(mSrcItems); spViewRv.setAdapter(mAdapter); spViewRv.setLayoutManager(new LinearLayoutManager(getContext())); spViewRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); spViewSearchEt.setOnTextChangedListener(new SearchEditText.OnTextChangedListener() { @Override public void onTextChanged(String text) { mAdapter.setItems(SpItem.filterItems(mSrcItems, text)); mAdapter.notifyDataSetChanged(); } }); setOnRefreshListener(spViewRv, new OnRefreshListener() { @Override public void onRefresh(BaseContentFloatView floatView) { mSrcItems = SpItem.getSpItems(mSPUtils); mAdapter.setItems(mSrcItems); mAdapter.notifyDataSetChanged(); spViewSearchEt.reset(); floatView.closeRefresh(); } }); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpViewerContentView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
652
```java package com.blankj.utildebug.debug.tool.fileExplorer.text; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/08 * desc : * </pre> */ public class TextViewer { } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/text/TextViewer.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
63
```java package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.SpanUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.blankj.utildebug.helper.SpHelper; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/09 * desc : * </pre> */ public class SpModifyContentView extends BaseContentView<FileExplorerFloatView> { private SPUtils mSPUtils; private String mKey; private Object mValue; private Class mClass; private TextView spModifyTitleTv; private EditText spModifyEt; private TextView spModifyCancelTv; private TextView spModifyYesTv; public static void show(FileExplorerFloatView floatView, SPUtils spUtils, String key, Object value) { new SpModifyContentView(spUtils, key, value).attach(floatView, true); } public SpModifyContentView(SPUtils spUtils, String key, Object value) { mSPUtils = spUtils; mKey = key; mValue = value; mClass = value.getClass(); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_sp_modify; } @Override public void onAttach() { spModifyTitleTv = findViewById(R.id.spModifyTitleTv); spModifyEt = findViewById(R.id.spModifyEt); spModifyCancelTv = findViewById(R.id.spModifyCancelTv); spModifyYesTv = findViewById(R.id.spModifyYesTv); SpanUtils.with(spModifyTitleTv) .append(mKey) .append("(" + SpHelper.getSpClassName(mClass) + ")").setForegroundColor(ColorUtils.getColor(R.color.loveGreen)) .create(); spModifyEt.setText(mValue.toString()); ClickUtils.applyPressedViewScale(spModifyCancelTv, spModifyYesTv); spModifyCancelTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFloatView().back(); } }); spModifyYesTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String val = spModifyEt.getText().toString(); boolean isSuccess = SpHelper.putValue(mSPUtils, mKey, val, mClass); if (isSuccess) { getFloatView().back(); } else { FloatToast.showShort("Type is wrong."); } } }); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpModifyContentView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
617
```java package com.blankj.utildebug.debug.tool.clearStorage; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.ShellUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public class ClearStorageDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_clear_storage; } @Override public int getName() { return R.string.du_clear_storage; } @Override public void onClick(View view) { ShellUtils.execCmd("pm clear " + AppUtils.getAppPackageName(), false); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearStorage/ClearStorageDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
210
```java package com.blankj.utildebug.debug.tool.fileExplorer.image; import com.blankj.utilcode.util.ImageUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.github.chrisbanes.photoview.PhotoView; import java.io.File; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/08 * desc : * </pre> */ public class ImageViewer extends BaseContentView<FileExplorerFloatView> { private File mFile; private PhotoView photoView; public static void show(FileExplorerFloatView floatView, File file) { new ImageViewer(file).attach(floatView, true); } public ImageViewer(File file) { mFile = file; } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_image; } @Override public void onAttach() { photoView = findViewById(R.id.imageViewerPv); photoView.setImageBitmap(ImageUtils.getBitmap(mFile)); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/image/ImageViewer.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
254
```java package com.blankj.utildebug.debug.tool.appInfo; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class AppInfoDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { int appIconId = AppUtils.getAppIconId(); if (appIconId != 0) return appIconId; return R.drawable.du_ic_debug_app_info_default; } @Override public int getName() { return R.string.du_app_info; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new AppInfoFloatView().show(); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
236
```java package com.blankj.utildebug.debug.tool.appInfo; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class AppInfoFloatView extends BaseContentFloatView<AppInfoFloatView> { private RecyclerView appInfoRv; @Override public int bindTitle() { return R.string.du_app_info; } @Override public int bindContentLayout() { return R.layout.du_debug_app_info; } @Override public void initContentView() { appInfoRv = findViewById(R.id.appInfoRv); BaseItemAdapter<AppInfoItem> adapter = new BaseItemAdapter<>(); adapter.setItems(AppInfoItem.getAppInfoItems()); appInfoRv.setAdapter(adapter); appInfoRv.setLayoutManager(new LinearLayoutManager(getContext())); appInfoRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoFloatView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
286
```java package com.blankj.utildebug.debug.tool.logcat; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/05 * desc : * </pre> */ public class LogcatDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_logcat; } @Override public int getName() { return R.string.du_logcat; } @Override public void onClick(View view) { FloatToast.showShort(FloatToast.WARNING, "Developing..."); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/logcat/LogcatDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
196
```java package com.blankj.utildebug.debug.tool.restartApp; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public class RestartAppDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_restart_app; } @Override public int getName() { return R.string.du_restart_app; } @Override public void onClick(View view) { AppUtils.relaunchApp(true); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/restartApp/RestartAppDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
190
```java package com.blankj.utildebug.debug.tool.appInfo; import android.os.Build; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import java.util.ArrayList; import java.util.List; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class AppInfoItem extends BaseItem<AppInfoItem> { private String mTitle; private String mContent; private OnClickListener mListener; private TextView titleTv; private TextView contentTv; public AppInfoItem(@StringRes int name, String info) { this(name, info, null); } public AppInfoItem(@StringRes int name, String info, OnClickListener listener) { super(R.layout.du_item_base_info); mTitle = StringUtils.getString(name); mContent = info; mListener = listener; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { titleTv = holder.findViewById(R.id.baseInfoTitleTv); contentTv = holder.findViewById(R.id.baseInfoContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (mListener != null) { ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyGlobalDebouncing(holder.itemView, mListener); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.VISIBLE); } else { holder.itemView.setOnTouchListener(null); holder.itemView.setOnClickListener(null); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.GONE); } } public static List<AppInfoItem> getAppInfoItems() { final List<AppInfoItem> appInfoItems = new ArrayList<>(); appInfoItems.add(new AppInfoItem(R.string.du_app_info_pkg_name, AppUtils.getAppPackageName())); appInfoItems.add(new AppInfoItem(R.string.du_app_info_version_name, AppUtils.getAppVersionName())); appInfoItems.add(new AppInfoItem(R.string.du_app_info_version_code, String.valueOf(AppUtils.getAppVersionCode()))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { appInfoItems.add(new AppInfoItem(R.string.du_app_info_min_sdk_version, String.valueOf(AppUtils.getAppMinSdkVersion()))); } appInfoItems.add(new AppInfoItem(R.string.du_app_info_target_sdk_version, String.valueOf(AppUtils.getAppTargetSdkVersion()))); appInfoItems.add(new AppInfoItem(R.string.du_app_info_open_app_info_page, "", new OnClickListener() { @Override public void onClick(View v) { AppUtils.launchAppDetailsSettings(); } })); return appInfoItems; } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
646
```java package com.blankj.utildebug.debug.tool.deviceInfo; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_device_info; } @Override public int getName() { return R.string.du_device_info; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new DeviceInfoFloatView().show(); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
198
```java package com.blankj.utildebug.debug.tool.deviceInfo; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoFloatView extends BaseContentFloatView<DeviceInfoFloatView> { private RecyclerView deviceInfoRv; @Override public int bindTitle() { return R.string.du_device_info; } @Override public int bindContentLayout() { return R.layout.du_debug_device_info; } @Override public void initContentView() { deviceInfoRv = findViewById(R.id.deviceInfoRv); final BaseItemAdapter<DeviceInfoItem> adapter = new BaseItemAdapter<>(); adapter.setItems(DeviceInfoItem.getAppInfoItems()); deviceInfoRv.setAdapter(adapter); deviceInfoRv.setLayoutManager(new LinearLayoutManager(getContext())); deviceInfoRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); getContentView().setOnRefreshListener(deviceInfoRv, new OnRefreshListener() { @Override public void onRefresh(final BaseContentFloatView floatView) { adapter.setItems(DeviceInfoItem.getAppInfoItems()); adapter.notifyDataSetChanged(); floatView.closeRefresh(); } }); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoFloatView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
361
```java package com.blankj.utildebug.debug.tool.deviceInfo; import android.content.Intent; import android.os.Build; import android.provider.Settings; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.ArrayUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.DeviceUtils; import com.blankj.utilcode.util.ScreenUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoItem extends BaseItem<DeviceInfoItem> { private String mTitle; private String mContent; private OnClickListener mListener; private TextView titleTv; private TextView contentTv; public DeviceInfoItem(@StringRes int name, String info) { this(name, info, null); } public DeviceInfoItem(@StringRes int name, String info, OnClickListener listener) { super(R.layout.du_item_base_info); mTitle = StringUtils.getString(name); mContent = info; mListener = listener; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { titleTv = holder.findViewById(R.id.baseInfoTitleTv); contentTv = holder.findViewById(R.id.baseInfoContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (mListener != null) { ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyGlobalDebouncing(holder.itemView, mListener); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.VISIBLE); } else { holder.itemView.setOnTouchListener(null); holder.itemView.setOnClickListener(null); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.GONE); } } public static List<DeviceInfoItem> getAppInfoItems() { List<DeviceInfoItem> appInfoItems = new ArrayList<>(); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_name, Build.MANUFACTURER + " " + Build.MODEL)); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_android_version, DeviceUtils.getSDKVersionName() + " (" + DeviceUtils.getSDKVersionCode() + ")")); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_adb_enabled, String.valueOf(DeviceUtils.isAdbEnabled()))); } appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_support_abis, ArrayUtils.toString(DeviceUtils.getABIs()))); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_screen_info, getScreenInfo())); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_open_development_settings_page, "", new OnClickListener() { @Override public void onClick(View v) { ActivityUtils.startActivity(new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)); } })); return appInfoItems; } private static String getScreenInfo() { return "width=" + ScreenUtils.getScreenWidth() + ", height=" + ScreenUtils.getScreenHeight() + ", density=" + ScreenUtils.getScreenDensity(); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
764
```java package com.blankj.utildebug.debug.tool.clearCache; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.ConvertUtils; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.PathUtils; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utilcode.util.ToastUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; import java.io.File; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/04 * desc : * </pre> */ public class ClearCacheDebug extends AbsToolDebug { private ThreadUtils.SimpleTask<Long> clearCacheTask; @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_clear_cache; } @Override public int getName() { return R.string.du_clear_cache; } @Override public void onClick(View view) { clearCache(); } private void clearCache() { DebugMenu.getInstance().dismiss(); if (clearCacheTask != null && !clearCacheTask.isDone()) { ToastUtils.showShort("Cleaning..."); return; } clearCacheTask = createClearCacheTask(); ThreadUtils.executeByIo(clearCacheTask); } private ThreadUtils.SimpleTask<Long> createClearCacheTask() { return new ThreadUtils.SimpleTask<Long>() { @Override public Long doInBackground() throws Throwable { try { long len = 0; File appDataDir = new File(PathUtils.getInternalAppDataPath()); if (appDataDir.exists()) { String[] names = appDataDir.list(); for (String name : names) { if (!name.equals("lib")) { File file = new File(appDataDir, name); len += FileUtils.getLength(file); FileUtils.delete(file); LogUtils.i("" + file + " was deleted."); } } } String externalAppCachePath = PathUtils.getExternalAppCachePath(); len += FileUtils.getLength(externalAppCachePath); FileUtils.delete(externalAppCachePath); LogUtils.i("" + externalAppCachePath + " was deleted."); return len; } catch (Exception e) { ToastUtils.showLong(e.toString()); return -1L; } } @Override public void onSuccess(Long result) { if (result != -1) { ToastUtils.showLong("Clear Cache: " + ConvertUtils.byte2FitMemorySize(result)); } } }; } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearCache/ClearCacheDebug.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
599
```java package com.blankj.utildebug.config; import android.view.View; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.ScreenUtils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/02 * desc : * </pre> */ public class DebugConfig { private static final String DEBUG_ICON_X = "DEBUG_ICON_X"; private static final String DEBUG_ICON_Y = "DEBUG_ICON_Y"; private static final String NO_MORE_REMINDER = "NO_MORE_REMINDER"; public static void saveDebugIconX(float x) { getSp().put(DEBUG_ICON_X, x); } public static float getDebugIconX() { return getSp().getFloat(DEBUG_ICON_X); } public static void saveDebugIconY(float y) { getSp().put(DEBUG_ICON_Y, y); } public static float getDebugIconY() { return getSp().getFloat(DEBUG_ICON_Y, ScreenUtils.getAppScreenHeight() / 3); } public static void saveNoMoreReminder() { getSp().put(NO_MORE_REMINDER, true); } public static boolean isNoMoreReminder() { return getSp().getBoolean(NO_MORE_REMINDER, false); } public static void saveViewY(View view, int y) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".yP", y); } else { getSp().put(view.getClass().getSimpleName() + ".yL", y); } } public static int getViewY(View view) { return getViewY(view, 0); } public static int getViewY(View view, int defaultVal) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".yP", defaultVal); } else { return getSp().getInt(view.getClass().getSimpleName() + ".yL", defaultVal); } } public static void saveViewX(View view, int x) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".xP", x); } else { getSp().put(view.getClass().getSimpleName() + ".xL", x); } } public static int getViewX(View view) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".xP"); } else { return getSp().getInt(view.getClass().getSimpleName() + ".xL"); } } public static void saveViewHeight(View view, int height) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".heightP", height); } else { getSp().put(view.getClass().getSimpleName() + ".heightL", height); } } public static int getViewHeight(View view, int height) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".heightP", height); } else { return getSp().getInt(view.getClass().getSimpleName() + ".heightL", height); } } public static void saveViewAlpha(View view, float alpha) { getSp().put(view.getClass().getSimpleName() + ".alpha", alpha); } public static float getViewAlpha(View view) { return getSp().getFloat(view.getClass().getSimpleName() + ".alpha", 1f); } private static SPUtils getSp() { return SPUtils.getInstance("DebugUtils"); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/config/DebugConfig.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
784
```java package com.blankj.utildebug.icon; import android.content.res.Configuration; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import com.blankj.utilcode.util.BarUtils; import com.blankj.utilcode.util.PermissionUtils; import com.blankj.utilcode.util.ToastUtils; import com.blankj.utilcode.util.TouchUtils; import com.blankj.utildebug.DebugUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.config.DebugConfig; import com.blankj.utildebug.helper.ShadowHelper; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/26 * desc : * </pre> */ public class DebugIcon extends RelativeLayout { private static final DebugIcon INSTANCE = new DebugIcon(); private int mIconId; public static DebugIcon getInstance() { return INSTANCE; } public static void setVisibility(boolean isShow) { if (INSTANCE == null) return; INSTANCE.setVisibility(isShow ? VISIBLE : GONE); } public DebugIcon() { super(DebugUtils.getApp()); inflate(getContext(), R.layout.du_debug_icon, this); ShadowHelper.applyDebugIcon(this); TouchUtils.setOnTouchListener(this, new TouchUtils.OnTouchUtilsListener() { private int rootViewWidth; private int rootViewHeight; private int viewWidth; private int viewHeight; private int statusBarHeight; @Override public boolean onDown(View view, int x, int y, MotionEvent event) { viewWidth = view.getWidth(); viewHeight = view.getHeight(); View contentView = view.getRootView().findViewById(android.R.id.content); rootViewWidth = contentView.getWidth(); rootViewHeight = contentView.getHeight(); statusBarHeight = BarUtils.getStatusBarHeight(); processScale(view, true); return true; } @Override public boolean onMove(View view, int direction, int x, int y, int dx, int dy, int totalX, int totalY, MotionEvent event) { view.setX(Math.min(Math.max(0, view.getX() + dx), rootViewWidth - viewWidth)); view.setY(Math.min(Math.max(statusBarHeight, view.getY() + dy), rootViewHeight - viewHeight)); return true; } @Override public boolean onStop(View view, int direction, int x, int y, int totalX, int totalY, int vx, int vy, MotionEvent event) { stick2HorizontalSide(view); processScale(view, false); return true; } private void stick2HorizontalSide(View view) { view.animate() .setInterpolator(new DecelerateInterpolator()) .translationX(view.getX() + viewWidth / 2f > rootViewWidth / 2f ? rootViewWidth - viewWidth : 0) .setDuration(100) .withEndAction(new Runnable() { @Override public void run() { savePosition(); } }) .start(); } private void processScale(final View view, boolean isDown) { float value = isDown ? 1 - 0.1f : 1; view.animate() .scaleX(value) .scaleY(value) .setDuration(100) .start(); } }); setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestDrawOverlays(new PermissionUtils.SimpleCallback() { @Override public void onGranted() { DebugMenu.getInstance().show(); } @Override public void onDenied() { ToastUtils.showLong(R.string.de_permission_tips); } }); } else { DebugMenu.getInstance().show(); } } }); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); wrapPosition(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); savePosition(); } private void savePosition() { DebugConfig.saveViewX(this, (int) getX()); DebugConfig.saveViewY(this, (int) getY()); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); wrapPosition(); } private void wrapPosition() { post(new Runnable() { @Override public void run() { View contentView = getRootView().findViewById(android.R.id.content); if (contentView == null) return; setX(DebugConfig.getViewX(DebugIcon.this)); setY(DebugConfig.getViewY(DebugIcon.this, contentView.getHeight() / 3)); setX(getX() + getWidth() / 2f > contentView.getWidth() / 2f ? contentView.getWidth() - getWidth() : 0); } }); } public void setIconId(final int iconId) { ImageView debugPanelIconIv = findViewById(R.id.debugIconIv); debugPanelIconIv.setImageResource(mIconId); } public int getIconId() { return mIconId; } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/icon/DebugIcon.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
1,133
```java package com.blankj.utildebug.menu; import android.widget.TextView; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.helper.ShadowHelper; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/29 * desc : * </pre> */ public class DebugMenuItem extends BaseItem<DebugMenuItem> { private String mTitle; private List<IDebug> mDebugs; private DebugMenuItem(String title, List<IDebug> debugs) { super(R.layout.du_item_menu); mTitle = title; mDebugs = debugs; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { TextView menuTitle = holder.findViewById(R.id.menuCategory); RecyclerView menuRv = holder.findViewById(R.id.menuRv); ShadowHelper.applyMenu(holder.itemView); menuTitle.setText(mTitle); BaseItemAdapter<DebugItem> adapter = new BaseItemAdapter<>(); adapter.setItems(DebugItem.getDebugItems(mDebugs)); menuRv.setAdapter(adapter); menuRv.setLayoutManager(new GridLayoutManager(menuRv.getContext(), 4)); } public static List<DebugMenuItem> getDebugMenuItems(List<IDebug> debugs) { Map<Integer, List<IDebug>> debugMap = new LinkedHashMap<>(); for (IDebug debug : debugs) { List<IDebug> debugList = debugMap.get(debug.getCategory()); if (debugList == null) { debugList = new ArrayList<>(); debugMap.put(debug.getCategory(), debugList); } debugList.add(debug); } List<DebugMenuItem> itemList = new ArrayList<>(); for (Map.Entry<Integer, List<IDebug>> entry : debugMap.entrySet()) { itemList.add(new DebugMenuItem(getCategoryString(entry.getKey()), entry.getValue())); } return itemList; } private static String getCategoryString(int category) { switch (category) { case IDebug.TOOLS: return StringUtils.getString(R.string.du_tools); case IDebug.PERFORMANCE: return StringUtils.getString(R.string.du_performance); case IDebug.UI: return StringUtils.getString(R.string.du_ui); case IDebug.BIZ: return StringUtils.getString(R.string.du_biz); default: return StringUtils.getString(R.string.du_uncategorized); } } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenuItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
612
```java package com.blankj.utildebug.menu; import android.widget.Switch; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.config.DebugConfig; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/10 * desc : * </pre> */ public class ReminderView extends BaseContentFloatView<ReminderView> { private Switch reminderNoMoreSwitch; @Override public int bindTitle() { return R.string.du_reminder; } @Override public int bindContentLayout() { return R.layout.du_reminder_view; } @Override public void initContentView() { reminderNoMoreSwitch = findViewById(R.id.reminderNoMoreSwitch); } @Override public void dismiss() { super.dismiss(); if (reminderNoMoreSwitch.isChecked()) { DebugConfig.saveNoMoreReminder(); } } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/menu/ReminderView.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
223
```java package com.blankj.utildebug.menu; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.drawable.PolygonDrawable; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.debug.IDebug; import java.util.List; import java.util.Random; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/29 * desc : * </pre> */ public class DebugItem extends BaseItem<DebugItem> { private IDebug mDebug; private int mColor = getRandomColor(); private DebugItem(IDebug debug) { super(R.layout.du_item_menu_item); mDebug = debug; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { ImageView menuItemIconIv = holder.findViewById(R.id.menuItemIconIv); TextView menuItemNameTv = holder.findViewById(R.id.menuItemNameTv); ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyPressedViewScale(holder.itemView); menuItemIconIv.setBackgroundDrawable(new PolygonDrawable(5, mColor)); menuItemIconIv.setImageResource(mDebug.getIcon()); menuItemNameTv.setText(StringUtils.getString(mDebug.getName())); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDebug.onClick(v); } }); } public static List<DebugItem> getDebugItems(List<IDebug> debugs) { return (List<DebugItem>) CollectionUtils.collect(debugs, new CollectionUtils.Transformer<IDebug, DebugItem>() { @Override public DebugItem transform(IDebug input) { return new DebugItem(input); } }); } private static final Random RANDOM = new Random(); private static int getRandomColor() { return ColorUtils.getColor(COLORS[RANDOM.nextInt(6)]); } private static final int[] COLORS = new int[]{ R.color.bittersweet, R.color.sunflower, R.color.grass, R.color.blueJeans, R.color.lavander, R.color.pinkRose }; } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugItem.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
533
```java package com.blankj.utildebug.menu; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.config.DebugConfig; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.icon.DebugIcon; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/29 * desc : * </pre> */ public class DebugMenu extends BaseContentFloatView<DebugMenu> { private static final DebugMenu INSTANCE = new DebugMenu(); private List<IDebug> mDebugs; private BaseItemAdapter<DebugMenuItem> mAdapter; private RecyclerView debugMenuRv; public static DebugMenu getInstance() { return INSTANCE; } @Override public int bindTitle() { return R.string.du_menus; } @Override public int bindContentLayout() { return R.layout.du_debug_menu; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); DebugIcon.setVisibility(false); if (!DebugConfig.isNoMoreReminder()) { new ReminderView().show(); } } @Override protected void onDetachedFromWindow() { int a = 0xe1; DebugIcon.setVisibility(true); super.onDetachedFromWindow(); } @Override public void initContentView() { setSwipeBackEnabled(false); debugMenuRv = findViewById(R.id.debugMenuRv); mAdapter = new BaseItemAdapter<>(); mAdapter.setItems(DebugMenuItem.getDebugMenuItems(mDebugs)); debugMenuRv.setAdapter(mAdapter); debugMenuRv.setLayoutManager(new LinearLayoutManager(getContext())); } public void setDebugs(List<IDebug> debugs) { mDebugs = debugs; } public void addDebugs(List<IDebug> debugs) { if (debugs == null || debugs.size() == 0) return; mDebugs.addAll(debugs); if (mAdapter == null) return; mAdapter.notifyDataSetChanged(); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenu.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
493
```java package com.blankj.utildebug.helper; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import com.blankj.utilcode.util.ScreenUtils; import com.blankj.utilcode.util.Utils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/08/29 * desc : * </pre> */ public class WindowHelper { private static WindowManager sWM; private WindowHelper() { } public static void updateViewLayout(final View view, ViewGroup.LayoutParams params) { getWindowManager().updateViewLayout(view, params); } public static int getAppWindowHeight() { return ScreenUtils.getAppScreenHeight(); } public static WindowManager getWindowManager() { if (sWM == null) { sWM = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE); } return sWM; } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/helper/WindowHelper.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
205
```java package com.blankj.utildebug.helper; import android.graphics.Bitmap; import android.widget.ImageView; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.ImageUtils; import com.blankj.utilcode.util.ThreadUtils; import java.io.File; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/06 * desc : * </pre> */ public class ImageLoader { public static void load(final String path, final ImageView imageView) { load(FileUtils.getFileByPath(path), imageView); } public static void load(final File file, final ImageView imageView) { if (!FileUtils.isFileExists(file)) return; imageView.post(new Runnable() { @Override public void run() { ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() { @Override public Bitmap doInBackground() throws Throwable { return ImageUtils.getBitmap(file, imageView.getWidth(), imageView.getHeight()); } @Override public void onSuccess(final Bitmap result) { imageView.setImageBitmap(result); } }); } }); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/helper/ImageLoader.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
244
```java package com.blankj.utildebug.helper; import android.view.View; import com.blankj.utilcode.util.ShadowUtils; import com.blankj.utilcode.util.SizeUtils; /** * <pre> * author: blankj * blog : path_to_url * time : 2019/09/16 * desc : * </pre> */ public class ShadowHelper { public static void applyDebugIcon(View view) { ShadowUtils.apply(view, new ShadowUtils.Config() .setCircle() .setShadowColor(0xc0_ffffff, 0x60_ffffff) ); } public static void applyFloatView(View view) { ShadowUtils.apply(view, new ShadowUtils.Config().setShadowRadius(SizeUtils.dp2px(8))); } public static void applyMenu(View view) { ShadowUtils.apply(view, new ShadowUtils.Config() .setShadowRadius(SizeUtils.dp2px(4)) ); } } ```
/content/code_sandbox/lib/utildebug/src/main/java/com/blankj/utildebug/helper/ShadowHelper.java
java
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
208