1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.android_webview.permission; 6 7 import android.net.Uri; 8 import android.util.Log; 9 10 import org.chromium.base.CalledByNative; 11 import org.chromium.base.JNINamespace; 12 import org.chromium.base.ThreadUtils; 13 14 /** 15 * This class wraps permission request in Chromium side, and can only be created 16 * by native side. 17 */ 18 @JNINamespace("android_webview") 19 public class AwPermissionRequest { 20 private static final String TAG = "AwPermissionRequest"; 21 22 private Uri mOrigin; 23 private long mResources; 24 private boolean mProcessed; 25 26 // AwPermissionRequest native instance. 27 private long mNativeAwPermissionRequest; 28 29 @CalledByNative create(long nativeAwPermissionRequest, String url, long resources)30 private static AwPermissionRequest create(long nativeAwPermissionRequest, String url, 31 long resources) { 32 if (nativeAwPermissionRequest == 0) return null; 33 Uri origin = Uri.parse(url); 34 return new AwPermissionRequest(nativeAwPermissionRequest, origin, resources); 35 } 36 AwPermissionRequest(long nativeAwPermissionRequest, Uri origin, long resources)37 private AwPermissionRequest(long nativeAwPermissionRequest, Uri origin, 38 long resources) { 39 mNativeAwPermissionRequest = nativeAwPermissionRequest; 40 mOrigin = origin; 41 mResources = resources; 42 } 43 getOrigin()44 public Uri getOrigin() { 45 return mOrigin; 46 } 47 getResources()48 public long getResources() { 49 return mResources; 50 } 51 grant()52 public void grant() { 53 validate(); 54 if (mNativeAwPermissionRequest != 0) 55 nativeOnAccept(mNativeAwPermissionRequest, true); 56 mProcessed = true; 57 } 58 deny()59 public void deny() { 60 validate(); 61 if (mNativeAwPermissionRequest != 0) 62 nativeOnAccept(mNativeAwPermissionRequest, false); 63 mProcessed = true; 64 } 65 66 @CalledByNative detachNativeInstance()67 private void detachNativeInstance() { 68 mNativeAwPermissionRequest = 0; 69 } 70 71 @Override finalize()72 protected void finalize() throws Throwable { 73 if (mNativeAwPermissionRequest == 0) return; 74 Log.e(TAG, "Neither grant() nor deny() has been called, " 75 + "the permission request is denied by default."); 76 deny(); 77 } 78 validate()79 private void validate() { 80 if (!ThreadUtils.runningOnUiThread()) 81 throw new IllegalStateException( 82 "Either grant() or deny() should be called on UI thread"); 83 84 if (mProcessed) 85 throw new IllegalStateException("Either grant() or deny() has been already called."); 86 } 87 nativeOnAccept(long nativeAwPermissionRequest, boolean allowed)88 private native void nativeOnAccept(long nativeAwPermissionRequest, boolean allowed); 89 } 90