java_util_regex_Pattern.cpp revision bef9ec33e1368f57c731fce63b6a8c61628c64b0
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 "Pattern" 18 19#include <stdlib.h> 20 21#include "JNIHelp.h" 22#include "JniConstants.h" 23#include "ScopedJavaUnicodeString.h" 24#include "jni.h" 25#include "unicode/parseerr.h" 26#include "unicode/regex.h" 27 28// ICU documentation: http://icu-project.org/apiref/icu4c/classRegexPattern.html 29 30static RegexPattern* toRegexPattern(jint addr) { 31 return reinterpret_cast<RegexPattern*>(static_cast<uintptr_t>(addr)); 32} 33 34static void throwPatternSyntaxException(JNIEnv* env, UErrorCode status, jstring pattern, UParseError error) { 35 static jmethodID method = env->GetMethodID(JniConstants::patternSyntaxExceptionClass, 36 "<init>", "(Ljava/lang/String;Ljava/lang/String;I)V"); 37 jstring message = env->NewStringUTF(u_errorName(status)); 38 jclass exceptionClass = JniConstants::patternSyntaxExceptionClass; 39 jobject exception = env->NewObject(exceptionClass, method, message, pattern, error.offset); 40 env->Throw(reinterpret_cast<jthrowable>(exception)); 41} 42 43static void Pattern_closeImpl(JNIEnv*, jclass, jint addr) { 44 delete toRegexPattern(addr); 45} 46 47static jint Pattern_compileImpl(JNIEnv* env, jclass, jstring javaRegex, jint flags) { 48 flags |= UREGEX_ERROR_ON_UNKNOWN_ESCAPES; 49 50 UErrorCode status = U_ZERO_ERROR; 51 UParseError error; 52 error.offset = -1; 53 54 ScopedJavaUnicodeString regex(env, javaRegex); 55 UnicodeString& regexString(regex.unicodeString()); 56 RegexPattern* result = RegexPattern::compile(regexString, flags, error, status); 57 if (!U_SUCCESS(status)) { 58 throwPatternSyntaxException(env, status, javaRegex, error); 59 } 60 return static_cast<jint>(reinterpret_cast<uintptr_t>(result)); 61} 62 63static JNINativeMethod gMethods[] = { 64 NATIVE_METHOD(Pattern, closeImpl, "(I)V"), 65 NATIVE_METHOD(Pattern, compileImpl, "(Ljava/lang/String;I)I"), 66}; 67int register_java_util_regex_Pattern(JNIEnv* env) { 68 return jniRegisterNativeMethods(env, "java/util/regex/Pattern", gMethods, NELEM(gMethods)); 69} 70