Possible thread issues when calling java from C++/Delphi/C#

Hi,
We have a java API for one of our applications. This API has wrapper API's in C++, Delphi and C#. There are two main top level classes in te API - Client and Receiver. Both haave a receive() method.
We used to ship JRE1.3 with the API installation - this was needed to suport the user applications. Recently we haev moved to java 1.4 as the least suported version.
We have two ways of using the java API in our wrapper API's.
Method one, we instantiate the client, and call client.receive(). There are no threads etc involved here. This is working fine.
In the second method, we set a callback on the client, which starts a thread (in C++/Delphi or C#) which calls receiver.receive() and tries to get the message. This is failing.
It fails at a line which simply says "DocumentBuilderFactory.newInstance()".
This call has already been made when connecting the client and it is successful because we can see the client connected.
Whether we do client.receive() or receiver.receive() in a thread, the code passes through this line.But is throwing the exception only when we come to it through a thread.
Any ideas on what I need to watch out for when calling methods on a JVM from a thread in C++/Delphi or C#?
Thanks
Hari
PS: I know we are using some really old versions, but thats needed and out of my control.

Hi,
I managed to solve this - finally!
This is what was the cause in our case - should apply to all situations though.
We had the Xerces classes packaged in a custom jar file along with other XML stuff we have. And this mega-jar was on the class path.
We were running everything on Java 1.3 and it worked fine.
But Java 1.4 wrecked all havoc.
So here is what I did:
1. I tried explicitly doing Class.forName() with the name of the Xerces class that was not found. I did this at the same point in the code where the exception was being thrown.
2. The class was successfully loaded indicating that it was on the class path somewhere.
3. Java 1.4 made some changes in terms of class loaders - so suspecting that, I tried printing out the System and the Context class loaders at the point where the exception was being thrown - the system class loader was a valid object, but context class loader was null
4. We have another point in the code base where the exact same lines were used, and these are getting successfully executed even in the multi threaded situation - this is the start up sequence.
5. I printed the two class loaders at this point - they are both valid objects, no nulls.
With this, I narrowed down the scope and was convinced that the class loaders are the cause.
A search on Google and after looking the the source code for Xerces, we realized that the Xerces API uses the Context Class Loader to resolve and load the DocumentFactoryImpl class - this change is from Java 1.4 onwards.
In our case, the JNI AttachCurrentThread method called from C++/C# and Delphi was attaching the thread to the JVM, but each time the context class loader was null.
We could not find anything on how we could make the method to put a non null context classloader.
So, we changed all our JNI interfaces to do the following
//attach the current thred
jvm->AttachCurrentThread(...)
//now get the system class loader and set it as the context class loader on the current thread
//get things from the Thread class
jclass thread = get the thread class
jmethod currentThread = get the static method currentThread()
jobject thread_object = get the current thread object into this
jmethod setContextClassLoader = get the setContextClassLoader() method on the thread
//get the SystemClassLoader
jclass clsLoader = get the class for ClassLoader
jmethodid getSysClsLoader = get the method ID for the getSystemClassLoader() method
jobect sysClsLoader = get the system class loader by calling the above method
//set the context class loader on the thread by calling set context class loader with the sys class loader as the argumentUnfortunately I don't have the code with me right now,otherwise would have shared the same.

Similar Messages

  • ResourceBundle throws MissingResourceException when calling Java from C

    All,
    Our code calls Java from C application.
    The C code create JVM using JNI_CreateJavaVM. Due to internal design issues we don't
    create the JVM with a "-classpath" option.
    After creating the JVM, we create a ClassLoader (URLClassLoader), with a URL list as it's classpath.
    The last step in the C code is to load a Java class using the C reference to URLClassLoader.loadClass
    (I will refer to this class as classA), and than call one of it's static methods.
    Please notice that classA is not instantiated, we call a static method.
    At this point we are moving to the Java code...
    In the Java static method we call ResourceBundle.getBundle("resources.messages"),
    the result is ResourceBundle throws MissingResourceException.
    - The JAR hosting "resources/messeges.properties" (refer as jarA) is include in the
    ClassLoader URL paths we used for loading the Java class.
    - Using a debugger we can see that ClassLoader.getSystemClassLoader() don't contain
    jarA in it's URL list.
    - Using the debugger we see that classA.class.getClassLoader() does contain
    jarA in it's URL list.
    After some investigation we see that ResourceBundle.getBundle calles to ResourceBundle.getLoader:
    private static ClassLoader getLoader() {
            Class[] stack = getClassContext();
            /* Magic number 2 identifies our caller's caller */
            Class c = stack[2];
            ClassLoader cl = (c == null) ? null : c.getClassLoader();
            if (cl == null) {
                cl = ClassLoader.getSystemClassLoader();
            return cl;
        } getClassContext() - native method, this can explain the why the above work fine for Windows.
    I suspect the problem raised in the above code. Since I couldn't get a debug
    version of rt.jar for Solaris, I need some help.
    Our environment is Solaris 8, Java 1.5.
    Please note that the same code works fine on WindowsXP with the same Java version!
    Thanks,
    Avi

    I was thinking JVM should the classpath when it is invoked. But obviously it is not and we need to assign the classpath ourselves when invoking from native side. Thanks for pointing that out. For other people's benefit the following is the code piece I for initializing JVM.
    char* str1;
              char* str2;
              char* classpath;
              str1 = "-Djava.class.path=";
              str2 = std::getenv("CLASSPATH");
              classpath = (char*)malloc(strlen(str1) + strlen(str2) + 1);
              strcpy(classpath, str1);
              strcat(classpath, str2);
              if (str2 == NULL)     {
                   printf("CLASSPATH environment variable is not defined.");
                   exit(1);
              m_VmArgs.version = JNI_VERSION_1_4;
              m_options[0].optionString= classpath;
              m_VmArgs.options = m_options;
              m_VmArgs.nOptions = 1;
              m_VmArgs.ignoreUnrecognized = JNI_TRUE;
              JNI_GetDefaultJavaVMInitArgs(&m_VmArgs);
              /* Create the Java VM */
              m_Res = JNI_CreateJavaVM(&m_Jvm, (void**)&m_Env, &m_VmArgs);
              if (m_Res < 0) {
                   printf("Can't create JVM\n");
                   exit(1);
    thanks,
    chancellor

  • Performance issue when calling java module

    Hi experts,
    It takes much time to call Java module 'JBND_CRM_SVY_XSLT_TRANSFORM' from abap function module.
    When I executed runtime analysis via t-cd:se30,
    most of time is consumed in 'wait for RFC' .
    When the java module is called, it always takes much time.
    I think VMC memory management is not the cause,
    because the issue also occurs at first call.
    The kernel patch level is 146 of release 700.
    Do you have any idea to improve performance?
    Regards,
    Fukuhara Yohei

    Hi
    try with this code
    remove
    READ TABLE i_events INTO wa_events WITH KEY name = 'USER_COMMAND'.
    IF sy-subrc EQ 0.
    wa_events-form = 'USER_COMMAND'.
    MODIFY i_events FROM wa_events TRANSPORTING form WHERE name =
    wa_events-name.
    ENDIF.
    and change alv
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
    EXPORTING
    i_callback_program = sy-repid
    i_callback_user_command = 'USER_COMMAND'
    it_fieldcat = i_ztal_prof1_cat[]
    i_save = 'A'
    TABLES
    t_outtab = i_ztal_prof1.
    Marco

  • ClassDefNotFound error when calling Java from C++

    Hi all,
    I have a problem with calling my java from C++ through JNI.
    I have set my CLASSPATH environment varible that include path to every libary that I need. My source is as follows:
    #include <jni.h>
    #include <stdio.h>
    int main()     
         JNIEnv               *env;
         JavaVM               *jvm;
         JavaVMInitArgs     vm_args;
         jint               res;
         jclass               cls;
         jmethodID          mid;
    IMPORTANT: specify vm_args version # if you use JDK 1.1.2 and beyond
         vm_args.version = JNI_VERSION_1_4;
         vm_args.ignoreUnrecognized = JNI_TRUE;
         JNI_GetDefaultJavaVMInitArgs(&vm_args);
         /* Create the Java VM */
         res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
         if (res < 0) {
              printf("Can't create JVM\n");
              return 1;
         cls = (env)->FindClass ("dds/test/comm/listeners/NACKListenerFrame");
         if (cls == 0)     {
              printf("Can't find NACKListenerFrame Class\n");
              return 1;
    mid = (env)->GetStaticMethodID(cls, "start", "()V");
         if (mid == 0)     {
              printf("Can't find NackListnerFrame.start \n");
              return 1;
         (env)->CallStaticVoidMethod((_jclass*)cls, (_jmethodID*)mid, NULL);
         jthrowable e = (env)->ExceptionOccurred();
         if (e)     {
              env->ExceptionDescribe();
              env->ExceptionClear();
         if ((jvm)->DestroyJavaVM() < 0)     {
              printf("Cannot destroy JVM./n");     
         return 0;
    I deliberately left out the codebelow because I want the JVM I created to load Classes from the system's CLASSPATH variable as I have set path to every classes that I need, in that CLASSPATH variable.
    JavaVMOption     options[1];
    options[0].optionString=
    "-Djava.class.path=.;E:/DDSproject/DDSImplementation/classes";
    vm_args.options = options;
    vm_args.nOptions = 1;
    But it seems like unless I specify CLASSPATH in my C++ source code the JVM could not find any classes.
    I tried to put the "jvm.dll" path to the first one in the System's PATH variable. It does not work either...
    Gurus Pls help!!!.. I don't know what to do... I don't wanna code my CLASSPATH in my c++ source code as above.
    Thanks in advance,
    chancellor

    I was thinking JVM should the classpath when it is invoked. But obviously it is not and we need to assign the classpath ourselves when invoking from native side. Thanks for pointing that out. For other people's benefit the following is the code piece I for initializing JVM.
    char* str1;
              char* str2;
              char* classpath;
              str1 = "-Djava.class.path=";
              str2 = std::getenv("CLASSPATH");
              classpath = (char*)malloc(strlen(str1) + strlen(str2) + 1);
              strcpy(classpath, str1);
              strcat(classpath, str2);
              if (str2 == NULL)     {
                   printf("CLASSPATH environment variable is not defined.");
                   exit(1);
              m_VmArgs.version = JNI_VERSION_1_4;
              m_options[0].optionString= classpath;
              m_VmArgs.options = m_options;
              m_VmArgs.nOptions = 1;
              m_VmArgs.ignoreUnrecognized = JNI_TRUE;
              JNI_GetDefaultJavaVMInitArgs(&m_VmArgs);
              /* Create the Java VM */
              m_Res = JNI_CreateJavaVM(&m_Jvm, (void**)&m_Env, &m_VmArgs);
              if (m_Res < 0) {
                   printf("Can't create JVM\n");
                   exit(1);
    thanks,
    chancellor

  • Problem calling java from vb via activex bridge

    I am trying to call java from vb via ActiveX Bridge and I am running into problems. I would appreciate any help.
    I am using Visual Basic 2010 express, and Java JDK 1.6.0_16. I have used the http://download.oracle.com/javase/1.4.2/docs/guide/beans/axbridge/developerguide/index.html page as a guideline. To try to make it work I took the following steps:
    1. Wrote a very simple java class (below):
    package xxx;
    import java.io.Serializable;
    public class axb implements Serializable {
    public int get_axb_Handle() {
    int Address = 12345678;
    return Address;
    2. After I compiled, and created the jar file. I built the dll using the following command:
    "C:\Program Files\Java\jdk1.6.0_16\bin\packager" -out "C:\Program Files\Java\jdk1.6.0_16\jre\axbridge\bin" E:\axb\dist\axb.jar xxx.axb
    3. I then registered using: regsvr32 axb.dll
    4. In Visual Basic Express IDE I use Project -> Add Reference to add Iterop.axb (dump below), and axb namespace
    5. In my basic code I use the following lines
    Dim axb1 As axb.axb
    axb1 = New axb.axb <== Crash here with AccessViolationException ( full exception below)
    What am I missing? Any help would be greatly appreciated
    Thanks
    Iterop.axb partial dump
    ___[MOD] C:\Documents and Settings\Elie A. Cohen.USINC022\My Documents\Visual Studio 2010\Projects\Repo API Example\Repo API Example\obj\x86\Release\Interop.axb.dll
    | M A N I F E S T
    |___[NSP] axb
    | |___[INT] axb.axb
    | | | .class interface public abstract auto ansi import /*02000006*/
    | | | implements axb.axbDispatch/*02000003*/
    | | | implements axb.axbSource_Event/*02000005*/
    | | | .custom /*0C000018:0A000001*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.GuidAttribute/*01000002*/::.ctor(string) /* 0A000001 */ = ( 01 00 24 34 45 36 44 30 44 41 38 2D 36 41 45 44 // ..$4E6D0DA8-6AED ...
    | | | .custom /*0C000019:0A000007*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.CoClassAttribute/*01000009*/::.ctor(class [mscorlib/*23000001*/]System.Type/*01000007*/) /* 0A000007 */ = ( 01 00 0C 61 78 62 2E 61 78 62 43 6C 61 73 73 00 // ...axb.axbClass. ...
    | |
    | |___[CLS] axb.axbClass
    | | | .class public auto ansi import /*02000004*/
    | | | implements axb.axbDispatch/*02000003*/
    | | | implements axb.axb/*02000006*/
    | | | implements axb.axbSource_Event/*02000005*/
    | | | .custom /*0C00000F:0A000008*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.ClassInterfaceAttribute/*0100000A*/::.ctor(int16) /* 0A000008 */ = ( 01 00 00 00 00 00 ) ...
    | | | .custom /*0C000010:0A000009*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.ComSourceInterfacesAttribute/*0100000B*/::.ctor(string) /* 0A000009 */ = ( 01 00 0F 61 78 62 2E 61 78 62 53 6F 75 72 63 65 // ...axb.axbSource ...
    | | | .custom /*0C000011:0A000001*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.GuidAttribute/*01000002*/::.ctor(string) /* 0A000001 */ = ( 01 00 24 43 44 42 46 36 42 33 33 2D 45 32 33 46 // ..$CDBF6B33-E23F ...
    | | | .custom /*0C000012:0A000002*/ instance void [mscorlib/*23000001*/]System.Runtime.InteropServices.TypeLibTypeAttribute/*01000003*/::.ctor(int16) /* 0A000002 */ = ( 01 00 02 00 00 00 ) ...
    | | |___[MET] method .ctor : void()
    | | |___[MET] method equals : bool(object)
    | | |___[MET] method getClass : object()
    | | |___[MET] method get_axb_Handle : int32()
    | | |___[MET] method hashCode : int32()
    | | |___[MET] method notify : void()
    | | |___[MET] method notifyAll : void()
    | | |___[MET] method toString : string()
    | | |___[MET] method wait : object(object,object)
    AccessViolationException exception
    System.AccessViolationException was unhandled
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=mscorlib
    StackTrace:
    at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
    at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
    at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
    at System.Activator.CreateInstance(Type type)
    at WindowsApplication1.Form1.getPatientHandle_Click(Object sender, EventArgs e) in C:\Documents and Settings\Elie A. Cohen.USINC022\my documents\visual studio 2010\Projects\Repo API Example\Repo API Example\Repo API Example.vb:line 13
    at System.Windows.Forms.Control.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
    at System.Windows.Forms.Button.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.Run(ApplicationContext context)
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
    at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException:

    In case you haven't figured it out already... Or if anyone else is curious... Or for myself when I get old and forgetful...
    h2. Object Creation
    For starters, when you create an ActiveX object from within VB, use:
    Set myObject = CreateObject("JavaObject.Bean")When I refer to JavaObject.Bean, I'm meaning the full object name + ".Bean". So, in your case, you should use:
    Set myObject = CreateObject("xxx.axb.Bean")h2. Location
    The .dll file must be located in the JRE that is used at the time of calling. Meaning, the .dll file must be placed under <jre_home>\axbridge\bin and registered there.
    In your case:
    DLL:
    C:\Program Files\Java\jre6\axbridge\bin
    Jar:
    C:\Program Files\Java\jre6\axbridge\libh4. A Note:
    The only supported JRE is a 32bit version as far as I know with regards to the ActiveX bridge. Just like the packager.exe can only be found in the 32bit JDK.
    h2. Methods
    h3. Object Types
    ActiveX Bridge does not support passing literals or arrays. However, it does support passing java's primitive data types as Objects.
    Simply meaning:
    h4. Invalid:
    public int get_axb_Handle() {
         int Address = 12345678;
         return Address;
    }h4. Valid:
    public Integer get_axb_Handle() {
         int Address = 12345678;
         return Address;
    }On a normal circumstance, there's little difference between the two methods. However, in the second example, the JVM does a typecast from a literal data type to a object data type, resulting in a valid object to pass through to Visual Basic. Now, obviously there are multiple ways to do a proper change, new Integer(int) for example. It doesn't matter to me. At the end of the day, you have to pass an object.
    As a side note, the same idea applies when receiving data from Visual Basic.
    h4. Invalid:
    public void set_axb_Handle(int newHandle) {
         int Address = newHandle;
    }h4. Valid:
    public void set_axb_Handle(Integer newHandle) {
         int Address =newHandle;

  • Call java from sybase trigger

    Is it possible to call java from Sybase trigger ? If so can you please supply example or URL to one ? Alternative solution is to call shell script from sybase trigger (as app is based on Solaris).
    Regards
    Michal

    Thank for your opinion, but what idea is better ?Doing things in the middle tier, where Java lives.
    Ever heard of event-based trading systems?
    pooling a table every 30 sec. ?. I need to implment
    real-time system which process each trade from table
    once it appears there.Sounds like you have it backwards - you're trying to drive Java from the database.
    I think it'd be better to write that event-based system in Java and leave the database just for persistence.
    GigaSpaces and their ilk are being used this way for highly transactional trading systems. Maybe you could see how they're doing it.
    %

  • Can't create DeliveryBean when call bpel from jsp

    Can't create DeliveryBean when call bpel from jsp
    /*** code ********************************/
    Properties props = new java.util.Properties();
    java.net.URL url = ClassLoader.getSystemResource("context.properties");
    props.load(url.openStream());
    Locator locator = new Locator(domain, "bpel", props);
    IDeliveryService deliveryService = (IDeliveryService)locator.lookupService(IDeliveryService.SERVICE_NAME);
    NormalizedMessage nm = new NormalizedMessage();
    String convId = GUIDGenerator.generateGUID();
    nm.setProperty(NormalizedMessage.CONVERSATION_ID, convId);
    nm.addPart("payload", xml);
    NormalizedMessage res = deliveryService.request(processID,operationName, nm);
    /*** code ********************************/
    This code works well in java , but when I use it in jsp on tomcat server,
    the following exception ocured:
    Can not create "ejb/collaxa/system/DeliveryBean" bean; exception reported is: "javax.naming.NameNotFoundException: Name ejb is not bound in this Context at org.apache.naming.NamingContext.lookup(NamingContext.java:768) at org.apache.naming.NamingContext.lookup(NamingContext.java:151) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:136) at javax.naming.InitialContext.lookup(InitialContext.java:351) at com.oracle.bpel.client.util.BeanRegistry.lookupDeliveryBean(BeanRegistry.java:279) at com.oracle.bpel.client.delivery.DeliveryService.getDeliveryBean(DeliveryService.java:250) at com.oracle.bpel.client.delivery.DeliveryService.request(DeliveryService.java:83) at com.oracle.bpel.client.delivery.DeliveryService.request(DeliveryService.java:53) at workflow.bpel.BpelProcessHelper.invokeSyncBpel(BpelProcessHelper.java:54) at
    Will anyone to tell me where "ejb/collaxa/system/DeliveryBean" bean is?
    Which jar file is this class in ?
    Thanks

    did you try including bpel/lib/orabpel.jar & bpel/system/server/j2ee/ob_ejb_engine.jar in your tomcat classpath.

  • I am receiving this error message when trying to export pictures: 'Unable to Export": An internal error has occured: Win32 API error 2 ( "The system cannot find the file specified.") when calling ShellExecuteExW from AgWorkspace.shellExecute.// I have a H

    I am receiving this error message when trying to export pictures: 'Unable to Export": An internal error has occured: Win32 API error 2 ( "The system cannot find the file specified.") when calling ShellExecuteExW from AgWorkspace.shellExecute.// I have a HP ENVY Phoenix, fully loaded, 1 1/2 years old.

    Nevermind I fixed it. Thank you.

  • Call java from ABAP

    JCo connectivity is used to call RFCs from Java. can i call Java from abap?
    thanks in advance.....
    regards,
    Sundararamaprasad

    Hi Sundar ,
             This link will surely give u an idea about calling java fro ABAP using Jco.
    http://www.thespot4sap.com/Articles/SAP_Netweaver_Java_Connector.asp
    regards,
    aravindh.

  • Calling Java from Delphi

    Can ActiveX bridge used for calling Java from Delphi?

    Also trying to solve this problem, after creating the bean i packaged/registered it successfully, (tested the bean using beanbox, works perfectly) then tried calling it via createoleobject in delphi 7
    (*Code Snip *)
    Var
    v : variant;
    begin
    try
    v := createoleobject(Edit1.text); // my class name ie WorldPort.Bean (also tried WorldPort.Bean.1
    except on e:exception do
    showmessage(e.Message)
    end;
    end;
    (*Code Snip*)
    After this simple code failed i started backtracking , eventually after getting "Access Violation...etc in axbridge.dll" all the time. tried delphi "import activex control" got the same access violation.
    Decided to test the example from http://java.sun.com/j2se/1.4.2/docs/guide/beans/axbridge/developerguide/examples.html........ they both crashed on execution (calc.exe and boundprop.exe).
    After this failed I tested these example classes on another machine, both crashed again.....
    Also tried this experiment in VC++ , after adding the class to the Toolbox , i try to drop it onto a form, once again access violation.**PS**
    ('You will need VC++ and the Microsoft SDK to build the dll, download c++beta for free from microsoft site it you need it')** and a simple cmd file todo the job would look something like this:
    echo - ** Build Java ActiveX Bridge **
    echo Make sure these folders exist in jre--> axbridge\lib and axbridge\bin
    cd\SDK\jre\axbridge\bin
    set path=%path%;C:\MSDN\Bin;C:\VisualC++\lib
    echo path
    javac WorldPort.java
    jar cmf Manifest.txt WorldPort.jar WorldPort.class
    "C:\SDK\bin\packager.exe" -clsid {162193C4-AD5C-4A06-9F88-A737AE9B43AD} -out "C:\SDK\jre\axbridge\bin" WorldPort.jar WorldPort-reg
    *** After running this cmd you will find the dll in bin folder and the jar in lib folder..***
    Must Read:http://java.sun.com/j2se/1.4.2/docs/guide/beans/axbridge/developerguide/index.html
    Hope some of this helps , if you have successfully created / installed/ used a "JavaActiveX" in Delphi , i would really like to try replicate it on my machine..

  • Advantages and Disadvantages of calling java from PL/SQL

    Hi,
    I have one doubt. What are all the advantages and disadvantages of the calling java from PL/SQL?
    In actual scenario the java program will be in the Application server side. It will do the operation and it will store the result in Data base. But in this case (calling java from PL/SQL), we are loading the java program in the Data base and it is doing the operations.
    I have seen many posts are coming regarding loading jar files into the database. Actually the jar will deploy in to Application server. Is there any difference instead of keeping in the Application server side?
    Then I have read,
    advantages:
    -> java having lot API's. so PL/SQL can use that API's.
    -> if we can not do anything in PL/SQL. we can do it using this mtd(calling java from PL/SQL).
    My questions:
    -> could you explain what are all the things we can not do but we can do using "calling java from PL/SQL" method?
    -> is there any other advantages?
    Disadvantages:
    -> the performance is very slow in calling java from PL/SQL.
    My questions:
    -> Then why others are loading java files and jar files into database?
    -> is there any other disadvantages?
    Could you explain about this one? It will be more helpful to others also…
    Regards,
    kk

    Hi,
    You can read the free first chapter of my book @ http://www.amazon.com/gp/product/1555583296/ (see details then Excerpt)
    Kuassi http://db360.blogspot.com

  • Questions abt. calling Java from C

    I have a java class that contains a method I need to make accessable to C functions. It looks something like this:
    public class ExportName
       private SomeObj theObj;
       public ExportName(SomeObj theObj)
          this.theObj = theObj;
       } //end ExportName
       public String getName()
          return theObj.getName();
       public native String getNameJNI();
    }Using javah I have my ExportName.h, and I'm in the process of writing ExportName.c:
    #include <stdio.h>
    #include <jni.h>
    #include "ExportName.h"
    JNIEXPORT jstring JNICALL Java_ExportName_getNameJNI (JNIEnv *, jobject)
       jclass cls = (*env)->GetObjectClass(env, obj);
       jMethodID mid = (*env)->GetMethodID(env, cls, "getName", "()Ljava/lang/String");
       if (mid == 0)
          return;
       } /* end if */
    }I have 2 questions:
    (1)At some point, I need to actually call the java method using
    (*env)->Call<TYPE>Method(env, obj, mid);
    What type should I use here (CallWhatMethod)?
    (2)Also, I need to create genuine C wrappers for these methods. How do I hand off the jstring returned by this JNI C code to the ANSI C method that calls it? I know that there is a conversion along the lines of:
    const char str = (env)->GetStringUTFChars(env, <<JSTRING HERE>>, 0);
    Can I just put the call to the JNI method where the jstring variable name goes?
    Any help would be appreciated. I have already read the Java tutorial on JNI, so please don't respond just to tell me to go there.
    Thanks!

    If that is the case, then your starting point is not javah, but to investigate the invocation API, after which you will call java methods from C.
    Well, the Invocation API is mostly orthogonal to whether you are calling Java from C or vice versa. The Invocation API is mostly about creating/destroying VMs. You can call Java methods from a flat C application or you can call Java methods from C from within Java native methods.
    If you want to call Java from C, you need to use the methods you're using like GetMethodID, CallXXXMethod, etc...
    In your particular example, if you wanted to call ExportName.getName(), you would use CallObjectMethod. You would cast the result to a jstring, and then use GetStringUTFChars, ReleaseStringUTFChars, etc...
    God bless,
    -Toby Reyelts
    For a solution to all your JNI woes, check out Jace - http://jace.reyelts.com/jace

  • Java.lang.stackoverflowerror issue when calling another jframe

    i created a login screen with a username/password field that i call from my main applicaton. I call the jframe with the following code
      createDirectories();
            startNotes();
            login.start();
            getLists();once it gets to the login.start(); it give the following error
    Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
    at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
    at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:240)
    at java.awt.Window.init(Window.java:368)
    at java.awt.Window.<init>(Window.java:407)
    here is the full code for my login.java minus the swing component creation
    import javax.swing.JOptionPane;
    public class loginScreen extends javax.swing.JFrame {
        TESTapplication app = new TESTapplication();
            patientObject patient = new patientObject();
        public loginScreen() {       
            initComponents();        
       //initcomponents removed from here
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                        
            sendLogin();
        private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
            System.out.println("User exited application");
            System.exit(3);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {              
                 // start();
        // Variables declaration - do not modify                    
        private javax.swing.JButton btnCancel;
        private javax.swing.JButton btnLogin;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel lblLoginInfo;
        private javax.swing.JPasswordField pswrdFldPassword;
        private javax.swing.JTextField txtFldUsername;
        // End of variables declaration                  
        public void start(){
            new loginScreen().setVisible(true);
        public void sendLogin(){
            if (
                    txtFldUsername.getText().trim().equals("") ||  //trim removes whitespace
                    pswrdFldPassword.getText().trim().equals("") )
                JOptionPane.showMessageDialog(null,"Complete empty field(s)","Warning",JOptionPane.WARNING_MESSAGE);
            } else {
                patient.setUsername(txtFldUsername.getText().trim());
                patient.setPassword(pswrdFldPassword.getText().trim());
                patient.setAction("login");
                app.sendPatient();
    }thanks for all help given

    I only need to call 1 new login screen and no new application... how can i call a
    function from another java file?From a method of any class you can invoke (call) methods of other classes. I use "method" rather than "function" here to emphasise that they are much more than bits of code that do something: they have a context (the object of which they are a method).
    for instance i want to call the start function of the loginScreen.java from the
    testapplication.java. i don't need any new pieces, just want to be able to open the
    loginscreen jframe from the test application jframe.I wondered before why that start() method was creating a new loginScreen, but leaving that aside... One way might be for the TESTapplication class to have a member variable of type loginScreen. When some method of TESTapplication wants to invoke the start() method it just does so:loginScreen myLoginScreen = new loginScreen();
    // much later...
    myLoginScreen.start();There is no need for the loginScreen to have its own TESTapplication member variable since, as you say. "i don't need any new pieces".
    The start() method appears to next to nothing. It makes the loginScreen instance visible. But there's already a public method to do that. Perhaps loginScreen should be a modal JDialog: calling setVisible(true) will allow the login screen to do its thing and not return until it has finished (without blocking the event queue).
    It's all really a bit speculative and will remain so until you break down your application into small pieces: not functions (actions), but classes (types of obejcts including the things they can do.) Each class should have a clear and documented description of what it does.

  • Correct clipping when calling "paint()" from thread

    How do I achieve correct clipping around JMenus or JTooltips when calling paint() for a Component from a background thread?
    The whole story:
    Trying to implement some blinking GUI symbols (visualizing alerts), I implemented a subclass of JPanel which is linked to a Swing timer and thus receives periodic calls to its "actionPerformed()" methods.
    In the "actionPerformed()" method, the symbol's state is toggled and and repainting the object should be triggered.
    Unfortunately, "repaint()" has huge overhead (part of the background would need to be repainted, too) and I decided to call "paint( getGraphics() )" instead of it.
    This works fine as long as there is nothing (like a JMenu, a JComboBox or a JTooltip) hiding the symbol (partially or completely). In such case the call to paint() simply "overpaints" the object.
    I suppose setting a clipping region would help, but where from can I get it?
    Any help welcome! (I alread spent hours in search of a solution, but I still have no idea...)

    For all those interested in the topic:
    It seems as if there is no reliable way to do proper clipping when calling
    "paint()".
    The problem was that when my sub-component called "repaint()" for itself, the underlying component's "paintComponent()" method was called as well. Painting of that component was complex and avoiding complexity by restricting
    on the clipping region is not easily possible.
    I have several sub-components to be repainted regularly, resulting in lots of calls to my parent component's "paintComponent()" method. This makes the
    repainting of the sub-components awfully slow; the user can see each one begin painted!
    Finally I decided I had to speed up the update of the parent component. I found two possible solutions:
    a) Store the background of each of the sub-components in a BufferedImage:
    When "paintComponent()" is called: test, if the clipping rectangle solely
    contains the region of a sub-component. If this is true check if there
    is a "cached" BufferedImage for this region. If not, create one, filling
    it with the "real" "paintComponent()" method using the Graphic object of
    the BufferedImage. Once we have such a cached image, simply copy it the
    the screen (i.e. the Graphics object passed as method parameter).
    b) To avoid the handling of several of such "cached" image tiles, simply
    store the whole parent component's visible part ("computeVisibleRect()")
    in a BufferedImage. Take care to re-allocate/re-paint this image each
    time the visible part changes. (I need to restrict the image buffer to
    the visible part since I use a zooming feature: Storing the whole image
    would easily eat up all RAM!) In the "paintComponent()", simple check
    if the currently buffered image is still valid - repaint if not -
    and copy the requested part of it (clip rect) to the screen. That's it!
    The whole procedure works fine.
    Best regards,
    Armin

  • "ReferenceError: "myIpAddr"  is not defined, when call JavaScript from java

    Hi developers,
    My java application was trying to issue a http request via proxy auto-config. So, I did below jobs
    1. Read URL of *.pac from registry
    2. Call FindProxyForURL from java, the code is like below
                   ScriptEngineManager factory = new ScriptEngineManager();
                   ScriptEngine engine = factory.getEngineByName("JavaScript");
                   engine.eval(autoProxyScript);
                   Invocable inv = (Invocable) engine;
                   Object obj = inv.invokeFunction("FindProxyForURL",
                             "http://java.sun.com/",
                             "java.sun.com");
    However, I got "ReferenceError: "myIpAddress" is not defined
    I can not change the script on server to add a function like "myIpAddress", I am wordering why IE or mozilla can call it successfully and get proxy server, while Java failed to do that.
    I got a ugly solution by calling "pacparser" by jni. But I really hope I can get a better solution.

    A .pac file is a JavaScript, but it requires some functions to be defined in the executing context to work (i.e. you must define those).
    From the example on the Wikipedia page there's at least "shExpMatch" and "isInNet". "myIpAddress" seems to be another such candidate.

Maybe you are looking for