/* Copyright (c) 2000 by Inria Lorraine.  All Rights Reserved */

/***
   NAME
     fake
   PURPOSE
     
   NOTES
     
   HISTORY
     gchelius - Jan 20, 2000: Created.
     $Log: jvm_utils.c,v $
     Revision 1.1  2000/04/27 15:52:50  sdalu
     *** empty log message ***

     Revision 1.2  2000/04/27 13:13:38  sdalu
     mise a jour jdk[12] phase1

     Revision 1.1.1.1  2000/02/08 16:31:57  chelius
     Initial import

     Revision 1.1.1.1  2000/02/01 11:10:45  chelius
     Mise sous CVS des sources de libnet6 for jdk1.2.*

***/

#include "jvm_utils.h"

/*
 * Attribut shortcut
 */
jfieldID
NET_GetFileDescriptorID(JNIEnv *env) {
    jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
    return (*env)->GetFieldID(env, cls, "fd", "I");
}

/* 
 * Exception handling
 */
JNIEXPORT void JNICALL 
JNU_ThrowByName(JNIEnv *env, const char *name, const char *msg) {
    jclass cls = (*env)->FindClass(env, name);

    if (cls != 0) /* Otherwise an exception has already been thrown */
        (*env)->ThrowNew(env, cls, msg);

    /* It's a good practice to clean up the local references. */
    (*env)->DeleteLocalRef(env, cls);
}

JNIEXPORT void JNICALL 
JNU_ThrowNullPointerException(JNIEnv *env, const char *msg) {
    JNU_ThrowByName(env, NullPointerException, msg);
}

JNIEXPORT void JNICALL 
JNU_ThrowOutOfMemoryError(JNIEnv *env, const char *msg) {
    JNU_ThrowByName(env, OutOfMemoryError, msg);
}

JNIEXPORT void JNICALL 
JNU_ThrowIOException(JNIEnv *env, const char *msg) {
    JNU_ThrowByName(env, IOException, msg);
}

void 
NET_ThrowCurrent(JNIEnv *env, char *msg) {
    NET_ThrowNew(env, errno, msg);
}

void
NET_ThrowNew(JNIEnv *env, int errorNumber, char *msg) {
    char fullMsg[512];
    if (msg == NULL)
	msg = "no further information";

    switch(errorNumber) {
    case EBADF: 
#if JDK_VERSION >= 2
	jio_snprintf(fullMsg, sizeof(fullMsg), "socket closed: %s", msg);
#endif
	JNU_ThrowByName(env, SocketException, fullMsg);
	break;
    case EINTR:
	JNU_ThrowByName(env, InterruptedIOException, msg);
	break;
    default:
#if JDK_VERSION >= 2
	jio_snprintf(fullMsg, sizeof(fullMsg), "%s: %s", msg, strerror(errno));
#endif
	JNU_ThrowByName(env, SocketException, fullMsg);
	break;
    }
}
