1 // Copyright (c) 2010 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 #include "android/jni/jni_utils.h"
6 #include "base/logging.h"
7 #include "base/utf_string_conversions.h"
8 #include "jni.h"
9
10 namespace {
11 JavaVM* sVM = NULL;
12
getJavaVM()13 JavaVM* getJavaVM() {
14 return sVM;
15 }
16 }
17
18 namespace android {
19 namespace jni {
20
21 // All JNI code assumes this has previously been called with a valid VM
SetJavaVM(JavaVM * vm)22 void SetJavaVM(JavaVM* vm)
23 {
24 sVM = vm;
25 }
26
checkException(JNIEnv * env)27 bool checkException(JNIEnv* env)
28 {
29 if (env->ExceptionCheck() != 0)
30 {
31 LOG(ERROR) << "*** Uncaught exception returned from Java call!\n";
32 env->ExceptionDescribe();
33 return true;
34 }
35 return false;
36 }
37
jstringToString16(JNIEnv * env,jstring jstr)38 string16 jstringToString16(JNIEnv* env, jstring jstr)
39 {
40 if (!jstr || !env)
41 return string16();
42
43 const char* s = env->GetStringUTFChars(jstr, 0);
44 if (!s)
45 return string16();
46 string16 str = UTF8ToUTF16(s);
47 env->ReleaseStringUTFChars(jstr, s);
48 checkException(env);
49 return str;
50 }
51
jstringToStdString(JNIEnv * env,jstring jstr)52 std::string jstringToStdString(JNIEnv* env, jstring jstr)
53 {
54 if (!jstr || !env)
55 return std::string();
56
57 const char* s = env->GetStringUTFChars(jstr, 0);
58 if (!s)
59 return std::string();
60 std::string str(s);
61 env->ReleaseStringUTFChars(jstr, s);
62 checkException(env);
63 return str;
64 }
65
GetJNIEnv()66 JNIEnv* GetJNIEnv() {
67 JNIEnv* env;
68 getJavaVM()->AttachCurrentThread(&env, NULL);
69 return env;
70 }
71
JstringToStdString(JNIEnv * env,jstring jstr)72 std::string JstringToStdString(JNIEnv* env, jstring jstr) {
73 return jstringToStdString(env, jstr);
74 }
75
JstringToString16(JNIEnv * env,jstring jstr)76 string16 JstringToString16(JNIEnv* env, jstring jstr)
77 {
78 return jstringToString16(env, jstr);
79 }
80
CheckException(JNIEnv * env)81 bool CheckException(JNIEnv* env)
82 {
83 return checkException(env);
84 }
85
ConvertUTF8ToJavaString(JNIEnv * env,std::string str)86 jstring ConvertUTF8ToJavaString(JNIEnv* env, std::string str)
87 {
88 return env->NewStringUTF(str.c_str());
89 }
90
DetachFromVM()91 void DetachFromVM()
92 {
93 JavaVM* vm = getJavaVM();
94 vm->DetachCurrentThread();
95 }
96
97 } // namespace jni
98 } // namespace android
99
100