All Downloads are FREE. Search and download functionalities are using the official Maven repository.

one.nio.net.native.jni_util.c Maven / Gradle / Ivy

/*
 * Copyright 2015 Odnoklassniki Ltd, Mail.Ru Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include 
#include 
#include 


jfieldID cache_field(JNIEnv* env, const char* holder, const char* field, const char* signature) {
    jclass cls = (*env)->FindClass(env, holder);
    return (*env)->GetFieldID(env, cls, field, signature);
}

int array_equals(JNIEnv* env, jbyteArray array, void* buf, int buflen) {
    int len = (*env)->GetArrayLength(env, array);
    if (len != buflen) {
        return 0;
    }

    jbyte* data = (*env)->GetByteArrayElements(env, array, NULL);
    int result = memcmp(data, buf, buflen);
    (*env)->ReleaseByteArrayElements(env, array, data, JNI_ABORT);
    return result == 0;
}

void throw_by_name(JNIEnv* env, const char* exception, const char* msg) {
    jclass cls = (*env)->FindClass(env, exception);
    if (cls != NULL) {
        (*env)->ThrowNew(env, cls, msg);
    }
}

void throw_socket_closed(JNIEnv* env) {
    throw_by_name(env, "one/nio/net/SocketClosedException", "Socket closed");
}

void throw_io_exception(JNIEnv* env) {
    int error_code = errno;
    switch (error_code) {
        case ETIMEDOUT:
        case EINPROGRESS:
        case EWOULDBLOCK:
            throw_by_name(env, "java/net/SocketTimeoutException", "Connection timed out");
            break;
        case ECONNABORTED:
        case ECONNRESET:
            throw_by_name(env, "java/net/SocketException", "Connection reset");
            break;
        case EPIPE:
            throw_by_name(env, "java/net/SocketException", "Broken pipe");
            break;
        case ECONNREFUSED:
            throw_by_name(env, "java/net/ConnectException", "Connection refused");
            break;
        case EADDRINUSE:
            throw_by_name(env, "java/net/BindException", "Address already in use");
            break;
        case EHOSTUNREACH:
            throw_by_name(env, "java/net/NoRouteToHostException", "Host is unreachable");
            break;
        case ENETUNREACH:
            throw_by_name(env, "java/net/NoRouteToHostException", "Network is unreachable");
            break;
        default:
            throw_by_name(env, "java/io/IOException", strerror(error_code));
            break;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy