Accessing a native method from within a packaged class

I have seen some very useful information from RPaul. However, I can not quite get it to work.
I have a class "JNIGetUserId" that is in a package "com.services.localoptions". I am trying to call a native method from a dll. it works fine at the default package level. But not in the package. I have tried adding the "_" between each level of the directory in the h and c++ files. I also found that doing a javah at the top of the package structure it includes some information in the h file. A "_0005" shows up between each level.
This is on Windows XP. I am also using VisualAge for Java. I also am using JDK 1.3.1.
The source files:
package com.services.localoptions;
* This class provides the JNI Interface to call the
* AD User Maintainence routines.
* These routines are stored in the JNIGetUserIdLibrary.dll.
* The routines are:
* <ul>
* <li>getUser - returns a string containing the User Id
* <eul>
* @author: Ray Rowehl
* @date (10/15/2003 10:30:59 AM)
public class JNIGetUserId
     // Load the library
     static
     try
          System.out.println("loading dll");
     System.loadLibrary("JNIGetUserIdLibrary");
     System.out.println("loaded dll");
     catch (UnsatisfiedLinkError ue)
          System.out.println("Link Error");
* native C++ method to call getUserId routine
public native String getUser() throws Exception;
* This method allows us to test standalone..
* Creation date: (10/16/2003 2:08:58 PM)
* @param args java.lang.String[]
public static void main(String[] args)
     try
          System.out.println("Trying method 3");
          JNIGetUserId lGUD = new JNIGetUserId();
          System.out.println(lGUD.getUser());
     catch (Exception e)
          System.out.println("Got an exception " + e);
          e.printStackTrace();
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNIGetUserId */
#ifndef IncludedJNIGetUserId
#define IncludedJNIGetUserId
#ifdef __cplusplus
extern "C" {
#endif
* Class: JNIGetUserId
* Method: getUser
* Signature: ()Ljava/lang/String;
JNIEXPORT jstring JNICALL Java_com_localoptions_JNIGetUserId_getUser
(JNIEnv *, jobject);
#ifdef __cplusplus
#endif
#endif
// Implements method to return a string to Java
// C++ core header
#include <iostream.h>
// header from Java Interface
#include "JNIGetUserId.h"
#include "JNIGetUserId2.h"
// returns a string back to Java for package structure
JNIEXPORT jstring JNICALL Java_com_services_localoptions_JNIGetUserId_getUser
( JNIEnv * env, jobject thisObject )
     // set up constant user id for testing return
     char* userid = "RROWEHLP";
     // return userid to caller
     return env->NewStringUTF( userid );     
// returns a string back to Java for flat structure
JNIEXPORT jstring JNICALL Java_JNIGetUserId_getUser
( JNIEnv * env1, jobject thisObject1 )
     // set up constant user id for testing return
     char* userid1 = "RROWEHL1";
     // return userid to caller
     return env1->NewStringUTF( userid1 );     
}

Ok. A co-worker figured it out for me. The key thing is to do "javah com.services.localoptions.JNIGetUserId". Note the use of "." instead of "\". Running on windows, I was used to doing "\". That was part of the problem. Another key is doing the javah at the top of the package structure. This was mentioned in a post over at IBM.
We got our JNI stuff working now. thanks, ray.

