Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  * Copyright (C) 2017 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 #ifndef CONSCRYPT_BIO_OUTPUT_STREAM_H_
     18 #define CONSCRYPT_BIO_OUTPUT_STREAM_H_
     19 
     20 #include <jni.h>
     21 
     22 #include <conscrypt/bio_stream.h>
     23 
     24 namespace conscrypt {
     25 
     26 class BioOutputStream : public BioStream {
     27  public:
     28     explicit BioOutputStream(jobject stream) : BioStream(stream) {}
     29 
     30     int write(const char* buf, int len) {
     31         JNIEnv* env = jniutil::getJNIEnv();
     32         if (env == nullptr) {
     33             JNI_TRACE("BioOutputStream::write => could not get JNIEnv");
     34             return -1;
     35         }
     36 
     37         if (env->ExceptionCheck()) {
     38             JNI_TRACE("BioOutputStream::write => called with pending exception");
     39             return -1;
     40         }
     41 
     42         ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
     43         if (javaBytes.get() == nullptr) {
     44             JNI_TRACE("BioOutputStream::write => failed call to NewByteArray");
     45             return -1;
     46         }
     47 
     48         env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
     49 
     50         env->CallVoidMethod(getStream(), jniutil::outputStream_writeMethod, javaBytes.get());
     51         if (env->ExceptionCheck()) {
     52             JNI_TRACE("BioOutputStream::write => failed call to OutputStream#write");
     53             return -1;
     54         }
     55 
     56         return len;
     57     }
     58 };
     59 
     60 }  // namespace conscrypt
     61 
     62 #endif  // CONSCRYPT_BIO_OUTPUT_STREAM_H_
     63