1 /*
2 * Copyright (C) 2013 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 #define LOG_TAG "IcuUtilities"
18
19 #include <android/log.h>
20 #include <nativehelper/JNIHelp.h>
21 #include <nativehelper/ScopedLocalRef.h>
22 #include <nativehelper/ScopedUtfChars.h>
23
24 #include "IcuUtilities.h"
25
26 #include "JniConstants.h"
27 #include "JniException.h"
28 #include "unicode/strenum.h"
29 #include "unicode/ustring.h"
30 #include "unicode/uloc.h"
31
fromStringEnumeration(JNIEnv * env,UErrorCode & status,const char * provider,icu::StringEnumeration * se)32 jobjectArray fromStringEnumeration(JNIEnv* env, UErrorCode& status, const char* provider, icu::StringEnumeration* se) {
33 if (maybeThrowIcuException(env, provider, status)) {
34 return NULL;
35 }
36
37 int32_t count = se->count(status);
38 if (maybeThrowIcuException(env, "StringEnumeration::count", status)) {
39 return NULL;
40 }
41
42 jobjectArray result = env->NewObjectArray(count, JniConstants::GetStringClass(env), NULL);
43 for (int32_t i = 0; i < count; ++i) {
44 const icu::UnicodeString* string = se->snext(status);
45 if (maybeThrowIcuException(env, "StringEnumeration::snext", status)) {
46 return NULL;
47 }
48 ScopedLocalRef<jstring> javaString(env, jniCreateString(env, string->getBuffer(), string->length()));
49 env->SetObjectArrayElement(result, i, javaString.get());
50 }
51 return result;
52 }
53
maybeThrowIcuException(JNIEnv * env,const char * function,UErrorCode error)54 bool maybeThrowIcuException(JNIEnv* env, const char* function, UErrorCode error) {
55 if (U_SUCCESS(error)) {
56 return false;
57 }
58 const char* exceptionClass = "java/lang/RuntimeException";
59 if (error == U_ILLEGAL_ARGUMENT_ERROR) {
60 exceptionClass = "java/lang/IllegalArgumentException";
61 } else if (error == U_INDEX_OUTOFBOUNDS_ERROR || error == U_BUFFER_OVERFLOW_ERROR) {
62 exceptionClass = "java/lang/ArrayIndexOutOfBoundsException";
63 } else if (error == U_UNSUPPORTED_ERROR) {
64 exceptionClass = "java/lang/UnsupportedOperationException";
65 } else if (error == U_FORMAT_INEXACT_ERROR) {
66 exceptionClass = "java/lang/ArithmeticException";
67 }
68 jniThrowExceptionFmt(env, exceptionClass, "%s failed: %s", function, u_errorName(error));
69 return true;
70 }
71