• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 
17 package com.google.android.mobly.snippet.bundled;
18 
19 import android.content.Context;
20 import android.net.Uri;
21 import android.os.ParcelFileDescriptor;
22 import androidx.test.platform.app.InstrumentationRegistry;
23 import com.google.android.mobly.snippet.Snippet;
24 import com.google.android.mobly.snippet.bundled.utils.Utils;
25 import com.google.android.mobly.snippet.rpc.Rpc;
26 import java.io.IOException;
27 import java.security.DigestInputStream;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 
31 /** Snippet class for File and abstract storage URI operation RPCs. */
32 public class FileSnippet implements Snippet {
33 
34     private final Context mContext;
35 
FileSnippet()36     public FileSnippet() {
37         mContext = InstrumentationRegistry.getInstrumentation().getContext();
38     }
39 
40     @Rpc(description = "Compute MD5 hash on a content URI. Return the MD5 has has a hex string.")
fileMd5Hash(String uri)41     public String fileMd5Hash(String uri) throws IOException, NoSuchAlgorithmException {
42         Uri uri_ = Uri.parse(uri);
43         ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri_, "r");
44         MessageDigest md = MessageDigest.getInstance("MD5");
45         int length = (int) pfd.getStatSize();
46         byte[] buf = new byte[length];
47         ParcelFileDescriptor.AutoCloseInputStream stream =
48                 new ParcelFileDescriptor.AutoCloseInputStream(pfd);
49         DigestInputStream dis = new DigestInputStream(stream, md);
50         try {
51             dis.read(buf, 0, length);
52             return Utils.bytesToHexString(md.digest());
53         } finally {
54             dis.close();
55             stream.close();
56         }
57     }
58 
59     @Rpc(description = "Remove a file pointed to by the content URI.")
fileDeleteContent(String uri)60     public void fileDeleteContent(String uri) {
61         Uri uri_ = Uri.parse(uri);
62         mContext.getContentResolver().delete(uri_, null, null);
63     }
64 
65     @Override
shutdown()66     public void shutdown() {}
67 }
68