JNI Help!

I am trying to build a simple test program to call a win32api dll.
Here's the code:
import java.util.*;
import java.lang.*;
public class JNItest
static
System.loadLibrary( "winmm" );
System.out.println( "Library loaded." );
static native long PlaySound(String lpszSound, long dwFlags, long fuSound);
public static void main (String args[])
long returnCode = 0;
long xx = 0;
long flags = 0;
String soundFile = "\\MEDIA\\The Microsoft Sound.wav";
System.out.println("Playing '" + soundFile + "'...");
returnCode = PlaySound(soundFile, xx, flags);
The code compiles fine, with no warnings. I then run javah -jni to build the header file. This also works fine.
When I run it, the static initializer fires and loads the native library without error. However, when I actually hit the line of code to call the PlaySound method I get the following exception: "java.lang.UnsatisfiedLinkError: PlaySound".
My path includes a link to c:\winnt\system32 where winmm.dll resides. If you move this dll the loadLibrary method will fail, so I know it is finding the dll.
??? Does anyone know why the call to PlaySound is failing?
Thanks,
alan

It failed because you cannot call a Win32 API function in Java without writing a wrapper dll. What you did is just creates a C/C++ header file.
As for why the static initializer successfully loads the dll is because the file exists.
All C/C++ codes for the native method should have something likeJNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)As for your's, the function should beJNIEXPORT jlong JNICALL Java_JNItest_PlaySound(JNIEnv *env, jobject obj, jstring lpszSound, jlong dwFlags, jlong fuSound)For more information:
http://java.sun.com/docs/books/tutorial/native1.1/index.html

