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