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?

Similar Messages

  • Calling c function from java!!

    hi all,
    I want to call c function from java . I have gone through the link http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/index.html for JNI.
    According to this link we need to write the native method implementation in such a way that the method signature should exactly match the method signature created in the header file.
    My problem is that i have a c application which i cannot modify in any ways i.e., i cannot change its code. But i want to call its function from my java code.
    Please suggest me appropriate solution for this. Please let me know whether it can be done using JNI or is there any other method for this.
    thanks

    This link is amazing since those sources were wrote in 1998 and I started to develop JNative in 2004. I did not found them when I started.
    Since JNative can deal with callbacks and probably COM in a near future, I expect to see it living to Dolphin at least.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Call DLL function from JAVA

    HI!
    What's the best way (and simple) to call DLL function from JAVA.
    DLL function (developed in C) has two input parameters (string) and return an integer.
    Could you help with an example?
    Thanks a lot.

    Do a google search for 'JNI tutorial' and it will turn up hundreds of examples.

  • Calling a function from another class - help!

    I realize that this is probably a basic thing for people who have been working with JavaFX for a while, but it is eluding me, and I have been working on it for over a week.
    I need to call a function that is in another class.  Here's the deal.  In EntryDisplayController.java, there are 2 possible passwords that can be accepted - one will give full access to the car, the second will limit functions on the car.  So when a password is entered and verified as to which one it is, I need to call a function in MainDisplayController.java to set a variable that will let the system know which password is being used - full or restricted.
    So in MainDisplayController.java I have this snippet to see
    public class MainDisplayController implements Initializable, ControlledScreen {
        ScreensController myController;
        public static char restrict;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            // TODO
        public void setRestriction(){
            restrict = 0;
            restrictLabel.setText("RESTRICTED");
        public void clearRestriction(){
            restrict = 1;
            restrictLabel.setText("");
    And in EntryScreenDisplay.java I have this snippet:
    public class EntryDisplayController implements Initializable, ControlledScreen {
         @FXML
        private Label passwordLabel ;
        static String password = new String();
        static String pwd = new String("");
         ScreensController myController;
         private MainDisplayController controller2;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            setPW(pwd);    // TODO
         @FXML
        private void goToMainDisplay(ActionEvent event){
            if(password.equals ("123456")){
              controller2.clearRestriction();
               myController.setScreen(ScreensFramework.MainDisplayID);
               pwd = "";
               password = "";
               setPW(pwd);
            else if(password.equals ("123457")){
               controller2.setRestriction();
                myController.setScreen(ScreensFramework.MainDisplayID);
               pwd = "";
               password = "";
               setPW(pwd);
            else{
                password = "";
                pwd = "";
                setPW(pwd);
    When I enter the restricted (or full) password, I get a long list of errors, ending with
    Caused by: java.lang.NullPointerException
      at velocesdisplay.EntryDisplayController.goToMainDisplay(EntryDisplayController.java:60)
    Line 60 is where "controller2.setRestriction(); is.
    As always, thanks for any help.
    Kind regards,
    David

    You never set the controller2 variable to anything, which is why you get a null pointer exception when you try to reference it.
    public static variables (and even singletons) are rarely a good idea as they introduce global state (sometimes they can be, but usually not).
    If a static recorder like this can only have a binary value, use a boolean, if it can have multiple values, use an enum.
    Some of the data sharing solutions in dependency injection - Passing Parameters JavaFX FXML - Stack Overflow might be more appropriate.
    I also created a small framework for roll based solutions in JavaFX which perhaps might be useful:
    http://stackoverflow.com/questions/19666982/is-there-a-way-to-implement-a-property-like-rendered-on-javafx
    https://gist.github.com/jewelsea/7229260
    It was just something I hacked together, so it's not a fully polished solution and you probably don't need something quite so complex.
    What you need is a model class shared between the components of your application.  Dependency injection frameworks such as afterburner.fx can help achieve this in a fairly simple to use way.
    If you don't want to go with a dependency injection framework, then you could use either a static singleton model class for your settings or pass the model class using the mechanism in defined in the passing parameters link I provided.  For a model class example, see the ClickCounter class from this example.   That example doesn't use FXML, but to put it together with the passing parameters solution, for your restriction model, you would have something like the following:
       private class Restricted {
         private final ReadOnlyBooleanWrapper restricted;
         public Restricted(boolen isRestricted) {
           restricted = new ReadOnlyBooleanWrapper(isRestricted);  
         public boolean isRestricted() {
           return restricted.get();
         public ReadOnlyBooleanProperty restrictedProperty() {
           return restricted.getReadOnlyProperty();
    Then in your EntryDisplayController you have:
    @FXML
    public void goToMainDisplay(ActionEvent event) {
         // determine the restriction model as per your original code...
         RestictionModel restrictionModel = new RestrictionModel(<appropriate value>);
      FXMLLoader loader = new FXMLLoader(
      getClass().getResource(
       "mainDisplay.fxml"
      Stage stage = new Stage(StageStyle.DECORATED);
      stage.setScene(
       new Scene(
         (Pane) loader.load()
      MainDisplayController controller =
        loader.<MainDisplayController>getController();
      controller.initRestrictionModel(restrictionModel);
      stage.show();
    class MainDisplayController() {
      @FXML private RestrictionModel restrictionModel;
      @FXML private RestrictLabel restrictLabel;
      public void initialize() {}
      // naming convention (if the restriction model should only be set once per controller, call the method init, otherwise call it set).
      public void initRestrictionModel(RestrictionModel restrictionModel) {
        this.restrictionModel = restrictionModel;
         // take some action based on the new restriction model, for example
        restrictLabel.textProperty.bind(
          restrictionModel.restrictedProperty().asString()
    If you have a centralized controller for your navigation and instantiation of your FXML (like in this small FXML navigation framework), then you can handle the setting of restrictions on new screens centrally within the framework at the point where it loads up FXML or navigates to a screen (it seems like you might already have something like this with your ScreensController class).
    If you do this kind of stuff a lot, then you would probably benefit from a move to a framework like afterburner.  If it is just a few times within your application, then perhaps something like the above outline will give you enough guidance to implement a custom solution.

  • Call C function from Java

    Hi
    How do I call a C function from a java applet. Any ideas.
    Thanks
    Jay

    How do I call a C function from a java applet.
    You're going to run into problems here even after you figure out all the JNI details. Loading a shared object from an applet violates the security model - you will have to sign the applet. In addition, to be cross-platform (I'm using linux now), you will have to provide multiple dll/so - one for each architecture...

  • Call peoplesoft function from java code

    Can we call the peoplesoft decrypt function from within java code ?

    Hi Sumit,
    For getting the connection, I would use something like:
    import com.sap.mw.jco.JCO;
    public class R3Connector {
         private JCO.Client jcoclient = null;
         public  R3Connector () {
                   super();
         public JCO.Client getClient() {
              if (jcoclient == null) {
                   /* get connection from Pool */
                   jcoclient = JCO.getClient (POOL_NAME);
              return jcoclient;
         public void releaseClient() {
              if (jcoclient != null) {
                   JCO.releaseClient(jcoclient);     
    and of course you will have to define your POOL property somewhere (portalapp.xml presumably)
    Hope this helps!

  • Calling PL/SQL function from external Java class

    I was wondering if I was able to call a pl/sql function from an external java class? If so, would you be able to tell me briefly on how to go about it. I know I can call java methods that are internally stored in the db from pl/sql, but I was hoping I could call pl/sql from external java. Thanks,
    Kelly

    Ok, I made the changes, but I'm now getting the following error:
    Error code = 1403
    Error message = ORA-01403: no data found
    ORA-06512: at "IOBOARD.GETSTATUS", line 6
    ORA-06512: at line 1
    The ora-01403 I don't understand because there is data for the name Kelly.Brace.
    ora-06512 error: at string line string.
    Here's what the code looks like after I made the changes:
    String sql = "{?=call ioboard.GetStatus(?)}";
          // create a Statement object
          myStatement = myConnection.prepareCall( sql );
          myStatement.setString( 1, "Kelly.Brace" );
          myStatement.registerOutParameter(2, java.sql.Types.LONGVARCHAR );
          // create a ResultSet object, and populate it with the
          // result of a SELECT statement
          ResultSet myResultSet = myStatement.executeQuery();
          // retrieve the row from the ResultSet using the
          // next() method
          myResultSet.next();
          // retrieve the user from the row in the ResultSet using the
          // getString() method
          String status = myResultSet.getString(1);
          System.out.println("Hello Kelly, your status is: " + status);
          // close this ResultSet object using the close() method
          myResultSet.close();Here's what the function looks like:
    CREATE OR REPLACE FUNCTION GetStatus( user_name in varchar2)
    RETURN VARCHAR2
    is
    v_status varchar2(10);
    BEGIN
    select iob_location into v_status
    from ioboard.iob_user
    where iob_username = user_name;
      RETURN( v_status);
    END;This works perfectly in the SQL Window:
    select iob_location
    from ioboard.iob_user
    where iob_username = 'Kelly.Brace';

  • I get EXCEPTION_ACCESS_VIOLATION by calling JNI function.

    Hello Everyone.
    I need someone's help that I have a problem with JNI.
    I got an error as below when a Java program calls JNI function that I created with VC++.
    JNI functions are called not once and got an error not first call.
    First of all, The JNI function is called at Main function.
    then, Main function create another thread.
    and next JNI function is called in another thread.
    when the JNI function is called first time is suceeded.
    but, second time is always failed.
    I wrote down some of detail in source code's comment.
    // ErrorLog is from here ------------------------------------------------------
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d7c7c5f, pid=2460, tid=3144
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_14-b03 mixed mode)
    # Problematic frame:
    # V [jvm.dll+0x87c5f]
    --------------- T H R E A D ---------------
    Current thread (0x00843650): JavaThread "Thread-0" [_thread_in_vm, id=3144]
    siginfo: ExceptionCode=0xc0000005, reading address 0x00000009
    Registers:
    EAX=0x00000001, EBX=0x06d77d40, ECX=0x00000008, EDX=0x00843710
    ESP=0x0afaf4a8, EBP=0x0afaf4d8, ESI=0x0afaf4ec, EDI=0x0afaf53c
    EIP=0x6d7c7c5f, EFLAGS=0x00010246
    Top of Stack: (sp=0x0afaf4a8)
    0x0afaf4a8: 0afaf4ec 06d77d40 6d7cfa7e 00000001
    0x0afaf4b8: 0afaf53c 0afaf4ec 06d77d40 00843070
    0x0afaf4c8: 00841a10 00841a18 00841e04 00843650
    0x0afaf4d8: 0afaf53c 100020a6 00843710 0082f3d0
    0x0afaf4e8: 0afaf5a0 0afaf5a4 06d77d40 06d77d40
    0x0afaf4f8: cccccccc cccccccc cccccccc cccccccc
    0x0afaf508: cccccccc cccccccc cccccccc cccccccc
    0x0afaf518: cccccccc cccccccc cccccccc cccccccc
    Instructions: (pc=0x6d7c7c5f)
    0x6d7c7c4f: 5f 5e 5b c3 8b 44 24 04 8b 0d 14 e2 8b 6d 53 56
    0x6d7c7c5f: 8b 34 01 8b 0d 10 e2 8b 6d 57 8b 3c 01 8b 0d 0c
    Stack: [0x0af70000,0x0afb0000), sp=0x0afaf4a8, free space=253k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    V [jvm.dll+0x87c5f]
    C [FilterDriver.dll+0x20a6]
    C [FilterDriver.dll+0x16c7]
    C [FilterDriver.dll+0x1c59]
    C [FilterDriver.dll+0x22b3]
    j xx.xx.xx.xx.xx.TestClass.get(Ljava/lang/String;)Z+0
    j xx.xx.xx.xx.xx.ClassExtendedThread.run()V+24
    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+0x2a3b0]
    C [kernel32.dll+0xb683]
    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j xx.xx.xx.xx.xx.TestClass.get(Ljava/lang/String;)Z+0
    j xx.xx.xx.xx.xx.ClassExtendedThread.run()V+24
    v ~StubRoutines::call_stub
    --------------- P R O C E S S ---------------
    Java Threads: ( => current thread )
    0x008433b0 JavaThread "DestroyJavaVM" [_thread_blocked, id=2676]
    =>0x00843650 JavaThread "Thread-0" [_thread_in_vm, id=3144]
    0x0083d5f0 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=2024]
    0x0083c730 JavaThread "CompilerThread0" daemon [_thread_blocked, id=3444]
    0x0083b560 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=2784]
    0x00839970 JavaThread "JDWP Command Reader" daemon [_thread_in_native, id=2876]
    0x00838c60 JavaThread "JDWP Event Helper Thread" daemon [_thread_blocked, id=2980]
    0x00836250 JavaThread "JDWP Transport Listener: dt_socket" daemon [_thread_blocked, id=536]
    0x0082e410 JavaThread "Finalizer" daemon [_thread_blocked, id=2100]
    0x0082d190 JavaThread "Reference Handler" daemon [_thread_blocked, id=1968]
    Other Threads:
    0x0082c470 VMThread [id=296]
    0x0083fd50 WatcherThread [id=464]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 576K, used 300K [0x02bd0000, 0x02c70000, 0x030b0000)
    eden space 512K, 58% used [0x02bd0000, 0x02c1b200, 0x02c50000)
    from space 64K, 0% used [0x02c50000, 0x02c50000, 0x02c60000)
    to space 64K, 0% used [0x02c60000, 0x02c60000, 0x02c70000)
    tenured generation total 1408K, used 0K [0x030b0000, 0x03210000, 0x06bd0000)
    the space 1408K, 0% used [0x030b0000, 0x030b0000, 0x030b0200, 0x03210000)
    compacting perm gen total 8192K, used 1711K [0x06bd0000, 0x073d0000, 0x0abd0000)
    the space 8192K, 20% used [0x06bd0000, 0x06d7bf00, 0x06d7c000, 0x073d0000)
    No shared spaces configured.
    Dynamic libraries:
    0x00400000 - 0x0040d000      C:\Program Files\Java\jdk1.5.0_14\bin\javaw.exe
    0x7c940000 - 0x7c9dd000      C:\WINDOWS\system32\ntdll.dll
    0x7c800000 - 0x7c932000      C:\WINDOWS\system32\kernel32.dll
    0x77d80000 - 0x77e29000      C:\WINDOWS\system32\ADVAPI32.dll
    0x77e30000 - 0x77ec1000      C:\WINDOWS\system32\RPCRT4.dll
    0x77cf0000 - 0x77d7f000      C:\WINDOWS\system32\USER32.dll
    0x77ed0000 - 0x77f17000      C:\WINDOWS\system32\GDI32.dll
    0x77bc0000 - 0x77c18000      C:\WINDOWS\system32\MSVCRT.dll
    0x762e0000 - 0x762fd000      C:\WINDOWS\system32\IMM32.DLL
    0x60740000 - 0x60749000      C:\WINDOWS\system32\LPK.DLL
    0x73f80000 - 0x73feb000      C:\WINDOWS\system32\USP10.dll
    0x6d740000 - 0x6d8de000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\client\jvm.dll
    0x76af0000 - 0x76b1b000      C:\WINDOWS\system32\WINMM.dll
    0x6d300000 - 0x6d308000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\hpi.dll
    0x76ba0000 - 0x76bab000      C:\WINDOWS\system32\PSAPI.DLL
    0x6d400000 - 0x6d435000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\jdwp.dll
    0x6d710000 - 0x6d71c000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\verify.dll
    0x6d380000 - 0x6d39d000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\java.dll
    0x6d730000 - 0x6d73f000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\zip.dll
    0x6d290000 - 0x6d297000      C:\Program Files\Java\jdk1.5.0_14\jre\bin\dt_socket.dll
    0x719e0000 - 0x719f7000      C:\WINDOWS\system32\WS2_32.dll
    0x719d0000 - 0x719d8000      C:\WINDOWS\system32\WS2HELP.dll
    0x71980000 - 0x719bf000      C:\WINDOWS\System32\mswsock.dll
    0x76ed0000 - 0x76ef7000      C:\WINDOWS\system32\DNSAPI.dll
    0x76f60000 - 0x76f68000      C:\WINDOWS\System32\winrnr.dll
    0x76f10000 - 0x76f3c000      C:\WINDOWS\system32\WLDAP32.dll
    0x76f70000 - 0x76f76000      C:\WINDOWS\system32\rasadhlp.dll
    0x607c0000 - 0x60816000      C:\WINDOWS\system32\hnetcfg.dll
    0x719c0000 - 0x719c8000      C:\WINDOWS\System32\wshtcpip.dll
    0x10000000 - 0x10076000      C:\xx\whaticreated.dll
    0x71a50000 - 0x71a62000      C:\WINDOWS\system32\MPR.dll
    VM Arguments:
    jvm_args: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:1759
    java_command: xx.xx.xx.xx.xx.Sample start
    Launcher Type: SUN_STANDARD
    Environment Variables:
    JAVA_HOME=C:\Program Files\Java\jdk1.5.0_14
    PATH=C:\WINDOWS\system32;C:\WINDOWS;D:\tools\apache-ant-1.7.0\bin;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;D:\PROGRA~1\ATT\Graphviz\bin;D:\Program Files\doxygen\bin;D:\Program Files\Microsoft SDK\Bin\.;D:\Program Files\Microsoft SDK\Bin\WinNT\.;C:\Program Files\Java\jdk1.5.0_14\bin;C:\Program Files\Microsoft Visual Studio\Common\Tools\WinNT;C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin;C:\Program Files\Microsoft Visual Studio\Common\Tools;C:\Program Files\Microsoft Visual Studio\VC98\bin;D:\Program Files\Microsoft SDK\Bin\.;D:\Program Files\Microsoft SDK\Bin\WinNT\.
    USERNAME=xxx
    OS=Windows_NT
    PROCESSOR_IDENTIFIER=x86 Family 6 Model 15 Stepping 2, GenuineIntel
    --------------- S Y S T E M ---------------
    OS: Windows XP Build 2600 Service Pack 2
    CPU:total 2 (cores per cpu 2, threads per core 1) family 6 model 15 stepping 2, cmov, cx8, fxsr, mmx, sse, sse2
    Memory: 4k page, physical 1038124k(270512k free), swap 1711740k(953716k 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
    // The end of ErrorLog --------------------------------------------------------
    and the codes are below.
    // TestClass.java
    public class TestClass {
         // Load native library
         static{
              System.loadLibrary("DLLName");
         public native int start(String str, int count);
         public native int end();
         public native boolean get(String str);
    // ClassExtendedThread.java
    public class ClassExtendedThread extends Thread {
         private TestClass tc;
         // Constructor
         public ClassExtendedThread(TestClass in_tc)
              ts = in_tc;
         // This will be executing in another thread
         public void run()
              while( true )
                   if( !false )
                        String str = new String();
                        // get function returns false means nothing to catch event.
                        if( false == ts.get( str ) ) // calling first time is suceed. but, I got an error second time.
                          // Set Interval for loop.
    // Sample.java
    public class Sample {
         public static void main(String[] args) {
              TestClass tc = null;
              ClassExtendedThread cet = null;
              tc = new TestClass();
              // Init something
              if(0 != TestClass.start(xxx, xxx)) // First JNI function suceeds.
                   System.out.println("start error.");
                   return;
              // Starting Thread
              cet = new ClassExtendedThread(tc);
              cet.start();
    }Have anyone got any idea to resolve this problem?
    Edited by: fc3srx7m on Apr 25, 2008 3:56 AM

    Hi Martin.
    Thank you for your advice.
    I thought the problem is in the FilterDriver.dll as well.
    I tried DebugBreak() into native code.
    but, I still can't find where the problem is.
    I'm trying to convert C structure to Java class like using structConverter which is tool of book for JNI.
    Here's some code including native code.
    // Java source codes //////////////////////////////////////////////////////////////////////////////////
    // Event.java ----------------------------------------------------------------------------------------------
    // This class for C structure Convert
    public class Event {
         private int     aaa;
         private long     bbb;
         private String     ccc;
            // Getter/Setter
         public int getAaa() {
              return aaa;
         public void setAaa(int aa) {
              aaa = aa;
         public long getBbb() {
              return bbb;
         public void setBbb(long cc) {
              bbb = bb;
         public String getCcc() {
              return ccc;
         public void setCcc(String cc) {
              ccc = cc;
            // Field Initialize
         private native static void initFIDs();
         static {
              initFIDs();
    // EventStruct,java --------------------------------------------------------------------------------------
    public class EventStruct extends Event {
         private void _init()
              setAaa(0);
              setBbb(0);
              setCcc(new String());
         // Constructor
         public LogEventStruct()
              _init();
              System.loadLibrary("FilterDriver");
    // EndOfJavaSource ////////////////////////////////////////////////////////////////////////////////////
    // Native source code /////////////////////////////////////////////////////////////////////////////////
    // Event.cpp ----------------------------------------------------------------------------------------------
    // FieldIDs
    static jfieldID Event_Aaa_FID;
    static jfieldID     Event_Bbb_FID;
    static jfieldID     Event_Ccc_FID;
    // Initialize Adapter
    static void initEventFieldIDs(JNIEnv* env, jclass clazz)
              Event_Aaa_FID     = env->GetFieldID(clazz, "aaa",     "I");
              Event_Bbb_FID     = env->GetFieldID(clazz, "bbb",      "J");
              Event_SFlNm_FID = env->GetFieldID(clazz, "ccc",      "Ljava/lang/String;");
    // Call from Java
    JNIEXPORT void JNICALL Java_Event_initFIDs(JNIEnv *env, jclass clazz)
              initEventFieldIDs(env, clazz);
    // Setter
    void jni_SetAaa_in_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisaaa)
              env->SetIntField(thisaaa, Event_Aaa_FID, (jint)__EVENT_->aaa);
    // Getter
    void jni_GetAaa_from_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisaaa)
              __EVENT_->aaa = (int)env->GetIntField(thisaaa, Event_Aaa_FID);
    // Setter
    void jni_SetBbb_in_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisbbb)
              env->SetLongField(thisbbb, Event_Bbb_FID, __EVENT_->bbb);
    // Getter
    void jni_GetBbb_from_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisbbb)
              __EVENT_->bbb = (unsigned int)env->GetLongField(thisbbb, Event_Bbb_FID);
    // Setter
    void jni_SetCcc_in_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisccc)
              env->SetObjectField(thisccc, Event_Ccc_FID, env->NewStringUTF(__EVENT_->ccc));
    // Getter
    void jni_GetCcc_from_Event(EVENT* __EVENT_, JNIEnv *env, jobject thisccc)
              jboolean isCopy;
              const char *str = __EVENT_->ccc;
              jstring jstr = (jstring)env->GetObjectField(thisccc, Event_Ccc_FID);
              str = env->GetStringUTFChars(jstr, &isCopy);
              if(JNI_TRUE == isCopy)
                        env->ReleaseStringUTFChars(jstr, str);
    // Getting (Java Object to C Structure)
    void jni_SetAll_in_Event(EVENT *__EVENT_, JNIEnv *env, jobject thisEvent)
              jni_SetAaa_in_Event(__EVENT_, env, thisEvent);
              jni_SetBbb_in_Event(__EVENT_, env, thisEvent);
              jni_SetCcc_in_Event(__EVENT_, env, thisEvent);
    // Setting (C structure to Java Object)
    void jni_GetAll_in_Event(EVENT *__EVENT_, JNIEnv *env, jobject thisEvent)
              jni_GetAaa_from_Event(__EVENT_, env, thisEvent);
              jni_GetBbb_from_Event(__EVENT_, env, thisEvent);
              jni_GetCcc_from_Event(__EVENT_, env, thisEvent);
    // AnotherLib.h ------------------------------------------------------------------------------------
    // C Structure which I want to convert.
    typedef struct EVT {
         int                  aaa;
         unsigned int    bbb;
         char               ccc[256];
    } EVENT;
    // prototype
    BOOL GetEvent( EVENT* buf, char *name );
    // test.h -----------------------------------------------------------------------------------------------------
    #if !defined(AFX_TEST_H__F9A4A432_24D3_4DE4_89D7_A2009B8EC2AA__INCLUDED_)
    #define AFX_TEST_H__F9A4A432_24D3_4DE4_89D7_A2009B8EC2AA__INCLUDED_
    #if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000
    #include <windows.h>
    #include "AnotherLib.h"
    #include "Event.h" // output by javah command
    extern void jni_GetAll_in_Event(EVENT *__EVENT_, JNIEnv *env, jobject thisEvent);
    extern void jni_SetAll_in_Event(EVENT *__EVENT_, JNIEnv *env, jobject thisEvent);
    #endif // !defined(AFX_TEST_H__F9A4A432_24D3_4DE4_89D7_A2009B8EC2AA__INCLUDED_)
    // test.cpp --------------------------------------------------------------------------------------------------
    JNIEXPORT jboolean JNICALL Java_get(JNIEnv *env, jobject obj, jstring name)
              EVENT s_Event;
              char strName[_MAX_PATH];
    //DebugBreak();
              memset(&s_Event, 0x00, sizeof(EVENT));
              memset(strName, 0x00, _MAX_PATH);
              jni_SetAll_in_Event(&s_Event, env, obj);
              BOOL ret = GetEvent(&s_Event, strName);
              if(TRUE == ret)
                        jni_GetAll_in_Event(&s_Event, env, obj);
                        // convert char array to jstring
                        name = env->NewStringUTF(strName);
              return ret;
    // EndOfNativeSource ////////////////////////////////////////////////////////////////////////////////Edited by: fc3srx7m on Apr 27, 2008 10:05 PM

  • How to call oracle function from ejb3

    i'm trying to call an oracle query-function from ejb3.
    The oracle function:
    create or replace FUNCTION getSecThreadCount(secId in NUMBER,avai in NUMBER)
    RETURN SYS_REFCURSOR is cur SYS_REFCURSOR;
    m_sql VARCHAR2(250);
    BEGIN
    m_sql:='select count(thrId) from thread where secId='|| secid||'
    and thrAvai='|| avai;
    open cur for m_sql;
    return cur;
    END;
    I'v tried several ways to call it,but all failed:
    1. the calling code:
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNativeQuery("{call getSecThreadCount(?,?) }");     
              query.setParameter(1, secId);
              query.setParameter(2, avai);
              return query.getSingleResult();
    but i got the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: ORA-06550: row 1, col 7:
    PLS-00221: 'GETSECTHREADCOUNT' not procedure or not defined
    ORA-06550: row 1, col 7:
    PL/SQL: Statement ignored
    2. the calling code:
    @SqlResultSetMapping(name = "getSecThreadCount_Mapping")
    @NamedNativeQuery(name = "getSecThreadCount",
    query = "{?=call getSecThreadCount(:secId,:avai)}",
    resultSetMapping = "getSecThreadCount_Mapping",
    hints = {@QueryHint(name = "org.hibernate.callable", value = "true"),
              @QueryHint(name = "org.hibernate.readOnly", value = "true")})
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNamedQuery("getSecThreadCount");     
              query.setParameter("secId", secId);
              query.setParameter("avai", avai);
              return query.getSingleResult();
    but i run into the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: lost in index IN or OUT parameter:: 3
    By the way, i have successfully called the function from hibernate. And i use oracle 11g, JBoss5 RC1.
    Could anyone tell me how to call the function from EJB3?
    Thanks.

    Here's a working model:
    package.procedure: (created in example schema scott)
    CREATE OR REPLACE package  body data_pkg as
      type c_refcursor is ref cursor;
      -- function that return all emps of a certain dept
      function getEmployees ( p_deptId in number
      return c_refcursor
      is
        l_refcursor c_refcursor;
      begin
         open l_refcursor
        for
              select e.empno as emp_id
              ,        e.ename as emp_name
              ,        e.job   as emp_job
              ,        e.hiredate as emp_hiredate
              from   emp e
              where  e.DEPTNO = p_deptId;
        return l_refcursor;
      end getEmployees;
    end data_pkg;
    /entity class:
    package net.app.entity;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.QueryHint;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @SuppressWarnings("serial")
    @Entity
    @Table (name="emp")
    @SequenceGenerator(name = "EmployeeSequence", sequenceName = "emp_seq")
    @NamedNativeQuery( name = "getEmpsByDeptId"
                   , query = "{ ? = call data_pkg.getEmployees(?)}"
                   , resultClass = Employee.class
                   , hints = { @QueryHint(name = "org.hibernate.callable", value = "true")
                          , @QueryHint(name = "org.hibernate.readOnly", value = "true")
    public class Employee implements Serializable
        @Id
        @Column(name="emp_id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EmployeeSequence")
        private int id;
        @Column(name="emp_name")
        private String name;
        @Column(name="emp_job")
        private String job;
        @Column(name="emp_hiredate")
        private Date hiredate;
        // constructor
        public Employee (){}
        // getters and setters
        public int getId()
         return id;
    etc...session bean:
    package net.app.entity;
    import java.util.ArrayList;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    @Stateless
    public class ScottAdminImpl implements ScottAdmin
        @PersistenceContext
        private EntityManager entityManager;
        @SuppressWarnings("unchecked")
        public List<Employee> getEmployeesByDeptId(int deptId)
         ArrayList<Employee> empList;
         try
             Query query = entityManager.createNamedQuery("getEmpsByDeptId");
             query.setParameter(1, deptId);
             empList = (ArrayList<Employee>) query.getResultList();
             return empList;
         catch (Exception e)
             e.printStackTrace(System.out);
             return null;
    }client:
    package net.app.client;
    import java.util.List;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    public class ScottClient
        public static void main(String[] args)
         try
             // create local interface
             InitialContext ctx = new InitialContext();
             ScottAdmin adminInterface = (ScottAdmin) ctx.lookup("ScottAdminImpl/remote");
             // select employees by deptno
             int deptno = 20;
             List<Employee> empList = adminInterface.getEmployeesByDeptId(deptno);
             // output
             System.out.println("Listing employees:");
             for (Employee emp : empList)
              System.out.println(emp.getId() + ": " + emp.getName() + ", " + emp.getJob() + ", " + emp.getHiredate());
         catch (NamingException e)
             e.printStackTrace(System.out);
    }Basically you just ignore the refcursor outbound parameter.
    This is a stored function, have yet to try outbound refcursor parameters in stored procedures...
    Edited by: _Locutus on Apr 2, 2009 2:37 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Calling a Function from another Function within CFC

    Hi all,
    I have many functions in my CFC that do various things, but
    one query is a query that selects absolutely every record from a
    table.
    The thing is, I need to do a query like this in another
    function to obtain only a recordcount of the same table used in
    both separate functions. Instead of writing the query out again,
    how can I utilise the function already written?
    My question is, how can I invoke and use the results of a
    query in one cffunction for another cffunction in the same CFC
    component?
    An example may look like the code attached...
    Many thanks for your patience and help!
    Mikey.

    quote:
    Originally posted by:
    Dan Bracuk
    Generally, to call a function from within a cfc, you do
    exactly what you do outside a cfc.
    For your specific case, if your requirements permit it, you
    might consider caching the big query for a couple of seconds. Then
    you can continously call the function and not have to wait for it
    to run and bring back the data each time.
    Do you mean to say that within a CFC function I can execute
    the same cfinvoke tags I use in normal CFM pages?
    Mikey.

  • Calling JavaScript function from Servlet ?

    I have a Servlet that needs to call a general purpose JavaScript function to retrieve some data. The JavaScript function sits in a file on the web server called general.js.
    How can I call this function from my servlet to retrieve an integer result ?
    Sarah.

    http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm
    Look for Java to JavaScript communication.

  • Calling a servlet from a Java Stored Procedure

    Hey,
    I'm trying to call a servlet from a Java Stored Procedure and I get an error.
    When I try to call the JSP-class from a main-method, everything works perfectly.
    Java Stored Procedure:
    public static void callServlet() {
    try {
    String servletURL = "http://127.0.0.1:7001/servletname";
    URL url = new URL(servletURL);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Pragma", "no-cache");
    conn.connect();
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    Integer client = (Integer)ois.readObject();
    ois.close();
    System.out.println(client);
    conn.disconnect();
    } catch (Exception e) {
    e.printStackTrace();
    Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    Integer id = new Integer(10);
    OutputStream os = response.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(id);
    oos.flush();
    oos.close();
    response.setStatus(0);
    Grant:
    call dbms_java.grant_permission( 'JAVA_USER', 'SYS:java.net.SocketPermission','localhost', 'resolve');
    call dbms_java.grant_permission( 'JAVA_USER','SYS:java.net.SocketPermission', '127.0.0.1:7001', 'connect,resolve');
    Package:
    CREATE OR REPLACE PACKAGE pck_jsp AS
    PROCEDURE callServlet();
    END pck_jsp;
    CREATE OR REPLACE PACKAGE BODY pck_jsp AS
    PROCEDURE callServlet()
    AS LANGUAGE JAVA
    NAME 'JSP.callServlet()';
    END pck_jsp;
    Architecture:
    AS: BEA WebLogic 8.1.2
    DB: Oracle 9i DB 2.0.4
    Exception:
    java.io.StreamCorruptedException: InputStream does not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java)
    The Servlet and the class work together perfectly, only when I make the call from
    within the database things go wrong.
    Can anybody help me.
    Thank in advance,
    Bart Laeremans
    ... Desperately seeking knowledge ...

    Look at HttpCallout.java in the following code sample
    http://www.oracle.com/technology/sample_code/tech/java/jsp/samples/jwcache/Readme.html
    Kuassi

  • How to call IAC Iview from WebDynpro java code

    Hi Team,
    I am tring to call IAC Iview from WebDynpro Java code. we are passing value but blank page  displayed and there is no error show on error log.
    Below is Java Code which i am calling.
      public void wdDoInit()
          try {
                String strURL = "portal_content/TestSRM/iView/TestSRM";                           //WDProtocolAdapter.getProtocolAdapter().getRequestParameter("application");
                 String random = WDProtocolAdapter.getProtocolAdapter().getRequestObject().getParameter("random_code");     
                 //wdContext.currentContextElement().setRandomNumber(random);
    //below we are call URL           
    WDPortalNavigation.navigateAbsolute("ROLES://portal_content/TestSRM/iView/TestSRM?VAL="+random,WDPortalNavigationMode.SHOW_INPLACE,(String)null, (String)null,
                       WDPortalNavigationHistoryMode.NO_DUPLICATIONS,(String)null,(String)null, " ");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    I am passing value from URL.
    http://<host Name>:<port>/webdynpro/resources/local/staruser/StarUser?random_code=111111111
    when we call above URL we getting blank screen.
    Regards
    Pankaj Kamble

    Hi Vinod,
    read this document (from pages 7 ).
    <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b5380089-0c01-0010-22ae-bd9fa40ddc62">https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b5380089-0c01-0010-22ae-bd9fa40ddc62</a>
    In addition lok at these links: (Navigation Between Web Dynpro Applications in the Portal)
    <a href="http://help.sap.com/saphelp_erp2005/helpdata/en/ae/36d93f130f9115e10000000a155106/frameset.htm">http://help.sap.com/saphelp_erp2005/helpdata/en/ae/36d93f130f9115e10000000a155106/frameset.htm</a>
    <a href="http://help.sap.com/saphelp_erp2004/helpdata/en/b5/424f9c88970f48ba918ad68af9a656/frameset.htm">http://help.sap.com/saphelp_erp2004/helpdata/en/b5/424f9c88970f48ba918ad68af9a656/frameset.htm</a>
    It may be helpful for you.
    Best regards,
    Gianluca Barile

  • Can Any one tell me what is the step in calling a function from a *.lib file in Labview application

    Hi, I am working on Labview 8.0.
    I am trying to  communicate to a thrid party HW using the driver file he has provided to me.
    The drive file is a *.lib file.
    I am unable to call the function from the lib file.
    I could get only from a DLL.
    Pls help .
    Regards
    -Patil

    patil wrote:
    When it is possible in Lab Windows, why calling a function from a static library is prohibited?
    I was trying to use Function node, but found that it is only for functions from a DLL file.
    Will CIN be useful.? 
    LabWindows is not the same as LabVIEW. LabVIEW cannot call .lib files. LIB files are intermediary products and you need to use a wrapper DLL that's compatible with the object format of the .lib file. It's as simple as that. LabWindows creates C application and from that perspective is no different than a regular C
    compiler. That's why you can call .lib files because that's how .lib
    files are used.
    A CIN, as pointed out, is something completely different and will not help you.  

  • SQL Exception: Invalid column index while calling stored proc from CO.java

    Hello all,
    I am getting a "SQL Exception: Invalid column index" error while calling stored proc from CO.java
    # I am trying to call this proc from controller instead of AM
    # PL/SQL Proc has 4 IN params and 1 Out param.
    Code I am using is pasted below
    ==============================================
              OAApplicationModule am = (OAApplicationModule)oapagecontext.getApplicationModule(oawebbean);
    OADBTransaction txn = (OADBTransaction)am.getOADBTransaction();
    OracleCallableStatement cs = null;
    cs = (OracleCallableStatement)txn.createCallableStatement("begin MY_PACKAGE.SEND_EMAIL_ON_PASSWORD_CHANGE(:1, :2, :3, :4, :5); end;", 1);
         try
    cs.registerOutParameter(5, Types.VARCHAR, 0, 2000);
                        cs.setString(1, "[email protected]");
                             cs.setString(2, s10);
    //Debug
    System.out.println(s10);
                             cs.setString (3, "p_subject " );
                             cs.setString (4, "clob_html_message - WPTEST" );
                   outParamValue = cs.getString(1);
    cs.executeQuery();
    txn.commit();
    catch(SQLException ex)
    throw new OAException("SQL Exception: "+ex.getMessage());
    =========================================
    Can you help please.
    Thanks,
    Vinod

    You may refer below URL
    http://oracleanil.blogspot.com/2009/04/itemqueryvoxml.html
    Thanks
    AJ

Maybe you are looking for