1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 #include "JniConstants.h" 19 #include "JniException.h" 20 #include "UniquePtr.h" 21 #include "ZipUtilities.h" 22 23 void throwExceptionForZlibError(JNIEnv* env, const char* exceptionClassName, int error, 24 NativeZipStream* stream) { 25 if (error == Z_MEM_ERROR) { 26 jniThrowOutOfMemoryError(env, NULL); 27 } else if (stream != NULL && stream->stream.msg != NULL) { 28 jniThrowException(env, exceptionClassName, stream->stream.msg); 29 } else { 30 jniThrowException(env, exceptionClassName, zError(error)); 31 } 32 } 33 34 NativeZipStream::NativeZipStream() : input(NULL), inCap(0), mDict(NULL) { 35 // Let zlib use its default allocator. 36 stream.opaque = Z_NULL; 37 stream.zalloc = Z_NULL; 38 stream.zfree = Z_NULL; 39 } 40 41 NativeZipStream::~NativeZipStream() { 42 } 43 44 void NativeZipStream::setDictionary(JNIEnv* env, jbyteArray javaDictionary, int off, int len, 45 bool inflate) { 46 UniquePtr<jbyte[]> dictionaryBytes(new jbyte[len]); 47 if (dictionaryBytes.get() == NULL) { 48 jniThrowOutOfMemoryError(env, NULL); 49 return; 50 } 51 env->GetByteArrayRegion(javaDictionary, off, len, &dictionaryBytes[0]); 52 const Bytef* dictionary = reinterpret_cast<const Bytef*>(&dictionaryBytes[0]); 53 int err; 54 if (inflate) { 55 err = inflateSetDictionary(&stream, dictionary, len); 56 } else { 57 err = deflateSetDictionary(&stream, dictionary, len); 58 } 59 if (err != Z_OK) { 60 throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err, NULL); 61 return; 62 } 63 mDict.reset(dictionaryBytes.release()); 64 } 65 66 void NativeZipStream::setInput(JNIEnv* env, jbyteArray buf, jint off, jint len) { 67 input.reset(new jbyte[len]); 68 if (input.get() == NULL) { 69 inCap = 0; 70 jniThrowOutOfMemoryError(env, NULL); 71 return; 72 } 73 inCap = len; 74 if (buf != NULL) { 75 env->GetByteArrayRegion(buf, off, len, &input[0]); 76 } 77 stream.next_in = reinterpret_cast<Bytef*>(&input[0]); 78 stream.avail_in = len; 79 } 80 81 NativeZipStream* toNativeZipStream(jlong address) { 82 return reinterpret_cast<NativeZipStream*>(static_cast<uintptr_t>(address)); 83 } 84