Similar Messages

  • No access to method from within the same class

    Hey there.
    First I have to excuse my English for I'm german and just learning...
    Ok, my problem is as follows. I have a class called JDBC_Wrapper it includes the method sendQuery(String query). When I call this method from within another class (where 'wrapper' is my instance of JDBC_Wrapper) it works fine. For example:
    wrapper.sendQuery("SELECT * FROM myDataBase");
    But then I have written a method called getNumRows() into my JDBC_Wrapper class.
    This method should send a query through sendQuery(Strin query) but when calling getNumRows() it says: "java.sql.SQLException: [FileMaker][ODBC FileMaker Pro driver][FileMaker Pro]Unbekannter Fehler." (Unbekannter Fehler -> Unknown Exception). What could that be?
    I'm using jdk2 sdk 1.4.2 with BlueJ. My database is Filemaker Pro 6. The ODBC/JDBC connector works fine.
    BerndZack

    This is within my JDBC_Wrapper class:
    public ResultSet sendQuery(String query)
            if(connected)
                try
                    Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                    ResultSet rs = s.executeQuery(query);
                    return rs;
                catch(Exception e)
                    System.out.println(e);
            else
                //System.out.println("There is no connection to the datasource!");
            return null;
    public int getNumRows()
            try
                ResultSet r;
                r = this.sendQuery("SELECT COUNT(*) FROM " + table_name); // At this line the error occurs
                r.next();
                return (int)r.getInt(1);
            catch(Exception e)
                System.out.println(e.getMessage());
                return -1;
    }When I call sendQuery() from within another class it works, but calling getNumRows()
    throws an exception.

  • Access native methods from an applet

    hi all
    I am developping a applet which has to access the native method which is c++ code. but it does not work at all, even though it can be compiled well.
    it returns
    java.lang.ExceptionInInitializerError
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.MemoInfo)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkLink(Unknown Source)
         at java.lang.Runtime.loadLibrary0(Unknown Source)
         at java.lang.System.loadLibrary(Unknown Source)
         at InfoShow.<clinit>(InfoShow.java:24)
         ... 11 more
    who can give me some suggestions on accessing native method from applet! thx
    regards
    beginner

    you don't have access to native code from an applet unless you've modified your policy file or you're using a signed applet.

  • How to call a set method from within a constructor

    Hello,
    I want to be able to call a set method from within a Scanner, to be used as the argument to pass to the Scanner (from a source file). Here's what i tried:
    private void openFiles()
            input = new Scanner( setSource );              
        and here is the set method:
    public String setSource( String in )
            source = in;
            return source;
        }obviously there will be more code in this method but i'm trying to tackle one problem at a time. Thanks in advance..

    The "String in" declaration says: "Nobody may ever invoke setSource() without specifying a certain String. The content of the String is known at run-time only."
    In no place in your code you say the compiler: "I want the 'in' variable (actually, parameter) of method setSource() to contain the first arg which is passed to the application".
    This is exactly the same mechanism allowing you to write "new Scanner" with something inside the two parentheses.

  • How to call methods from within run()

    Seems like this must be a common question, but I cannot for the life of me, find the appropriate topic. So apologies ahead of time if this is a repeat.
    I have code like the following:
    public class MainClass implements Runnable {
    public static void main(String args[]) {
    Thread t = new Thread(new MainClass());
    t.start();
    public void run() {
    if (condition)
    doSomethingIntensive();
    else
    doSomethingElseIntensive();
    System.out.println("I want this to print ONLY AFTER the method call finishes, but I'm printed before either 'Intensive' method call completes.");
    private void doSomethingIntensive() {
    System.out.println("I'm never printed because run() ends before execution gets here.");
    return;
    private void doSomethingElseIntensive() {
    System.out.println("I'm never printed because run() ends before execution gets here.");
    return;
    }Question: how do you call methods from within run() and still have it be sequential execution? It seems that a method call within run() creates a new thread just for the method. BUT, this isn't true, because the Thread.currentThread().getName() names are the same instead run() and the "intensive" methods. So, it's not like I can pause one until the method completes because they're the same thread! (I've tried this.)
    So, moral of the story, is there no breaking down a thread's execution into methods? Does all your thread code have to be within the run() method, even if it's 1000 lines? Seems like this wouldn't be the case, but can't get it to work otherwise.
    Thanks all!!!

    I (think I) understand the basics.. what I'm confused
    about is whether the methods are synced on the class
    type or a class instance?The short answer is; the instance for non-static methods, and the class for static methods, although it would be more accurate to say against the instance of the Class for static methods.
    The locking associated with the "sychronized" keyword is all based around an entity called a "monitor". Whenever a thread wants to enter a synchronized method or block, if it doesn't already "own" the monitor, it will try to take it. If the monitor is owned by another thread, then the current thread will block until the other thread releases the monitor. Once the synchronized block is complete, the monitor is released by the thread that owns it.
    So your question boils down to; where does this monitor come from? Every instance of every Object has a monitor associated with it, and any synchronized method or synchonized block is going to take the monitor associated with the instance. The following:
      synchronized void myMethod() {...is equivalent to:
      void myMethod() {
        synchronized(this) {
      ...Keep in mind, though, that every Class has an instance too. You can call "this.getClass()" to get that instance, or you can get the instance for a specific class, say String, with "String.class". Whenever you declare a static method as synchronized, or put a synchronized block inside a static method, the monitor taken will be the one associated with the instance of the class in which the method was declared. In other words this:
      public class Foo {
        synchronized static void myMethod() {...is equivalent to:
      public class Foo{
        static void myMethod() {
          synchronized(Foo.class) {...The problem here is that the instance of the Foo class is being locked. If we declare a subclass of Foo, and then declare a synchronized static method in the subclass, it will lock on the subclass and not on Foo. This is OK, but you have to be aware of it. If you try to declare a static resource of some sort inside Foo, it's best to make it private instead of protected, because subclasses can't really lock on the parent class (well, at least, not without doing something ugly like "synchronized(Foo.class)", which isn't terribly maintainable).
    Doing something like "synchronized(this.getClass())" is a really bad idea. Each subclass is going to take a different monitor, so you can have as many threads in your synchronized block as you have subclasses, and I can't think of a time I'd want that.
    There's also another, equivalent aproach you can take, if this makes more sense to you:
      static final Object lock = new Object();
      void myMethod() {
        synchronized(lock) {
          // Stuff in here is synchronized against the lock's monitor
      }This will take the monitor of the instance referenced by "lock". Since lock is a static variable, only one thread at a time will be able to get into myMethod(), even if the threads are calling into different instances.

  • How to call a package from within a package

    How would I call a package from within a package and pass variables to it. For instance I am trying to pass variables to a log package from another package when a user inserts or updates a table

    First, technical questions need to be addressed to one of the technical forums. Products | Database | SQL & PL/SQL would be appropriate for this question. Please direct any followup to that forum.
    Second, you cannot call a package; a package is a collection of stored procedures and functions. You can call a packaged function or procedure from another package simply by specifying the package name and the procedure
    CREATE OR REPLACE PACKAGE pkgA
    AS
      PROCEDURE callPkgB;
    END;
    CREATE OR REPLACE PACKAGE BODY pkgA
    AS
      CREATE PROCEDURE callPkgB
      AS
      BEGIN
        pkgB.someProcedure( 'Some argument' );
      END callPkgB;
    END pkgA;In general, any packaged procedure can be called by specifying the schema, package, and procedure name, i.e.
    EXEC mySchema.myPackage.myProcedurethough the schema and package can be omitted if the calling procedure is in the same schema or package.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • How to refer to enclosing instance from within the member class?

    Hi
    How to refer to the enclosing instance from within the member class?
    I have the following code :
    import java.awt.*;
    import java.awt.event.*;
    public class MyDialog extends Dialog
         public MyDialog(Frame fr,boolean modal)
              super(fr,modal);
              addWindowListener(new MyWindowAdapter());
         public void paint(Graphics g)
              g.drawString("Modal Dialogs are sometimes needed...",10,10);
         class MyWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent evt)
                   //MyDialog.close(); // is this right?
    In the above code, how can I call the "close()" method of the "Dialog" class (which is the enclosing class) from the inner class?
    Thanks in advance.
    Senthil.

    Hi Senthil,
    You can directly call the outer class method. Otherwise use the following way MyDialog.this.close(); (But there is no close() method in Dialog!!)
    If this is not you expected, give me more details about problem.
    (Siva E.)

  • Running a "heavy" program from within a java class

    Dear Java programmers,
    I 'm trying to run a software called surflex from within a java class, using the following java command:
    Runtime.getRuntime().exec( new String[ { "/bin/bash", "docking_script_2.bash"} );
    For convenience I've created the following simple bash script but for some strange reason surflex is not executed:
    #!/bin/bash
    surflex-dock-v211-linux.exe proto drug.mol2 receptor_hydro.mol2 p1;
    surflex-dock-v211-linux.exe dock drug.mol2 p1-protomol.mol2 receptor_hydro.mol2 >& 1OHR_A_output.txt;
    Can anybody help me on that (ignore the arguments, they are correctly set)? I'll try to find another, more generic example, but so far I've noticed that the same thing happens with unix grep command.
    thanks,
    Tom

    I think if you want to invoke a bash shell and give it a command to execute, you need to do
    /bin/bash -c commandrather than
    /bin/bash commandAccordingly, your call to exec should look like
    exec( new String[ { "/bin/bash", "-c" "docking_script_2.bash"} );Beyond, that, I'd suggest the following as general debugging tips and best practices:
    * As the first line of the bash script, include a line that does something simple, like touch a file, so you can see if the script is executing at all.
    * In Java, call Process.waitFor(). Its return value is the process' exit value.
    * Make sure you're gobbling stdout and stderr from the process, and giving stdin any input it needs. You'll have to do this for the process to run correctly, and you can also use what you read from stdout and stderr to debug the execution of the process. [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
    * You may wan to look into ProcessBuilder, rather than Runtime.exec. I haven't used it myself yet, but apparently it's supposed to be the preferred way to execute external processes.

  • Why I can't call my native method from my package?

    it is fine if my java code didn't complied into a package.
    But if I complied my java code as a package, and call its native method outside. It give me "UnsatisfiedLinkError". And can not find my method. It is indeed the method is inside.
    Thank a lot any helps. Email me on [email protected]

    I have found that javah does not generate the correct JNI function names when the native function is in a class that is within a Java package. The net result is an Unsatisfied link error.
    The JNI function name must be included in the package name. The naming is a bit complicated and that's why javah should be used, except in this case it does not work. I can't quite remember exactly how it works, something like adding in packagename_1 into the JNI name. The SWIG tool (http://www.swig.org) does generate the correct names when using packages. It is a tool which takes C or C++ header files and generates the JNI and Java classes for you so that you can call C/C++ code from Java. Once you have installed SWIG and run 'make check', have a look in the directory Examples/test-suite/java for the JNI naming for packages. I'll try remember to post the exact naming if you don't want to install SWIG.

  • Accessing a method from within another method

    I am having trouble accessing a method from inside a method in the same class.
    here is my code:
    public String getAns(int ans){
    answer = ans;
    ranswer = number1 * number2;
    if(answer != ranswer){
    return "No. Please try again";
    }else{
    return "Very good!";
    genQues();
    when i run this i get an Unreachable code error pertaining to genQues();
    is this allowed in Java and is there a more practical way to go about this?
    Thank you in advance

    next time use the correct code tags to post your code.
    Think of your problem like this though.
    You write
    if( something )
    then return some value;
    else
    then return some other value.
    The returns end the method here, returning the value.
    So, if the method ended at one of these 2 statements, how do you think it'll reach genQues(); ?
    Hope this helps.

  • EJB 3.1 @Asynchronous and calling other methods from within

    Hey all,
    I am helping a friend set up a test framework, and I've turned him on to using JEE6 for the task. I am decently familiar with entity beans, session beans, and such. One of the new features is @Asynchronous, allowing a method to be ran on a separate thread. The test framework generally needs to spawn potentially 1000's of threads to simulate multiple users at once. Originally I was doing this using the Executor classes, but I've since learned that for some reason, spawning your own threads within a JEE container is "not allowed" or bad to do. I honestly don't quite know why this is.. from what I've read the main concern is that the container maintains threads and your own threads could mess up the container somehow. I can only guess that this might be possible if your threads use the container services in some way.. but if anyone could enlighten me on the details as to why this is bad, that would be great.
    None the less, EJB 3.1 adds the async capability and I am now looking to use this. From my servlet I use @EJB to access the session bean, and call an async method. My servlet returns right away as it should. From the async method I do some work and using an entity bean store results, so I don't need to return a Future object. In fact, my ejb then makes an HttpClient call to another servlet to notify it that the result is ready.
    My main question though, is if it's ok to call other methods from the async method that are not declared @Asynchronous. I presume it is ok, as the @Asynchronous just enables the container to spawn a thread to execute that method in. But I can't dig up any limitations on the code within an async method.. whether or not it has restrictions on the container services, is there anything wrong with using HttpClient to make a request from the method.. and making calls to helper methods within the bean that are not async.
    Thanks.

    851827 wrote:
    Hey all,.. from what I've read the main concern is that the container maintains threads and your own threads could mess up the container somehow. I can only guess that this might be possible if your threads use the container services in some way.. but if anyone could enlighten me on the details as to why this is bad, that would be great.
    Yes since the EE spec delegated thread management to conatiners, the container might assume that some info is available in the thread context that you may not have made available to your threads.
    Also threading is a technical implementation detail and the drive with the EE spec is that you should concentrate on business requirements and let the container do the plumbing part.
    If you were managing your own threads spawned from EJBs, you'd have to be managing your EJBs' lifecycle as well. This would just add to more plumbing code by the developer and typically requires writting platform specific routines which the containers already do anyway.
    >
    None the less, EJB 3.1 adds the async capability and I am now looking to use this. From my servlet I use @EJB to access the session bean, and call an async method. My servlet returns right away as it should. From the async method I do some work and using an entity bean store results, so I don't need to return a Future object. In fact, my ejb then makes an HttpClient call to another servlet to notify it that the result is ready.
    My main question though, is if it's ok to call other methods from the async method that are not declared @Asynchronous. I presume it is ok, as the @Asynchronous just enables the container to spawn a thread to execute that method in. But I can't dig up any limitations on the code within an async method.. whether or not it has restrictions on the container services, is there anything wrong with using HttpClient to make a request from the method.. and making calls to helper methods within the bean that are not async.
    Thanks.If you want to be asynchronous without caring about a return value then just use MDBs.
    The async methods have no restrictions on container services and there is nothing wrong with calling other non async methods. Once the async method is reached those annotations don't matter anyway (unless if you call thhose methods from a new reference of the EJB that you look up) as they only make sense in a client context.
    Why do you need to make the call to the servlet from the EJB? Makes it difficult to know who is the client here. Better use the Future objects and let the initial caller delegate to the other client components as needed.

  • Call native methods from windows dll

    Hello all,
    I want to call BlockInput method from User32.dll. My source code looks something like this:
    public class User32Dll_1 {
         static {
              try {
                   System.loadLibrary("User32");
              catch (Exception ex)
                   ex.printStackTrace();
         public static void main(String[] args) throws UnsatisfiedLinkError {
              BlockInput (true);
         /** @param b
         * @dll.import("USER32")*/
         private static native boolean BlockInput(boolean bBOOL);
    And the problem is that I get the following exception:
    java.lang.UnsatisfiedLinkError: BlockInput
         at User32Dll_1.BlockInput(Native Method)
         at User32Dll_1.main(User32Dll_1.java:27)
    Exception in thread "main"
    Can someone provide me a solution for this?
    Thank you in advance!

    can't do
    use JACOB
    http://danadler.com/jacob/
    or
    http://www.ezjcom.com/

  • Urgent - How to call native methods from J2ME

    Hi,
    I have to do some very heavy processing work, so I have my code written in C. And now I want these native functions to be called from a J2ME application. I had thought this was not possible and J2ME did not support something like JNI as J2SE did.
    However, when contacted with Sun Technical Support we were advised to use KNI in J2ME. I went through the KNI documentation and did not find any example to do so.
    On reading about it I understood that it cannot be implemented by developers as the native functions if any using KNI should be implemented while compiling the KVM.
    I would like to know whether my understanding is correct, or is it possible to call native functions from J2ME. Say I would like to have my native functions called from J2ME and run it on my Nokia N73 or other such phones.
    Experts please clear this.
    Regards,
    Kamalakshan

    Hi,
    You are right in your assumptions regarding KNI. Here is some related thread that might also help. There has been [some work|http://developer.symbian.com/main/downloads/papers/MIDlet_Native_Services_Framework/MIDlet_Native_Services_Framework_v1.1.zip] done in accessing native services through a MIDlet.
    Mihai

  • How do I access BSD file tree from within Linux?

    I just installed PC-BSD 8.0 RC on an external USB HDD.  I went with the PC-BSD default partition layout, i.e. one primary partition for the entire PC-BSD slice, and 4 "partitions" within that slice, for /, swap, /usr and /var.
    In order to access the PC-BSD file tree from within Linux, I mount it as follows:
    mount -t ufs -o ufstype=ufs2,ro /dev/sdb1 /mnt/bsd
    But after executing this command I can only access the PC-BSD / , not /usr and /var , presumably because they reside on two BSD "partitions" (subslices) different from / .  Is there any way I can mount these (read-only) in Linux, too, or would I have to reinstall PC-BSD and opt for laying out the slice differently, i.e. specifying only / and swap in sdb1?
    Last edited by RobF (2010-02-13 11:55:39)

    Look at  /dev/sdb*  there should be more than just sdb1.  You would need to mount those to see which is which.  For ufs write support the default kernel needs to be recompiled with experimental enabled.

  • Calling parent method from within child object

    Hello,
    A quick question! Is it possible to call a method in a parent object from within a child object.By child object I mean an object that was instantiated within the parent object.
    Thanks.

    A quick question! Is it possible to call a method in a
    parent object from within a child object.By child
    object I mean an object that was instantiated within
    the parent object.Since you are using ambiguous terminology, it would be much better if you provided a small sample of your code to avoid confusion. I am guessing that you are actually talking about an inner class when you say child class.
    If that is correct, then you can do something like this:
    class Parent {
      void foo() {}
      void bar() {}
      class Child {
        void foo() {}
        void test() {
          bar(); // No conflicts, just call the Parent method
          Parent.this.foo(); // Use explicit qualification to avoid conflicts.

Maybe you are looking for

  • Scheduling with JOB_CLOSE - Can I have multiple Predecessor Jobs?

    I have a situation where I need to submit a job stream with several individual jobs.  Some of the early jobs can run in parallel, and I don't know which will finish first.  I don't want the final job to start until all previous jobs have finished. Th

  • Is there a way of making contacts in CS4???

    Is there a way of making contacts in CS4??? I can't find it and I have to go back to CS3 every time I have to give proofs to my clients. I hope is not taken out from the program. Thanks, Dan Demetriad [email deleted for privacy]

  • Why cant I group by large fields, and why dont these print properly?

    I have a number of Crystal Reports fed by my database which has a table in it that stores Paths (to given files and locations). In SQL Server this path column is set to nvarchar(MAX). However, whenever I try to use this column in reports 2 things app

  • Error in connecting a remote server

    hi friends, Though Cisco VPN i'm trying to establish connection with a remote server.The VPN connection is successfully established but when trying to logon to the sap server it gives NI(Network Interface error) Can any one give some idea on what can

  • Why can i not install DesignStandard_CS6_LS4 ?

    after every try i get the message i must restart my pc. i did it but the problem is the same