android_media_Utils.cpp revision 79f407cc6c5ae34fc6f04d52fd034b49d1f002c4
1/*
2 * Copyright 2011, 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_NDEBUG 0
18#define LOG_TAG "AndroidMediaUtils"
19
20#include <utils/Log.h>
21#include "android_media_Utils.h"
22
23namespace android {
24
25bool ConvertKeyValueArraysToKeyedVector(
26        JNIEnv *env, jobjectArray keys, jobjectArray values,
27        KeyedVector<String8, String8>* keyedVector) {
28
29    int nKeyValuePairs = 0;
30    bool failed = false;
31    if (keys != NULL && values != NULL) {
32        nKeyValuePairs = env->GetArrayLength(keys);
33        failed = (nKeyValuePairs != env->GetArrayLength(values));
34    }
35
36    if (!failed) {
37        failed = ((keys != NULL && values == NULL) ||
38                  (keys == NULL && values != NULL));
39    }
40
41    if (failed) {
42        LOGE("keys and values arrays have different length");
43        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
44        return false;
45    }
46
47    for (int i = 0; i < nKeyValuePairs; ++i) {
48        // No need to check on the ArrayIndexOutOfBoundsException, since
49        // it won't happen here.
50        jstring key = (jstring) env->GetObjectArrayElement(keys, i);
51        jstring value = (jstring) env->GetObjectArrayElement(values, i);
52
53        const char* keyStr = env->GetStringUTFChars(key, NULL);
54        if (!keyStr) {  // OutOfMemoryError
55            return false;
56        }
57
58        const char* valueStr = env->GetStringUTFChars(value, NULL);
59        if (!valueStr) {  // OutOfMemoryError
60            env->ReleaseStringUTFChars(key, keyStr);
61            return false;
62        }
63
64        keyedVector->add(String8(keyStr), String8(valueStr));
65
66        env->ReleaseStringUTFChars(key, keyStr);
67        env->ReleaseStringUTFChars(value, valueStr);
68        env->DeleteLocalRef(key);
69        env->DeleteLocalRef(value);
70    }
71    return true;
72}
73
74}  // namespace android
75
76