Similar Messages

  • Newbie needs JNI help

    the JNI tutorial speaks about creating a "shared directory" where a "dll" file is created and stored.
    How do i create this ".dll" file and store it into the shared directory ? ...

    Hi,
    Creating dll is outside the realm of Java programming. You need to use some language like C/C++/VB etc. Any good C/C++ IDE has wizards to help you create a dll. Use them. There is a free one at www.bloodshed.org called Dev-C++.
    cheers
    Projyal

  • JNI help - FindClass

    I have recently been trying to play around with JNI, but every time I run my program it says that it cannot locate my file (aka I get the error that it couldn't find the CTF class). I'm currently using xcode on my mac. Here is my code:
    * ctf.c
    * CTF
    #include "JavaVM.framework/Headers/jni.h"
    int main() {
    JNIEnv *env;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    jint res;
    jclass cls;
    jmethodID cid, mid;
    jstring opp_str, opp_str_loc;
    jobjectArray args;
    jobject class_instance, return_val;
    char classpath[4096] = "-Djava.class.path=.:";
    /* IMPORTANT: specify vm_args version # if you use JDK1.1.2 and beyond */
    vm_args.version = JNI_VERSION_1_4;
    JNI_GetDefaultJavaVMInitArgs(&vm_args);
    //this is the directory where my CTF.class file is located
    char *classpathOption = strcat(classpath, "~/Documents/Research/CTF");
    fprintf(stdout, "class path is %s\n", classpathOption);
    JavaVMOption options[1];
    options[0].optionString = classpathOption;
    vm_args.version = 0x00010004;
    vm_args.options = options;
    vm_args.nOptions = 1;
    vm_args.ignoreUnrecognized = JNI_TRUE;
    /* Create the Java VM */
    res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
    if (res < 0) {
    fprintf(stderr, "Can't create Java VM\n");
    exit(1);
    } else {
    printf("created Java VM just fine.\n");
    cls = (*env)->FindClass(env, "CTF");
    if (cls == 0) {
    fprintf(stderr, "Can't find CTF class\n");
    exit(1);
    cid = (*env)->GetMethodID(env, cls, "<init>", "()V");
    if (cid == 0) {
    fprintf(stderr, "Can't find CTF constructor\n");
    class_instance = (*env)->NewObject(env, cls, cid);
    if (class_instance == 0) {
    fprintf(stderr, "Can't create CTF class\n");
    mid = (*env)->GetMethodID(env, cls, "makePrediction", "([Ljava/lang/String;)V");
    if (mid == 0) {
    fprintf(stderr, "Can't find CTF.makePrediction\n");
    exit(1);
    opp_str = (*env)->NewStringUTF(env, "opponent");
    if (opp_str == 0) {
    fprintf(stderr, "Out of memory\n");
    exit(1);
    opp_str_loc = (*env)->NewStringUTF(env, "desk");
    if (opp_str_loc == 0) {
    fprintf(stderr, "Out of memory\n");
    exit(1);
    args = (*env)->NewObjectArray(env, 2,
    (*env)->FindClass(env, "java/lang/String"), opp_str);
    if (args == 0) {
    fprintf(stderr, "Out of memory\n");
    exit(1);
    } else {
    (*env)->SetObjectArrayElement(env, args, 1, opp_str_loc);
    return_val = (*env)->CallObjectMethod(env, class_instance, mid, args);
    (*jvm)->DestroyJavaVM(jvm);
    return 0;

    I'm using java 1.4.2, and jni version 1.4.
    Here's the c code:
    #include "wwhd.h"
    #include "JavaVM.framework/Headers/jni.h"
    #include <stdlib.h>
    char *wwhd(char** knowledge) {
        JNIEnv *env;
        JavaVM *jvm;
        JavaVMInitArgs vm_args;
         jint res;
        jclass cls;
        jmethodID cid, mid;
        jstring opp_str, opp_str_loc, method_str;
        jobjectArray args;
         jobject class_instance, return_val;
        char classpath[4096] = "-Djava.class.path=.:";
        //JNI_GetDefaultJavaVMInitArgs(&vm_args);
         char *classpathOption = strcat(classpath, getenv("CLASSPATH"));
         classpathOption = strcat(classpathOption, ":");
         classpathOption = strcat(classpathOption, "~/Documents/Research/NRL/Eclipse_Workspace/CTF");
         JavaVMOption options[1];
         options[0].optionString = classpathOption;
         vm_args.version = 0x00010004;
         vm_args.options = options;
         vm_args.nOptions = 1;
         vm_args.ignoreUnrecognized = JNI_FALSE;
             /* Create the Java VM */
            res = JNI_CreateJavaVM(&jvm,(void **)&env,&vm_args);
            if (res < 0) {
                fprintf(stderr, "Can't create Java VM\n");
                exit(1);
            } else {
              printf("created Java VM just fine.\n");
            cls = (*env)->FindClass(env, "CTF_Human");
            if (cls == 0) {
                fprintf(stderr, "Can't find CTF_Human class\n");
               (*jvm)->DestroyJavaVM(jvm);
                exit(1);
            } else {
              fprintf(stdout, "Found CTF_Human class\n");
         cid = (*env)->GetMethodID(env, cls, "<init>", "()V");
         if (cid == 0) {
              fprintf(stderr, "Can't find CTF_Human constructor\n");
              (*jvm)->DestroyJavaVM(jvm);
         } else {
              fprintf(stdout, "Found CTF_Human constructor successfully\n");
         class_instance = (*env)->NewObject(env, cls, cid);
             if (class_instance == 0) {
              fprintf(stderr, "Can't create CTF_Human class\n");
              (*jvm)->DestroyJavaVM(jvm);
         } else {
              fprintf(stdout, "Created CTF_Human class w/out a problem\n");
         cls = (*env)->GetObjectClass(env, cls);
         if (cls == 0) {
             fprintf(stderr, "Can't get CTF_Human class from instance\n");
              (*jvm)->DestroyJavaVM(jvm);
                      exit(1);
              } else {
              fprintf(stdout, "Got CTF_Human class from instance\n");
         mid = (*env)->GetStaticMethodID(env, cls, "main", "([java/lang/String;)V");
             if (mid == 0) {
                      fprintf(stderr, "Can't find CTF_Human.main\n");
              if ((*env)->ExceptionOccurred(env)) {
                   fprintf(stderr, "about to exception describe\n");
                   (*env)->ExceptionDescribe(env);
                   fprintf(stderr, "done exception describing\n");
              (*jvm)->DestroyJavaVM(jvm);
                     exit(1);
        (*jvm)->DestroyJavaVM(jvm);
         return "";          
    }and the output is
    Running...
    created Java VM just fine.
    Found CTF_Human class
    Found CTF_Human constructor successfully
    Created CTF_Human class w/out a problem
    Got CTF_Human class from instance
    Can't find CTF_Human.main
    about to exception describe
    java.lang.NoSuchMethodError: main
    Exception in thread "main" done exception describing
    Debugger stopped.
    Program exited with status value:1.(gdb)
    The java code (main function) is:
         public static void main(String[] args) {
              String[] arg = new String[2];
              arg[0] = "opponent";
              arg[1] = "desk";
              CTF h =  new CTF();
              System.out.println(h.makePrediction(arg, true, null));  //another fn in the class
              System.exit(0);
         }Thanks for all your help/time...

  • Need urgent (JNI) help

    I tried this question in the JNI forum also, but there are not many ppl there, and I'm terribly stuck at the moment.
    Hi,
    I'm new with java and new with JNI.
    I'm trying to make an interface between java and a c__ program.
    I get everything wroking except for one method. And I have no clue how to solve it. I have been reading for two days on the net now, and All the things I encounter are too complicated too understand for me at this stage.
    I have a function in c++ :
    // get pair at internal iterator
            inline bool             get(classifType&        theID, string&  theName)
    const
            { return (Converter::get(theID, theName));      }Basicly it will give me back a (Map) key value pair (as reference argument) and a boolean if succeeded.
    in the java file it stands as:
    public  native String  get(long jarg1,String jarg2)the problem is that I have no idea how to work with reference arguments.
    Another approach would also be possible, It would also be good to have a java method:
    public  native Map     getTypes();That would give me a Map with all the available key value pairs.
    The c++ code to get them all would be:
                   ParamTypeConv   ptc(&conn);
                    LOG_INFO ("Walking through the list:");
                    ptc.top();
                    do {
                            string  strvalue;
                            int16   value;
                            if (ptc.get(value, strvalue)) {
                                    LOG_INFO_STR (value << " : " << strvalue);
                    } while (ptc.next());I was thinking in this direction:
    JNIEXPORT jobject JNICALL Java_nl_astron_lofar_sas_otb_jotdb2_jClassifConv_getT\
    ypes(JNIEnv *env, jobject) {
      // Construct java Map
      jobject itemMap, jkey,jval,jold,result;
      jclass mapClass;
      jmethodID init,put;
      mapClass = env->FindClass("java/util/Map");
      init = env->GetMethodID(mapClass, "<init>", "()V");
      result = env->NewObject(mapClass, init);
      put = env->GetMethodID(mapClass, "put",
                 "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
      classifConv->top();
      do {
        string  value;
        long    key;
        if (classifConv->get((classifType)key, value)) {
         jkey   = key;             <<<<<< WRONG
         jvalue = value;        <<<<<<WRONG
          jold   = env->CallObjectMethod(env, result, put, jkey, jval);
      } while (classifConv->next());
      return result;
    But that goes wrong also, no idea how to make object of that (if that is what is going wrong)
    Could anybody please help me out on this ?
    Either solution would be good for me, but pure for extending my knowledge It would be great if someone could shed some light on the first approach also please.
    Thanks for your time and knowledge sharing

    Allready working on it in the Native Methods tread

  • Problems creating a Java Array using JNI-HELP!

    Hi,
    I am trying to create a Java Array using JNI.I have posted the code below. The problem is that the oth element is added correctly to the Array but when the JVM gets to the next element...it goes for a toss. It is not able to create a new instance of the object in GetUGEntity() function...there seems to be some problem in creating a new instance of the object!
    Can somebody help me with this?
    jobject GetUGEntity(JNIEnv *env, UF_DISP_j3d_entity_t* entity_list)
         int numVerts=0, numStrips=0;
         jfieldID fid;
         jdoubleArray jTransform=NULL;
         jstring jstrName=NULL;
         jdoubleArray jNormals=NULL;
         //Init an Entity object
         cout<< "**Getting New Class Reference...";
         jclass jEntity = env->FindClass("Lcom/wipro/java3d/rmi/Entity;");
         cout << "**got Class reference..."<<endl;
         if (jEntity == NULL)
              return NULL;
         cout<<"Creating new object instance...";
         jmethodID mIDInit = env->GetMethodID(jEntity, "<init>", "()V");
         cout<<"Got java method id...";
         jobject javaObj = env->NewObject(jEntity, mIDInit);
         if (javaObj==NULL)
              return NULL;
         cout << "Created!" << endl;
         //Entity ID
         cout<< "**Setting eid...";
         fid=env->GetFieldID(jEntity,"eid","I");
         jint eid = (jint)(entity_list)->eid;
         env->SetIntField(javaObj, fid, eid);
         //env->DeleteLocalRef(eid);
         cout << "Done!" << endl;
         cout << "Done!" << endl;
         cout<< "**Returning jobject...";
         return javaObj;
    jobjectArray createJArray(JNIEnv* env, UF_DISP_j3d_entity_t** entity_list, int noOfEntities )
         UF_DISP_j3d_entity_t* tempVar=NULL;
         cout<<"*Creating Jobjectarray...";
         jobjectArray jEntityArray = (jobjectArray) env->NewObjectArray(noOfEntities,
              env->FindClass("Lcom/wipro/java3d/rmi/Entity;"),NULL);
         cout<<"Created!"<<endl;
         for(int i=0; i<noOfEntities;++i)
              tempVar = &(*entity_list);
              if (tempVar !=NULL)
                   cout<<"*Trying to get Entity...."<<endl;
                   jobject jEntity = GetUGEntity(env, tempVar);
                   if (jEntity!= NULL)
                        cout<<"Got Entity!" <<endl;
                        cout <<"*Setting Array Element....";
                        env->SetObjectArrayElement(jEntityArray, i, jEntity);
                        cout << "Done!" << endl;
                   else
                        printf("ERROR: Did not get Entity Reference");
              else
                   printf("ERROR: Got a NULL Reference!");
         return jEntityArray;

    Hi Deepak,
    Could you please let us know upto which line your code is going safe. Try printing the value in the structure before you send that to the method GetUGEntity().
    I am not too sure that would be a problem. But I have faced a problem like this, wherein I tried to access a structure for which I have not allocated memory and hence got exception because of that.
    Since your JNI code seems to be error free, I got doubt on your C part. Sorry.
    Dhamo.

  • JNI help please

    I am currently working with a friend on developing a java application. The application will include a media player in it. We found the JMF very complicated and unable to even render the most simple media formats so we have decided to use another cross platform media player's rendering library. To get this library to render on a control of my choice though, I have to provide it with the window ID of the control (hWnd on windows and the x11 window handle on linux). After doing a tremendous amount of research, we have concluded that the only way of obtaining the window id is to use JNI to load a native library that extracts the window id. I can't get JNI to work. When i import my native library on windows and attempt to call the function, java throws an exception:
    java.lang.UnsatisfiedLinkError: getHWND
    I can't even get a native library to compile on linux; the compiler says there are syntax errors in included file jawt.h
    Any explanation as to why im gettign these errors would be appreciated. An easier way to get the window id all from java would be greatly appreciated.
    Im using a java1.6.0 snapshot.

    You should be more specific on how your java code is actually calling native functions.
    Can you show us the appropriate java code, and also the appropriate native code of the wrapper?
    Regards

  • Jni COM and MORE

    hello
    i'm french student and i try to make a program to use program in C and other language(Matlab for example) in a JAVA class.
    I would know ,if with a COM object we can permit at a java program to use any functions which are developped in other language.
    And if we can use COM object to call ,in Java class, functions wich are stockpiled inside DLL.
    I have made an experience with JNI and DLL based on c program ,but it is a very long and constraining way to realize a litle execution .
    I search an over way to developpe more easly this project.
    Sorry for my english
    if you have understand my question and if you have any document or idea on subject I'mwaiting your response
    thanks for your attention

    This is a complex issue:
    The simple answer is use JNI
    For a really good book on this topic, including COM integration, I recommend Stuart Halloway's excellent book "Component Development for the Java Platform" ISBN 9 780201 753066
    Stuart has developed a JNI helper system call JAWIN, whixh I have used to access COM objects. I have used this to insert data into Microsoft Outlook, for example.
    Hope this helps ....

  • Thanks bschauwe, but more questions on your post...

    You said in a helpful reply to my post:
    public class TestDataObject {
    public void setX(int val) {
    this.x = val;
    public int getX() {
    return this.x;
    }Your native methods take one of these objects as a parameter, or return one of these objects.
    public class Test {
    public native void setTestData(TestDataObject obj);
    public native TestDataObject getTestData();
    }The TestDataObject constructor, getter, and setter methods can all be invoked with JNI (C)
    code. In other words, to return the test data, you
    o use JNI to call the TestDataObject constructor.
    o Use JNI to call the setters to fill in the data.
    o Return the reference to the TestDataObject.
    I was curious bout the use JNI to call the TestDataObject constructor. Im not sure what u meant, I know there was a JNI call that could be done from C that was titled: Invoking a Java Method. IS that what you meant? like Native access to an objects own methods?
    If so I can check that chapter out in the book, if not then im still lost (as most this new JNI stuff is all greek to me)
    This is what i was starting to write before I realized I might be wrong in interpreting what you said:
    JNIEXPORT void JNICALL Java_AbfaRegion_setJSource
      (JNIEnv *env, jobject thisObj, jobject actualObj)
         jclass clazz = env->GetObjectClass(actualObj);
         jfieldID fid= env->GetFieldID(clazz, "height", "I");
         env->SetIntField(actualObj, fid, myValFromStruct);
    }Here i was explciting trying to set private members of the JSource class, thats not what u meant really is it?
    Thanks for any help again,
    Shane

    Let's assume you create a java class called TestDataObject. You define a constructor, a couple of getters, and a couple of setters.
    Using TestDataObject content in a JNI routine: You pass a TestDataObject to your native routine as a parameter. In the C code, you use JNI functions to invoke the (java) methods on the java object, getting back data types like jint, jlong, jstring, ....
    Using TestDataObject to pass back results from a JNI routine: In the C code, you use JNI functions to invoke the (java) methods of a TestDataObject. But wait! First you use JNI functions to create a new TestDataObject! In other words, JNI helps you invoke the constructor method.
    A C function can invoke java methods using JNI calls in roughly the following sequence:
    o Call a JNI function to get a reference to the class - a kind of "type" record. FindClass or GetObjectClass.
    o Call a JNI function to get the ID of the method you want to invoke: GetMethodID (class is a parameter)
    o Call a JNI function to invoke the method. CallxxxMethod (class and method ID are parameters to this function. If you are not calling a constructor or a static method, then instead of the class, pass an object pointer.)
    Finally: You can do what your code shows - shove data right into private data members of java classes. I choose instead to invoke getters and setters.

  • Java.io.File give incorrect chinese filenam when using javaw.exe

    I am running Chinese Win2000 Pro (SP2) with jre1.3.1 installed. If I use javaw.exe to run my application, java.io.File does not give the correct filename for chinese filename when I use it to run through a directory, though all English filenames show correctly.
    When the same program is run by java.exe instead of javaw.exe, the program runs with no problem and all chinese name are obtained successfully from java.io.File. Does anyone know the reason behind this ?
    I need to use javaw.exe since I am invoking Java from VC++. I don't want a black command prompt window to pop up behind my java application. Please help.

    Hi,
    I am sorry for not replying to ur query. Infact I am facing my own problem and after reading your problem I thought you could help me out in it because you are already successful in invoking java from VC++.
    My problem is that I want to invoke java class from VC++ in such a way that I want to capture the stdout of java class that I invoke from VC++ and use it in VC++. Let me explain first thing first. I am not able to invoke java class from withing vc++. I have looked at JNI help on SUN site but it is giving me lots of compilation error when I include JNI.h in my VC++ program. If you could help me out in this problem, it would be great.
    Thanks in advance.
    Regards
    Rakesh

  • AttachCurrentThread hangs after a few calls in a Apache2 PHP5 Extension

    Hello everybody,
    I have created a small C Library/API that calls with JNI a simple Java class with a few methods to work with a underlying Java Framework (Carrot2). That JVM/JNI code functions some kind like a bridge between C and Java. In a single-threaded environment I experienced no problems, the complete runtime flow works well, I get no crashes or other strange behaviour.
    Now I have built an PHP5 extension that makes use of that JNI/C code, the extension is built as a class with constructor/destructor and has a few methods that call functions of my C library. The JNI/C side I have 2 data structs, one is for the JVM and its handle (JavaVM) as well as the Java class name and its path, the jclass object of that class, jvm options, classpath, etc. A second data struct is for the Java environment containing the JNIEnv pointer, the jobject of the Java class and a few more application related variables. The C code consists of JNI functions to work with the Java class to call its methods, a few JNI helper functions and some internal application code and data handling.
    At module initialization (Apache startup) I use the PHP_MINIT and PHP_MSHUTDOWN functions to load and unload (on apache stop) the JVM. The JVM gets created and destroyed at these points.
    I use the PHP constructor (inside the extension) to attach to the JVM, that is AttachCurrentThread with the class constructor, I create and object of the Java class and preload a few Java primitives that I need for my methods later on and after all this I can work with the Java class through JNI. On PHP5 class destruction (also in the extension), I detach from the JVM using 'DetachCurrentThread', free some resources and "delete" the JNIEnv pointer (set it to NULL).
    The JVM data struct (containing the JVM object) is a static global in the PHP5 module since I think there is no need for thread safety. This data is only modified/used in module startup/shutdown. The JNI worker struct (data struct with the JNIEnv pointer and jobject, etc is safely handled by the Zend object store throughout the complete class, so this should be thread-safe. So I do not suspect any problem here.
    Testing the PHP 5 extension with a small PHP5 script using that PHP class and a few methods in Apache debug mode (that is the -X switch for just one worker process) works like a charm, no problems, crashes or misbehaving situations, not up to now with my testing though. But running Apache in regular mode with multiple processes, I run in to problems. One major problem is, after a few reloads of the php script using the extension class (lets say 10-15 reloads; The request is handled by the same apache child process) the `AttachCurrentThread' call hangs and the child process remains in that state. Continuing reloading the script a new child process answers and also here, after 10-15 reloads of the script, I get the same problem. So I am not sure what is really happening here nor I do not know how to solve that issue. Is that a signal problem (I read, that there can be signal mask issues and the JVM hangs when a new thread tries to attach to it, for example, the Jakarta Tomcat JK JNI worker uses a signal hack because of this problem. But that does not help me.
    Or is there some problem with the multi-threading itself (since the JVM is multithreaded too)? Another problem is, besides that hanging thread attach, that the processing sometimes stops in middle of a java call (I have one method that insert data (calling a add method in a for loop) with JNI into a Java list on the Java class side, there it can stop in middle of the insertion process.
    So, for now, I have no idea how to continue. Like said, in a single threaded environment, as a process, the application runs fine without a flaw.
    Some details of my development machines: Ubuntu Lucic 10.04 LTS (also another Ubuntu 8 LTS), Apache2 MPM Worker (multithreaded model) and also on another machine the prefork version, Java JRE 6.0.22, PHP 5.2.16 (compiled from source).
    So any hints that can help me proceeding the development of this module for PHP would be great. Any help is appreciated. If there are questions or some unclear points, please let me know.
    Andreas

    jschell wrote:
    847069 wrote:
    I use the PHP constructor (inside the extension) to attach to the JVM, that is AttachCurrentThread with the class constructor, I create and object of the Java class and preload a few Java primitives that I need for my methods later on and after all this I can work with the Java class through JNI. On PHP5 class destruction (also in the extension), I detach from the JVM using 'DetachCurrentThread', free some resources and "delete" the JNIEnv pointer (set it to NULL).
    That is unclear.
    I presume that you have a PHP class which is making JNI calls.
    Presumably you have a single thread in the caller of the PHP class, specifically a single method, which creates the PHP class, interacts with it, and then destroys it.
    Yes, programming PHP5 extensions in C or C++ let you implement a class or just flat functions that can be used in the PHP scripting language. I implemented a class. So my constructor attaches to the (already at Apache/Module startup created JVM). After that, I can use the methods I have implemented to use the carrot2 framework. To communicate with the Carrot2 library, I have written a simple Java Class containing static functions for adding documents, executing clustering algorithms and receiving the search results, so all pretty straightforward I think. When the PHP script exists (request finished) then the class destructor is called (also implemented in my PHP5 extension) to detach from the JVM and make some cleanup. This is generally how things work.
    Most problems with JNI is caused by pointer problems or misusing the API (like not handling exceptions correctly.)
    Other than that the Sun VM has a command line option that reports useful information when using JNI.I can compile and run my JNI code with some test data from command line and I pass to the JVM some debugging parameters (such as -Xcheck:jni, -verbose:jni and Xint) for testing and debugging. I get no exceptions, errors or warnings. Everything is executed cleanly, I see some JNI/JVM debugging output (such as Dynamic-linking native method messages) along my own debugging output and the program finishes normally. Most JNI calls are wrapped in special macros and I check for exceptions, describe and clear them and act with these situtions (if any), I also added a method to the Java Class where I am able to receive the Java backrace for further investigation and abort execution.
    So for now I am out of ideas. This is why I don't understand these problems within the Apache/PHP process. Like stated above, Apache with one worker "-X" the complete code runs fine, even with consecutive calls all is fine, but then in regular multiprocess mode, I get the above problems like the AttachCurrentThread hangs or the execution of called methods of my Java class (inserting documents to a ArrayList or executing one of the clustering algorithms) hang and I have no other choice but to stop Apache.
    One more thing, I valgrinded my C code as far as possible. It is not possible to valgrind C code that creates and executes a JVM. Valgrind will stop and report "Error occurred during initialization of VM". No wonder though, I do not expect valgrind to execute the JVM beast in its context. The PHP5 version i compiled from source is thread-safe (at least I compiled it with the proper flags for that).
    So any other debugging hints or ideas are welcome.
    Edited by: 847069 on Mar 24, 2011 10:31 PM
    Edited by: 847069 on Mar 24, 2011 10:35 PM

  • Raw TCP/IP data packets

    I have done a lot of client/server programming with Server and Client sockets in Java.
    However now I need to do raw TCP/IP programming. I would hate to go back to C/C++ to do this kind of programming. Is it possible to do raw tcp/ip programming in Java? Data packet by data packet, headers and the whole works in Java?
    Erik

    You can even white a sniffer with java (JNI helps a lot;)
    Look here -> http://www.goto.info.waseda.ac.jp/~fujii/jpcap/index.html

  • JNI Hotspot Error: Access Violation, need help interpreting the log.

    Hello. I'm a relatively new developer (previously an engineer), and so to start me off I was given the task of providing a JNI-enabled interface to some legacy licensing software (it's C++, we want Java). Now the functionality of JNI is not the problem I have. I HAD those types of problems but now I'm having a far more obscure problem that is absolutely stumping me.
    It's a Hotspot error that I cannot get rid off... and I cannot find a clear bit of info on how to interpret them.
    About the problem...first off this does not happen on my development machine, where it is isolated from other components in the end-product. The integration machine with the rest of the software runs fine with a "Dummy" version of my component, but we get errors when the real version is in use. I'd really appreciate any help in understanding these things, even if it is just some general pointers.
    First off here is the log
    # An unexpected error has been detected by HotSpot Virtual Machine:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7c82caa4, pid=5516, tid=4420
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_14-b03 mixed mode)
    # Problematic frame:
    # C  [ntdll.dll+0x2caa4]
    ---------------  T H R E A D  ---------------
    Current thread (0x0aa1eaa0):  JavaThread "btpool0-5" [_thread_in_native, id=4420]
    siginfo: ExceptionCode=0xc0000005, reading address 0x00000004
    Registers:
    EAX=0x0b1a9a40, EBX=0x00030000, ECX=0x00001448, EDX=0x00000000
    ESP=0x0c90e774, EBP=0x0c90e780, ESI=0x0b1a9a38, EDI=0x0b1aa000
    EIP=0x7c82caa4, EFLAGS=0x00010246
    Top of Stack: (sp=0x0c90e774)
    0x0c90e774:   00030000 00000003 00030005 0c90e7b8
    0x0c90e784:   7c833a2a 0b1a9a4c 0b1aa000 0c90e7ac
    0x0c90e794:   00000000 00000477 00030178 00030000
    0x0c90e7a4:   0ab2de05 0003015c 00000600 0afd0000
    0x0c90e7b4:   00030178 0c90e9e4 7c82b5fb 04030000
    0x0c90e7c4:   000023b8 000023ac 00000000 7c829fd6
    0x0c90e7d4:   7c82a124 00031138 0c90ea04 7c82a0b8
    0x0c90e7e4:   7c82a0fc 000001ba 00000000 7c829fd6
    Instructions: (pc=0x7c82caa4)
    0x7c82ca94:   63 02 00 8b 4e 0c 8d 46 08 8b 10 89 4d 08 8b 09
    0x7c82caa4:   3b 4a 04 89 55 0c 0f 85 ae 4f 01 00 3b c8 0f 85
    Stack: [0x0c8d0000,0x0c910000),  sp=0x0c90e774,  free space=249k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    C  [ntdll.dll+0x2caa4]
    C  [ntdll.dll+0x33a2a]
    C  [ntdll.dll+0x2b5fb]
    C  [MSVCRT.dll+0x1d08c]
    C  [verify.dll+0x4897]
    C  [verify.dll+0x19c6]
    C  [verify.dll+0x126b]
    C  [java.dll+0x3fb7]
    V  [jvm.dll+0x11d86a]
    V  [jvm.dll+0x78acb]
    V  [jvm.dll+0x78deb]
    V  [jvm.dll+0x78aaa]
    V  [jvm.dll+0xcb029]
    V  [jvm.dll+0xcbcc6]
    V  [jvm.dll+0xcbbac]
    V  [jvm.dll+0x82c7b]
    j  com.a.b.c.lmv.Factoralproducer.MeanManagerImpl.subscribe
    (Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;
    Lcom/a/b/c/lmv/baseFactoral/TopicExpressionType;Ljava/lang/Boolean;
    Lorg/oasis_open/docs/wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;
    Lorg/oasis_open/docs/
    wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;
    Lcom/a/b/c/lmv/Factoralproducer/MeanPolicyType;Ljavax/xml/datatype/XMLGregorianCalendar;
    Lcom/a/b/c/lmv/types/ppoToken;)
    Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;+231
    j  com.a.b.c.lmv.Factoralproducer.FactoralProducerImpl.subscribe
    (Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;
    Lcom/a/b/c/lmv/baseFactoral/TopicExpressionType;Ljava/lang/Boolean;Lorg/oasis_open/docs/wsrf/_2004/_06/
    wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;Lorg/oasis_open/docs/
    wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;Lcom/a/b/c/lmv
    /Factoralproducer/MeanPolicyType;Ljavax/xml/datatype/XMLGregorianCalendar;Lcom/a/b/c/lmv/types/ppoToken;)
    Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;+20
    v  ~StubRoutines::call_stub
    V  [jvm.dll+0x875dd]
    V  [jvm.dll+0xdfd96]
    V  [jvm.dll+0x874ae]
    V  [jvm.dll+0xf3f82]
    V  [jvm.dll+0xa5752]
    C  [java.dll+0x6d4f]
    j  sun.reflect.NativeMethodAccepporImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+87
    J  sun.reflect.DelegatingMethodAccepporImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    J  java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    v  ~RuntimeStub::alignment_frame_return Runtime1 stub
    j  org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(Lorg/apache/cxf/message/Exchange;
    Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;+57
    j  org.apache.cxf.service.invoker.AbstractInvoker.invoke(Lorg/apache/cxf/message/Exchange;Ljava/lang/Object;
    Ljava/lang/reflect/Method;Ljava/util/List;)Ljava/lang/Object;+26
    j  org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(Lorg/apache/cxf/message/Exchange;Ljava/lang/Object
    ;Ljava/lang/reflect/Method;Ljava/util/List;)Ljava/lang/Object;+179
    j  org.apache.cxf.service.invoker.AbstractInvoker.invoke(Lorg/apache/cxf/message/Exchange;Ljava/lang/Object;)
    Ljava/lang/Object;+114
    j  org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run()V+26
    j  org.apache.cxf.workqueue.SynchronousExecutor.execute(Ljava/lang/Runnable;)V+1
    j  org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(Lorg/apache/cxf/message/Message;)V+94
    j  org.apache.cxf.phase.PhaseInterceptorChain.dcntercept(Lorg/apache/cxf/message/Message;)Z+76
    j  org.apache.cxf.transport.ChainInitiationObserver.onMessage(Lorg/apache/cxf/message/Message;)V+137
    j  org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;)V+334
    j  org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;)V+341
    j  org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+47
    j  org.mortbay.jetty.handler.ContextHandler.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+700
    j  org.mortbay.jetty.handler.ContextHandlerCollection.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+272
    j  org.mortbay.jetty.handler.HandlerWrapper.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+23
    j  org.mortbay.jetty.Server.handle(Lorg/mortbay/jetty/HttpConnection;)V+110
    j  org.mortbay.jetty.HttpConnection.handleRequest()V+131
    J  org.mortbay.jetty.HttpParser.parseNext()J
    v  ~RuntimeStub::alignment_frame_return Runtime1 stub
    j  org.mortbay.jetty.HttpParser.parseAvailable()J+1
    j  org.mortbay.jetty.HttpConnection.handle()V+122
    j  org.mortbay.jetty.bio.SocketConnector$Connection.run()V+130
    j  org.mortbay.jetty.security.SslSocketConnector$SslConnection.run()V+51
    j  org.mortbay.thread.BoundedThreadPool$PoolThread.run()V+45
    v  ~StubRoutines::call_stub
    V  [jvm.dll+0x875dd]
    V  [jvm.dll+0xdfd96]
    V  [jvm.dll+0x874ae]
    V  [jvm.dll+0x8720b]
    V  [jvm.dll+0xa2089]
    V  [jvm.dll+0x1112e8]
    V  [jvm.dll+0x1112b6]
    C  [MSVCRT.dll+0x2b530]
    C  [kernel32.dll+0x24829]
    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j  com.a.b.c.lmv.Factoralproducer.MeanManagerImpl.subscribe
    (Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;Lcom/a/b/c/lmv/baseFactoral/TopicExpressionType;
    Ljava/lang/Boolean;Lorg/oasis_open/docs/wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;
    Lorg/oasis_open/docs/
    wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;Lcom/a/b/c/lmv/Factoralproducer/MeanPolicyType;
    Ljavax/xml/datatype/XMLGregorianCalendar;Lcom/a/b/c/lmv/types/ppoToken;)
    Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;+231
    j  com.a.b.c.lmv.Factoralproducer.FactoralProducerImpl.subscribe
    (Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;Lcom/a/b/c/lmv/baseFactoral/TopicExpressionType;
    Ljava/lang/Boolean;Lorg/oasis_open/docs/wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;
    Lorg/oasis_open/docs/
    wsrf/_2004/_06/wsrf_ws_resourceproperties_1_2_draft_01/QueryExpressionType;Lcom/a/b/c/lmv/Factoralproducer
    /MeanPolicyType;Ljavax/xml/datatype/XMLGregorianCalendar;Lcom/a/b/c/lmv/types/ppoToken;)
    Lorg/xmlbp/schemas/ws/_2003/_03/addressing/EndpcntReferenceType;+20
    v  ~StubRoutines::call_stub
    j  sun.reflect.NativeMethodAccepporImpl.invoke0(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)
    Ljava/lang/Object;+0
    j  sun.reflect.NativeMethodAccepporImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+87
    J  sun.reflect.DelegatingMethodAccepporImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    J  java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    v  ~RuntimeStub::alignment_frame_return Runtime1 stub
    j  org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(Lorg/apache/cxf/message/
    Exchange;Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;+57
    j  org.apache.cxf.service.invoker.AbstractInvoker.invoke(Lorg/apache/cxf/message/Exchange;
    Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/util/List;)Ljava/lang/Object;+26
    j  org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(Lorg/apache/cxf/message/Exchange;
    Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/util/List;)Ljava/lang/Object;+179
    j  org.apache.cxf.service.invoker.AbstractInvoker.invoke(Lorg/apache/cxf/message/Exchange;Ljava/lang/Object;)
    Ljava/lang/Object;+114
    j  org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run()V+26
    j  org.apache.cxf.workqueue.SynchronousExecutor.execute(Ljava/lang/Runnable;)V+1
    j  org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(Lorg/apache/cxf/message/Message;)V+94
    j  org.apache.cxf.phase.PhaseInterceptorChain.dcntercept(Lorg/apache/cxf/message/Message;)Z+76
    j  org.apache.cxf.transport.ChainInitiationObserver.onMessage(Lorg/apache/cxf/message/Message;)V+137
    j  org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;)V+334
    j  org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;)V+341
    j  org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+47
    j  org.mortbay.jetty.handler.ContextHandler.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+700
    j  org.mortbay.jetty.handler.ContextHandlerCollection.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+272
    j  org.mortbay.jetty.handler.HandlerWrapper.handle(Ljava/lang/String;Ljavax/servlet/http/HttpServletRequest;
    Ljavax/servlet/http/HttpServletResponse;I)V+23
    j  org.mortbay.jetty.Server.handle(Lorg/mortbay/jetty/HttpConnection;)V+110
    j  org.mortbay.jetty.HttpConnection.handleRequest()V+131
    J  org.mortbay.jetty.HttpParser.parseNext()J
    v  ~RuntimeStub::alignment_frame_return Runtime1 stub
    j  org.mortbay.jetty.HttpParser.parseAvailable()J+1
    j  org.mortbay.jetty.HttpConnection.handle()V+122
    j  org.mortbay.jetty.bio.SocketConnector$Connection.run()V+130
    j  org.mortbay.jetty.security.SslSocketConnector$SslConnection.run()V+51
    j  org.mortbay.thread.BoundedThreadPool$PoolThread.run()V+45
    v  ~StubRoutines::call_stub
    ---------------  P R O C E S S  ---------------
    Java Threads: ( => current thread )
      0x0aa2d9f8 JavaThread "RMI RenewClean-[47.166.94.29:3617]" daemon [_thread_in_native, id=4792]
    =>0x0aa1eaa0 JavaThread "btpool0-5" [_thread_in_native, id=4420]
      0x0aa1c450 JavaThread "btpool0-4" [_thread_in_native, id=4600]
      0x0aa574d0 JavaThread "btpool0-3" [_thread_in_native, id=3456]
      0x0aa61c60 JavaThread "RMI ConnectionExpiration-[localhost:8099]" daemon [_thread_blocked, id=5060]
      0x0aa44988 JavaThread "btpool0-2" [_thread_in_native, id=3956]
      0x0aa2f270 JavaThread "RMI LeaseChecker" daemon [_thread_blocked, id=4640]
      0x0aa2e668 JavaThread "RMI TCP Connection(1)-47.166.94.29" daemon [_thread_in_native, id=1600]
      0x0aa40d48 JavaThread "RMI Reaper" [_thread_blocked, id=4696]
      0x0b20ae68 JavaThread "Timer-0" daemon [_thread_blocked, id=4688]
      0x0aa294f8 JavaThread "RMI TCP Accept-0" daemon [_thread_in_native, id=4884]
      0x0aa29680 JavaThread "RMI ConnectionExpiration-[47.166.94.29:4375]" daemon [_thread_blocked, id=4860]
      0x0abfe318 JavaThread "btpool0-1" [_thread_in_native, id=716]
      0x0ac2b1f0 JavaThread "GC Daemon" daemon [_thread_blocked, id=3588]
      0x0ac26730 JavaThread "RMI RenewClean-[47.166.94.29:4375]" daemon [_thread_blocked, id=1820]
      0x0ab92d70 JavaThread "btpool1-0 - Acceptor0 [email protected]:9082" [_thread_in_native, id=3168]
      0x0b162be0 JavaThread "btpool0-0 - Acceptor0 [email protected]:9080" [_thread_in_native, id=5856]
      0x0b0e7a18 JavaThread "RMManager-Timer-12388840" daemon [_thread_blocked, id=4328]
      0x00035088 JavaThread "DestroyJavaVM" [_thread_blocked, id=4780]
      0x0afc6460 JavaThread "Thread-1" [_thread_blocked, id=440]
      0x0afd6768 JavaThread "Thread-0" daemon [_thread_blocked, id=4840]
      0x00814cc8 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=3076]
      0x00813950 JavaThread "CompilerThread0" daemon [_thread_blocked, id=3248]
      0x00812cc8 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=5140]
      0x00809bf8 JavaThread "Finalizer" daemon [_thread_blocked, id=3704]
      0x00808780 JavaThread "Reference Handler" daemon [_thread_blocked, id=5196]
    Other Threads:
      0x00804530 VMThread [id=736]
      0x00816058 WatcherThread [id=4436]
    VM state:not at safepcnt (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation   total 1984K, used 1897K [0x02850000, 0x02a70000, 0x02d30000)
    *eden space 1792K,  95% used [0x02850000, 0x029fa418, 0x02a10000)*
    * from space 192K, 100% used [0x02a40000, 0x02a70000, 0x02a70000)*
      to   space 192K,   0% used [0x02a10000, 0x02a10000, 0x02a40000)
    tenured generation   total 25896K, used 18178K [0x02d30000, 0x0467a000, 0x06850000)
       the space 25896K,  70% used [0x02d30000, 0x03ef0b60, 0x03ef0c00, 0x0467a000)
    compacting perm gen  total 22784K, used 22721K [0x06850000, 0x07e90000, 0x0a850000)
      * the space 22784K,  99% used [0x06850000, 0x07e806c8, 0x07e80800, 0x07e90000)*
    No shared spaces configured.
    Dynamic libraries:
    0x00400000 - 0x0040d000      D:\apps\Java\jre1.5.0_14\bin\java.exe
    0x7c800000 - 0x7c8c0000      C:\WINDOWS\system32\ntdll.dll
    0x77e40000 - 0x77f42000      C:\WINDOWS\system32\kernel32.dll
    0x77f50000 - 0x77feb000      C:\WINDOWS\system32\ADVAPI32.dll
    0x77c50000 - 0x77cef000      C:\WINDOWS\system32\RPCRT4.dll
    0x76f50000 - 0x76f63000      C:\WINDOWS\system32\Secur32.dll
    0x77ba0000 - 0x77bfa000      C:\WINDOWS\system32\MSVCRT.dll
    0x6d640000 - 0x6d7de000      D:\apps\Java\jre1.5.0_14\bin\client\jvm.dll
    0x77380000 - 0x77411000      C:\WINDOWS\system32\USER32.dll
    0x77c00000 - 0x77c48000      C:\WINDOWS\system32\GDI32.dll
    0x76aa0000 - 0x76acd000      C:\WINDOWS\system32\WINMM.dll
    0x71bc0000 - 0x71bc8000      C:\WINDOWS\system32\rdpsnd.dll
    0x771f0000 - 0x77201000      C:\WINDOWS\system32\WINSTA.dll
    0x71c40000 - 0x71c97000      C:\WINDOWS\system32\NETAPI32.dll
    0x76b70000 - 0x76b7b000      C:\WINDOWS\system32\PSAPI.DLL
    0x6d290000 - 0x6d298000      D:\apps\Java\jre1.5.0_14\bin\hpi.dll
    0x6d610000 - 0x6d61c000      D:\apps\Java\jre1.5.0_14\bin\verify.dll
    0x6d310000 - 0x6d32d000      D:\apps\Java\jre1.5.0_14\bin\java.dll
    0x6d630000 - 0x6d63f000      D:\apps\Java\jre1.5.0_14\bin\zip.dll
    0x68000000 - 0x68035000      C:\WINDOWS\system32\rsaenh.dll
    0x7c8d0000 - 0x7d0cf000      C:\WINDOWS\system32\SHELL32.dll
    0x77da0000 - 0x77df2000      C:\WINDOWS\system32\SHLWAPI.dll
    0x77420000 - 0x77523000      C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls
                                           _6595b64144ccf1df_6.0.3790.3959_x-ww_D8713E55\comctl32.dll
    0x6d4d0000 - 0x6d4e3000      D:\apps\Java\jre1.5.0_14\bin\net.dll
    0x71c00000 - 0x71c17000      C:\WINDOWS\system32\WS2_32.dll
    0x71bf0000 - 0x71bf8000      C:\WINDOWS\system32\WS2HELP.dll
    0x71b20000 - 0x71b61000      C:\WINDOWS\System32\mswsock.dll
    0x76ed0000 - 0x76efa000      C:\WINDOWS\system32\DNSAPI.dll
    0x76f70000 - 0x76f77000      C:\WINDOWS\System32\winrnr.dll
    0x76f10000 - 0x76f3e000      C:\WINDOWS\system32\WLDAP32.dll
    0x76f80000 - 0x76f85000      C:\WINDOWS\system32\rasadhlp.dll
    0x5f270000 - 0x5f2ca000      C:\WINDOWS\system32\hnetcfg.dll
    0x71ae0000 - 0x71ae8000      C:\WINDOWS\System32\wshtcpip.dll
    0x6d4f0000 - 0x6d4f9000      D:\apps\Java\jre1.5.0_14\bin\nio.dll
    0x6d5f0000 - 0x6d5f6000      D:\apps\Java\jre1.5.0_14\bin\rmi.dll
    0x10000000 - 0x10006000      C:\Program Files\a\lmv\punix.dll
    0x71f50000 - 0x71f58000      C:\WINDOWS\system32\snmpapi.dll
    0x0bb90000 - 0x0bb98000      C:\Program Files\a\lmv\periwin.dll
    0x0bba0000 - 0x0bbab000      C:\Program Files\a\lmv\vas.dll
    0x0bbb0000 - 0x0bbd0000      C:\Program Files\a\lmv\nilm.dll
    0x48890000 - 0x488cd000      C:\WINDOWS\system32\ODBC32.dll
    0x77530000 - 0x775c7000      C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls
                                            _6595b64144ccf1df_5.82.3790.3959_x-ww_78FCF8D0\COMCTL32.dll
    0x762b0000 - 0x762f9000      C:\WINDOWS\system32\comdlg32.dll
    0x76cf0000 - 0x76d0a000      C:\WINDOWS\system32\iphlpapi.dll
    0x7f010000 - 0x7f134000      C:\WINDOWS\system32\MFC42u.DLL
    0x77670000 - 0x777a9000      C:\WINDOWS\system32\ole32.dll
    0x77d00000 - 0x77d8b000      C:\WINDOWS\system32\OLEAUT32.dll
    0x77210000 - 0x772bb000      C:\WINDOWS\system32\WININET.dll
    0x761b0000 - 0x76243000      C:\WINDOWS\system32\CRYPT32.dll
    0x76190000 - 0x761a2000      C:\WINDOWS\system32\MSASN1.dll
    0x71bb0000 - 0x71bb9000      C:\WINDOWS\system32\WSOCK32.dll
    0x0bda0000 - 0x0bdb7000      C:\WINDOWS\system32\odbcint.dll
    0x0bf20000 - 0x0bf61000      C:\Program Files\a\lmv\JniLib.dll
    0x76cd0000 - 0x76ce9000      C:\WINDOWS\system32\MPRAPI.dll
    0x76df0000 - 0x76e24000      C:\WINDOWS\system32\ACTIVEDS.dll
    0x76dc0000 - 0x76de8000      C:\WINDOWS\system32\adsldpc.dll
    0x76b80000 - 0x76bae000      C:\WINDOWS\system32\credui.dll
    0x76a80000 - 0x76a98000      C:\WINDOWS\system32\ATL.DLL
    0x76e30000 - 0x76e3c000      C:\WINDOWS\system32\rtutils.dll
    0x7e020000 - 0x7e02f000      C:\WINDOWS\system32\SAMLIB.dll
    0x770e0000 - 0x771e8000      C:\WINDOWS\system32\SETUPAPI.dll
    0x77840000 - 0x77882000      C:\WINDOWS\system32\netman.dll
    0x76300000 - 0x764c0000      C:\WINDOWS\system32\netshell.dll
    0x74de0000 - 0x74df2000      C:\WINDOWS\system32\CLUSAPI.dll
    0x76e90000 - 0x76ecf000      C:\WINDOWS\system32\RASAPI32.dll
    0x76e40000 - 0x76e52000      C:\WINDOWS\system32\rasman.dll
    0x76e60000 - 0x76e8f000      C:\WINDOWS\system32\TAPI32.dll
    0x7fcf0000 - 0x7fd7e000      C:\WINDOWS\system32\WZCSvc.DLL
    0x76cc0000 - 0x76cc5000      C:\WINDOWS\system32\WMI.dll
    0x76d10000 - 0x76d2f000      C:\WINDOWS\system32\DHCPCSVC.DLL
    0x76f00000 - 0x76f08000      C:\WINDOWS\system32\WTSAPI32.dll
    0x4b180000 - 0x4b284000      C:\WINDOWS\system32\ESENT.dll
    0x730a0000 - 0x730ae000      C:\WINDOWS\system32\WZCSAPI.DLL
    VM Arguments:
    java_command: C:\Program Files\a\lmv\CDF\b_c_lmv.jar C:\Program Files\a\lmv\CDF
    Launcher Type: SUN_STANDARD
    Environment Variables:
    CLASSPATH=D:\a\Contact Center\Common Components\Cache\lib
    PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;
    C:\Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common;
    C:\a\Cache\CacheSys\Mgr\a\DLL;C:\Program Files\a\lmv\TAPI;C:\Program Files\a\lmv\
    OS=Windows_NT
    PROCEppoR_IDENTIFIER=x86 Family 6 Model 15 Stepping 11, GenuineIntel
    ---------------  S Y S T E M  ---------------
    OS: Windows Server 2003 family Build 3790 Service Pack 2
    CPU:total 4 (cores per cpu 4, threads per core 1) family 6 model 15 stepping 11, cmov, cx8, fxsr, mmx, sse, sse2
    Memory: 4k page, physical 2097151k(2097151k free), swap 4194303k(3537076k free)
    vm_info: Java HotSpot(TM) Client VM (1.5.0_14-b03) for windows-x86, built on Oct  5 2007 01:21:52 by "java_re" with MS VC++ 6.0
    {code}
    Sorry it's so long.
    Anyways my dll is Jni_interface.dll. It loads legacy.dll, and its dependents. Other code also uses these libraries.
    *So question 1* :
    I load the jni_interface.dll (and also the legacy.dll and its dependents) library at the start of execution in a static class and so it is never unloaded. I do this because the legacy.dll will be calling functions in my Jni_Interface.dll, which are propagated into the Java class on top of it all. Does this stop other code from loading the legacy.dll or from using its functionality?
    *On to question 2*:
    Here is the logged output from my library, immediately before the crash:
    {code:java}
          ***     JNI INTERFACE LIB - LOG 21 Jul 08 19:11:35.682     *** Log Level = DEBUG
    21 Jul 08 19:11:35.698 - Level[ info ] -          Thread[ 716 ]     :: initRegistry     Registry initialisation ok
    21 Jul 08 19:11:35.760 - Level[ info ] -          Thread[ 716 ]     :: vPersistData     vPersistData() called
    21 Jul 08 19:11:35.823 - Level[ debug ] -     Thread[ 716 ]     :: doVoidCallback() [ persistDataHandler ]       Signature  = (I)V
    21 Jul 08 19:11:35.823 - Level[ debug ] -     Thread[ 716 ]     :: doVoidCallback() [ setMaxUsageHandler ]       Signature  = (I)V
    21 Jul 08 19:11:35.838 - Level[ info ] -          Thread[ 716 ]     :: Constructor     _instance is instantiated
    21 Jul 08 19:11:35.838 - Level[ info ] -          Thread[ 716 ]     :: initiateLegacy()     JniManager initialisation successful
    21 Jul 08 19:11:35.838 - Level[ info ] -          Thread[ 716 ]     :: initiateLegacy()     Initial state is NORMAL
    21 Jul 08 19:11:35.838 - Level[ debug ] -     Thread[ 716 ]     :: getLicense()     Get request
    21 Jul 08 19:11:36.010 - Level[ debug ] -     Thread[ 716 ]     :: getLicense()     Get request
    {code}
    Now notice that the current thread in the Hotspot output is NOT the thread in my library. Thread 716 is a java thread by the way. This log appears absolutely fine according to me. Also note that in the hotspot log there is no mention of my java component  (the "boss" class), which is called LegacyLM. So does that mean that is in not to do with my code even though the problem only occurs when my component is included? Or is this just the cryptic nature of these problems?
    *Question 3*:
    If you see the heap section of the report, there are 3 items that I have highlighted that seem like very high values. Is this a possible cause of a crash? Or would I have received an "Out of space" error instead?
    In terms of actual code, I cannot post much, but I can tell you what I have done to try to solve the problem:
    (i) I have added mutex synchronisation to most of my shared variables.
    (ii) I have used monitorEnter and MonitorExit to control callback access to my java class.
    (iii) I have re-organised my code and replaced nearly every occurance of non-string character arrays with string equivalents.
    (iv) I changed how I attach and detach my threads so that I only attach/detach ones that previously were not (i.e. I leave java threads alone)
    As I said at the start, I am utterly confused and I don't have much of an idea about how to proceed. I'd really really appreciate a pointer or two.
    Thanks in advance.
    D
    Edited by: Diom1982 on Jul 21, 2008 12:35 PM
    Edited by: Diom1982 on Jul 21, 2008 12:40 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    For those of you who might be interested, I found a solution to this problem (my version, at least). In my situation, this was caused by attempting to access the fields of a ActionEvent object in VC++ by casting a variant to a BSTR. While the cast "worked", it somehow caused the state of the Java plugin or the AxBridge DLL to get flummoxed, causing the VM dump far downstream.
    The takehome message?
    When seeing problems like this in the plugin / ActiveX bridge, do not assume that the causative error is occuring in the location noted in the stack trace. Visual C++, in all of its gory unprotected glory, gives full memory access to the DLL interface and you can do a serious fandango on the VM core. that won't necessarily bite you until later.
    PS -- Sun gurus ... does this present a security violation in the Java paradigm?

  • Help writing to file in "C" using JNI

    Hi,
    I am trying to write the encrypted data that I read from a file. It writes the decrypted data; however, it prints extra characters at the end of file after the data. I am not sure why this is happening. Below is the code that I use to write the decrypted data to a file. I am using "C" and JNI to call Java classes in my application which is a DLL.
         cipherFile = fopen ( "C:\\ciphertext.1-6", "w" );
         if (cipherFile==NULL)
             printf("\nCan't open cipherFile\n");
             return -1;        
         fprintf(cipherFile, "%s", pass2EncToXUTF);                           
         // obtain file size.
        fseek (cipherFile , 0 , SEEK_END);
        lSize = ftell (cipherFile);
        printf("Size of cipherFile file:  %d\n", lSize);
        rewind (cipherFile);
         fclose(cipherFile);--------------------------------------------------------------------------------
    Here is the output.....
    John Doe 123-45-6789 1234567890123456 01/01/1950
    Jane Doe 234-56-7890 2345678901234567 02/02/1951
    John Smith 345-67-8901 3456789012345678 03/03/1952
    Jane Smith 456-78-9012 4567890123456789 04/04/1953
    John Walker 567-89-0123 5678901234567890 05/05/1954
    Jane Walker 678-90-1234 6789012345678901 06/06/1955
    John Asia 789-01-2345 7890123456789012 07/07/1956
    John Africa 890-12-3456 8901234567890123 08/08/1957
    John Europe 901-23-4567 9012345678901234 09/09/1958
    John America 012-34-5678 0123456789012345 10/10/1959
    ��������������
    As you can see, there is some garbage printed at the end of file. Why?
    Any help will be greatly appreciated. Thanks in advance.

    Sorry about that.
    Here's the code for jstring pass2EncToXUTF.
    pass2EncToXUTF = (*env)->GetStringUTFChars(env, resultOfEncToX, 0);
          if (pass2EncToXUTF == NULL) {
            printf("pass2EncToXUTF is null\n");
            exit(1);
          printf("\nResult of pass2EncToXUTF: %s\n", pass2EncToXUTF);

  • Help calling JNI function from a java thread

    I am using the following code to call a JNI fuction from a java thread:
    public class CMSMessageHandler extends MessageHandler{
    static{
    System.loadLibrary("jastb");
    public native int cmsReadIt(ByteBuffer buff);
    private ByteBuffer dirbuf = null;
    /** Creates a new instance of CMSMessageHandler */
    public CMSMessageHandler() {
    // allocate to max size datagram
    dirbuf = ByteBuffer.allocateDirect(65536);
    public void readMessages(){
    /*Thread worker = new Thread(){
    public void run(){*/
    int count;
    while (true){
    try{
    count = cmsReadIt(dirbuf);
    } catch (Exception e){
    e.printStackTrace();
    worker.start();*/
    public static void main(String[] args) {
    CMSMessageHandler handler = new CMSMessageHandler();
    handler.readMessages();
    When I run this main method with the thread commented out, it works great. When I run the main method with the thread, it works great for a while, and then funny things start happening with the native library I am using. My native library uses shared memory, signals, and semaphores. It feels a bit like my java program is stomping on the resources that my native library is using, when a run the java program with a thread.
    Is there something I don't know about calling native code from a thread? Should I be doing something explicitly to protect my native library's shared memory, signals, or semaphores?
    Thanks,
    Lisa.

    Does the library do any initialization when loaded? Does it make a dangerous assumption that the thead calling cmdReadIt will always be the same thread that initially loaded it? Try loading the library in the worker thread instead of in the main thread via the static initializer.Yes. There is a call to another native method cmsOpenIt that does CMS initialization. I put cmsOpenIt as well as the System.loadLibrary("jastb") in the worker thread and I'm still experiencing the same problems.
    Incidently, the mere presence of another Thread in this program does not seem to cause problems. It's only when I run calls to cmsReadIt in a thread that I get into trouble.
    For example, this works fine:
    public class CMSMessageHandler extends MessageHandler{
        public native int cmsReadIt(ByteBuffer buff);
        public ByteBuffer dirbuf = null;
        static {
            System.loadLibrary("jastb");
        public CMSMessageHandler() {
            // allocate to max size datagram
            dirbuf = ByteBuffer.allocateDirect(65536);
        public void readMessages(){
            try{
                int count = 0;
                while (true){
                    count = cmsReadIt(dirbuf);
            } catch (Exception e){
        public static void main(String[] args) {
            CMSMessageHandler handler = new CMSMessageHandler();
            Thread worker = new Thread(){
                public void run(){
                    while (true){
                        try{
                            Thread.currentThread().sleep(1000);
                            System.out.println("sleep thread.");
                        } catch (Exception e){
                            e.printStackTrace();
            worker.start();
            handler.readMessages();  
        }Are there JVM flags that I should experiment with that might help mitigate/diagnose this problem?

  • Help: I'm sure it is a Bug in JNI calling WebLogic EJB

    Help me! I'm using jni to call weblogic EJB from a Com+ component,here is the code:
    // This is the main project file for VC++ application project
    // generated using an Application Wizard.
    #include "stdafx.h"
    #pragma unmanaged
    #include <windows.h>
    #include <jni.h>
    #include <process.h>
    #include <stdio.h>
    #define USER_CLASSPATH "C:\\myClasses;C:\\j2sdk1.4.0\\lib\\tools.jar;Z:\\wlserver6.1\\lib\\weblogic.jar;"
    /* where Prog.class is */
    JavaVM *jvm;
    * Function GetJNIEnv(void) returns the java environment pointer
    * in case we are executing on a thread other than the one the
    * jvm was created on.
    JNIEnv* GetJNIEnv(void){
         JNIEnv *env = NULL;
         jint nRet = jvm->GetEnv((void **)&env, JNI_VERSION_1_2);
         if(nRet == JNI_EDETACHED){
              jvm->AttachCurrentThread((void **)&env, NULL);
         return env;
    * Function DoJNDI(void *arg) uses the Java Invocation API to
    * execute the following Java code:
    * Hashtable prop = new Hashtable();
    * prop.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"
    * prop.put( Context.PROVIDER_URL, "t3://192.168.40.137:7001" );
    * ctxInitial = new InitialDirContext( prop );
    void DoJNDI(void *arg){
         jclass clsHash, clsInitDirCx;
         jmethodID mHashInit, mHashPut, mInitDirCxInit;
         jobject objHash, objInitDirCx;
         JNIEnv *env = GetJNIEnv(); // Get the environment if on a different thread
         clsHash = env->FindClass("java/util/Hashtable");
         mHashInit = env->GetMethodID(clsHash, "<init>", "()V");
         objHash = env->NewObject(clsHash, mHashInit);
         mHashPut = env->GetMethodID(clsHash, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
         jstring jstrICxFactoryPut = env->NewStringUTF("java.naming.factory.initial");
         jstring jstrICxFactoryVal = env->NewStringUTF("weblogic.jndi.WLInitialContextFactory");
         env->CallObjectMethod(objHash, mHashPut, jstrICxFactoryPut,jstrICxFactoryVal);
         jstring jstrProviderUrlPut = env->NewStringUTF("java.naming.provider.url");
         jstring jstrProviderUrlVal = env->NewStringUTF("t3://192.168.40.137:7001");
         env->CallObjectMethod(objHash, mHashPut, jstrProviderUrlPut,jstrProviderUrlVal);
         clsInitDirCx = env->FindClass("javax/naming/InitialContext");
         mInitDirCxInit = env->GetMethodID(clsInitDirCx, "<init>", "(Ljava/util/Hashtable;)V");
         objInitDirCx = env->NewObject(clsInitDirCx, mInitDirCxInit, objHash);
         if(objInitDirCx == NULL){
              printf("%s test FAILED:\n\n", (char*)arg);
         else{
              printf("%s test PASSED\n\n", (char*)arg);
         jvm->DetachCurrentThread();
    * Function main(void) creates a JVM, and calls DoJNDI twice:
    * Once as a regular function call, and once as a spun off thread.
    void main() {
    JavaVMInitArgs vm_args;
    JavaVMOption options[5];
         options[0].optionString = "-client";
    options[1].optionString =
    "-cp " USER_CLASSPATH;
    options[2].optionString =
    "-Djava.class.path=" USER_CLASSPATH;
         //options[3].optionString =
         //     "-Xbootclasspath:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;z:\\wlserver6.1\\lib\\weblogic.jar;";
         options[3].optionString =
              "-Xbootclasspath/a:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;";
         options[4].optionString =
              "-Xbootclasspath/p:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;";
    vm_args.version = 0x00010002;
    vm_args.options = options;
    vm_args.nOptions = 5;
    vm_args.ignoreUnrecognized = JNI_TRUE;
         JNIEnv *env;
         jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
         // *** Make the magic calls! (Both lines should do the same thing) ***
         DoJNDI((void*)"Function call");
         _beginthread(DoJNDI,0,(void *)"Thread call");
         /* wait for thread(s) to finish */
         Sleep(5000);
         jvm->DestroyJavaVM();
    But it always send me a Exception like below:
    javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory.
    Root exception is java.lang.ClassNotFoundException: weblogic/jndi/WLInitialContextFactory
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:207)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:42)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:649)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:243)
    at javax.naming.InitialContext.init(InitialContext.java:219)
    at javax.naming.InitialContext.<init>(InitialContext.java:195)
    when I search this problem in java.sun.com,an article announce that it is a bug that
    JNDI not support multi-threads call,and it is fixed is JDK1.4 beta. The link is:
    http://developer.java.sun.com/developer/bugParade/bugs/4307751.html
    It seems that weblogic's JNDI is not support multi-thread call. what can i do?

    Try adding the following code before instantiating your initial context:
    Thread.currentThread().setContextClassLoader( ClassLoader.getSystemClassLoader()
    This fixed the problem for me.
    -Brian
    "Edward Lu" <[email protected]> wrote:
    >
    Help me! I'm using jni to call weblogic EJB from a Com+ component,here is
    the code:
    // This is the main project file for VC++ application project
    // generated using an Application Wizard.
    #include "stdafx.h"
    #pragma unmanaged
    #include <windows.h>
    #include <jni.h>
    #include <process.h>
    #include <stdio.h>
    #define USER_CLASSPATH "C:\\myClasses;C:\\j2sdk1.4.0\\lib\\tools.jar;Z:\\wlserver6.1\\lib\\weblogic.jar;"
    /* where Prog.class is */
    JavaVM *jvm;
    * Function GetJNIEnv(void) returns the java environment pointer
    * in case we are executing on a thread other than the one the
    * jvm was created on.
    JNIEnv* GetJNIEnv(void){
         JNIEnv *env = NULL;
         jint nRet = jvm->GetEnv((void **)&env, JNI_VERSION_1_2);
         if(nRet == JNI_EDETACHED){
              jvm->AttachCurrentThread((void **)&env, NULL);
         return env;
    * Function DoJNDI(void *arg) uses the Java Invocation API to
    * execute the following Java code:
    * Hashtable prop = new Hashtable();
    * prop.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"
    * prop.put( Context.PROVIDER_URL, "t3://192.168.40.137:7001" );
    * ctxInitial = new InitialDirContext( prop );
    void DoJNDI(void *arg){
         jclass clsHash, clsInitDirCx;
         jmethodID mHashInit, mHashPut, mInitDirCxInit;
         jobject objHash, objInitDirCx;
         JNIEnv *env = GetJNIEnv(); // Get the environment if on a different thread
         clsHash = env->FindClass("java/util/Hashtable");
         mHashInit = env->GetMethodID(clsHash, "<init>", "()V");
         objHash = env->NewObject(clsHash, mHashInit);
         mHashPut = env->GetMethodID(clsHash, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
         jstring jstrICxFactoryPut = env->NewStringUTF("java.naming.factory.initial");
         jstring jstrICxFactoryVal = env->NewStringUTF("weblogic.jndi.WLInitialContextFactory");
         env->CallObjectMethod(objHash, mHashPut, jstrICxFactoryPut,jstrICxFactoryVal);
         jstring jstrProviderUrlPut = env->NewStringUTF("java.naming.provider.url");
         jstring jstrProviderUrlVal = env->NewStringUTF("t3://192.168.40.137:7001");
         env->CallObjectMethod(objHash, mHashPut, jstrProviderUrlPut,jstrProviderUrlVal);
         clsInitDirCx = env->FindClass("javax/naming/InitialContext");
         mInitDirCxInit = env->GetMethodID(clsInitDirCx, "<init>", "(Ljava/util/Hashtable;)V");
         objInitDirCx = env->NewObject(clsInitDirCx, mInitDirCxInit, objHash);
         if(objInitDirCx == NULL){
              printf("%s test FAILED:\n\n", (char*)arg);
         else{
              printf("%s test PASSED\n\n", (char*)arg);
         jvm->DetachCurrentThread();
    * Function main(void) creates a JVM, and calls DoJNDI twice:
    * Once as a regular function call, and once as a spun off thread.
    void main() {
    JavaVMInitArgs vm_args;
    JavaVMOption options[5];
         options[0].optionString = "-client";
    options[1].optionString =
    "-cp " USER_CLASSPATH;
    options[2].optionString =
    "-Djava.class.path=" USER_CLASSPATH;
         //options[3].optionString =
         //     "-Xbootclasspath:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;z:\\wlserver6.1\\lib\\weblogic.jar;";
         options[3].optionString =
              "-Xbootclasspath/a:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;";
         options[4].optionString =
              "-Xbootclasspath/p:c:\\j2sdk1.4.0\\lib\\tools.jar;z:\\wlserver6.1\\lib\\weblogic_sp.jar;";
    vm_args.version = 0x00010002;
    vm_args.options = options;
    vm_args.nOptions = 5;
    vm_args.ignoreUnrecognized = JNI_TRUE;
         JNIEnv *env;
         jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
         // *** Make the magic calls! (Both lines should do the same thing) ***
         DoJNDI((void*)"Function call");
         _beginthread(DoJNDI,0,(void *)"Thread call");
         /* wait for thread(s) to finish */
         Sleep(5000);
         jvm->DestroyJavaVM();
    But it always send me a Exception like below:
    javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory.
    Root exception is java.lang.ClassNotFoundException: weblogic/jndi/WLInitialContextFactory
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:207)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:42)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:649)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:243)
    at javax.naming.InitialContext.init(InitialContext.java:219)
    at javax.naming.InitialContext.<init>(InitialContext.java:195)
    when I search this problem in java.sun.com,an article announce that it is
    a bug that
    JNDI not support multi-threads call,and it is fixed is JDK1.4 beta. The
    link is:
    http://developer.java.sun.com/developer/bugParade/bugs/4307751.html
    It seems that weblogic's JNDI is not support multi-thread call. what can
    i do?

Maybe you are looking for

  • HT4061 I am locked out of my Ipad it wants my passcode that I do not have?

    Iam locked out of my Ipad. It wants a passcode that I do not have. I have tried the re-boot and that did not work. This is a hand me down ipad and it was working for about a month then today it wanted this passcode? Don't know what to do I have a pc

  • Landscape Problems with Crystal Reports 2008 SP3

    My initial install of Crystal Reports 2008 was SP2 (12.2.0.290).  After installing SP3 and Fix Pack 3.3, I started to experience problems with reports in landscape orientation. The reports are set up as 11x8.5 in landscape.  They are loaded into a th

  • Cards app: how to delete saved cards

    In the Cards app: Ow can I delete cards that I have previously saved but no longer want anymore? I can't find a way to do it anywhere, please help me out! And if it isn't an option, why the heck not? I've only sent a total of three cards, but I have

  • Can I boot mac from an external hard drive (internal hard drive hard drive closure)

    Model: Macbook Pro 2010 mid OS: OSX 10.9 Hard Drive: WD5000BPKT 500GB For some reason I need to change my perfectly working internal bootable drive to external bootable drive. I took out my internal hard drive, put it into closure, and then connected

  • Where is the administrator?

    OK, I'm struggling here. I can't login to these forums on my Mac. Attempting to login from Safari v 3.2.1 results in this: Error page exception The server cannot use the error page specified for your application to handle the Original Exception print