1 /* 2 * Copyright (C) 2010 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 "NativeIDN" 18 19 #include "JNIHelp.h" 20 #include "JniConstants.h" 21 #include "ScopedStringChars.h" 22 #include "unicode/uidna.h" 23 24 static bool isLabelSeparator(const UChar ch) { 25 switch (ch) { 26 case 0x3002: // ideographic full stop 27 case 0xff0e: // fullwidth full stop 28 case 0xff61: // halfwidth ideographic full stop 29 return true; 30 default: 31 return false; 32 } 33 } 34 35 static jstring NativeIDN_convertImpl(JNIEnv* env, jclass, jstring javaSrc, jint flags, jboolean toAscii) { 36 ScopedStringChars src(env, javaSrc); 37 if (src.get() == NULL) { 38 return NULL; 39 } 40 UChar dst[256]; 41 UErrorCode status = U_ZERO_ERROR; 42 size_t resultLength = toAscii 43 ? uidna_IDNToASCII(src.get(), src.size(), &dst[0], sizeof(dst), flags, NULL, &status) 44 : uidna_IDNToUnicode(src.get(), src.size(), &dst[0], sizeof(dst), flags, NULL, &status); 45 if (U_FAILURE(status)) { 46 jniThrowException(env, "java/lang/IllegalArgumentException", u_errorName(status)); 47 return NULL; 48 } 49 if (!toAscii) { 50 // ICU only translates separators to ASCII for toASCII. 51 // Java expects the translation for toUnicode too. 52 // We may as well do this here, while the string is still mutable. 53 for (size_t i = 0; i < resultLength; ++i) { 54 if (isLabelSeparator(dst[i])) { 55 dst[i] = '.'; 56 } 57 } 58 } 59 return env->NewString(&dst[0], resultLength); 60 } 61 62 static JNINativeMethod gMethods[] = { 63 NATIVE_METHOD(NativeIDN, convertImpl, "(Ljava/lang/String;IZ)Ljava/lang/String;"), 64 }; 65 void register_libcore_icu_NativeIDN(JNIEnv* env) { 66 jniRegisterNativeMethods(env, "libcore/icu/NativeIDN", gMethods, NELEM(gMethods)); 67 } 68