1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.test.storagedelegator;
18 
19 import android.app.Activity;
20 import android.os.Bundle;
21 import android.os.RemoteCallback;
22 import android.util.Log;
23 
24 import java.io.File;
25 import java.io.IOException;
26 import java.nio.file.Files;
27 
28 /**
29  * Writes file content for use in tests. This is needed to create files when the test does not have
30  * sufficient permission.
31  */
32 public class StorageDelegator extends Activity {
33 
34     private static final String TAG = "StorageDelegator";
35     private static final String EXTRA_PATH = "path";
36     private static final String EXTRA_CONTENTS = "contents";
37     private static final String EXTRA_CALLBACK = "callback";
38     private static final String KEY_ERROR = "error";
39     private static final String ACTION_CREATE_FILE_WITH_CONTENT =
40             "com.android.cts.action.CREATE_FILE_WITH_CONTENT";
41 
42     @Override
onCreate(Bundle savedInstanceState)43     public void onCreate(Bundle savedInstanceState) {
44         super.onCreate(savedInstanceState);
45         if (!getIntent().getAction().equals(ACTION_CREATE_FILE_WITH_CONTENT)) {
46             Log.w(TAG, "Unsupported action: " + getIntent().getAction());
47             finish();
48             return;
49         }
50 
51         final String path = getIntent().getStringExtra(EXTRA_PATH);
52         final String contents = getIntent().getStringExtra(EXTRA_CONTENTS);
53         Log.i(TAG, "onHandleIntent: path=" + path + ", content=" + contents);
54 
55         final File file = new File(path);
56         if (file.getParentFile() != null) {
57             file.getParentFile().mkdirs();
58         }
59 
60         final Bundle result = new Bundle();
61         try {
62             Files.write(file.toPath(), contents.getBytes());
63             Log.i(TAG, "onHandleIntent: path=" + path + ", length=" + file.length());
64         } catch (IOException e) {
65             Log.e(TAG, "writing file: " + path, e);
66             result.putString(KEY_ERROR, e.getMessage());
67         }
68         sendResult(result);
69         finish();
70     }
71 
sendResult(Bundle result)72     void sendResult(Bundle result) {
73         getIntent().<RemoteCallback>getParcelableExtra(EXTRA_CALLBACK).sendResult(result);
74     }
75 }
76