Using C++ classes in Java

I need links, ebooks or other resources of using C++ in Java using JNI.
regards!

Yes! I have understand it.
Now I am reached to this link http://www.javaworld.com/javaworld/javatips/jw-javatip17.html?page=2
void NumberListProxy_initCppSide(struct HNumberListProxy* Obj);
the method signature is different from the one that is generated here at my machine by java which is:
JNIEXPORT void JNICALL Java_NumberListProxy_initCppSide
(JNIEnv *, jobject);
Also when I run the command ' javah stubs NumberListProxy '
Error: JNI does not require stubs, please refer to the JNI documentation.
I think u ( bschauwejava ) can tell me about this problem.

Similar Messages

  • Most commenly used abstract class in java.

    hi all,
    can anyone please tell me, what is most commonly used abstract class in java. this question was asked in interview.

    I hate interviewers when they ask about specifics of some classes.The fact that you hate it doesn't automatically follow that it's a bad question from the perspective of the person conducting the interviewer. You don't know what the real question is.
    Bad "real" question: Do you know the statistics of Java usage off the top of your head?
    Good "real" question: Do you know that Object isn't Abstract and can you name a few Abstract classes off the cuff?
    Even then Programmers are so literal minded - the real question may be "Talk about what you know a bit."

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

  • Problems changing colour using Graphics class in java.awt

    Hi,
    The problem only happens when more than two images are on a panel. In this case, I have to strings that are drawn. The first drawn string is called "A" the second drawn string is called "B". However, when i change the colour of "B" to let's say Red, the panel erases the letter "B" and insteads changes "A" to red. How can I fix this so that when the user chooses the colour red it changes the colour of the latest drawn string and not the first one. please help!!!!
    import java.awt.*;
    public class StringPanel extends GBPanel
         private String shape = "clear", str;
         private int x, y;
         private Color color = Color.black;
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor (color);
              if(shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else if (shape.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void drawCurve(Color color)
         this.color = color;
         repaint();
         public void drawString(String shape, String str, int x, int y)
              this.shape = shape;
              this.str = str;
              this.x = x;
              this.y = y;
              repaint();
         public void drawString1(String shape, String str, int x, int y)
              Graphics g = getGraphics();
              g.setColor(color);
              if (shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else
                   repaint();
    }

    well, as I said, I can't remember what the update method thing was for... I think it was related to not clearing the screen first.
    Anyway, if you maintain a list of objects that should be drawn and then in the paintComponent method, loop thru the list of objects and redraw them, it will work. Then you change the state of an object and call repaint. When you are going to change color, you need to, in effect, redraw the entire affected area. Now this can be done partially with clipping, but it's complicated to deal with that. So the simplest way is just redraw everything on repaint.

  • Java6: How to compile java using JavaCompiler class

    Hi all,
    Using JavaCompiler, we can run the java program thru programmaticaly using run() method.
    Could anyone please tell me how to compile a java program using JavaCompailer class? Or calling run() itself will compile java file?
    Thanks
    Shagil

    import spoon.support.input.SpoonInputStream;
    import com.sun.tools.javac.code.Symbol.ClassSymbol;
    import com.sun.tools.javac.comp.Attr;
    import com.sun.tools.javac.comp.AttrContext;
    import com.sun.tools.javac.comp.Enter;
    import com.sun.tools.javac.comp.Env;
    import com.sun.tools.javac.comp.Todo;
    import com.sun.tools.javac.tree.Tree;
    import com.sun.tools.javac.tree.Tree.ClassDef;
    import com.sun.tools.javac.tree.Tree.TopLevel;
    import com.sun.tools.javac.util.Abort;
    import com.sun.tools.javac.util.Context;
    import com.sun.tools.javac.util.List;
    import com.sun.tools.javac.util.ListBuffer;
    import com.sun.tools.javac.util.Log;
    import com.sun.tools.javac.util.Name;
    * The Spoon compiler (uses javac).
    public class SpoonCompiler extends com.sun.tools.javac.main.JavaCompiler {
         Attr attr;
         Enter enter;
         boolean hasBeenUsed = false;
         Log log;
         Todo todo;
         public SpoonCompiler(Context arg0) {
              super(arg0);
              enter = Enter.instance(arg0);
              todo = Todo.instance(arg0);
              log = Log.instance(arg0);
              attr = Attr.instance(arg0);
              sourceOutput=true;
          * Main method: compile a list of files, return all compiled classes
          * @param filenames
          *            The names of all files to be compiled.
         @SuppressWarnings("unused")
         public List<Tree> parseAndAttribute(List<SpoonInputStream> filenames)
                   throws Throwable {
              // as a JavaCompiler can only be used once, throw an exception if
              // it has been used before.
              assert !hasBeenUsed : "attempt to reuse JavaCompiler";
              hasBeenUsed = true;
              long msec = System.currentTimeMillis();
              ListBuffer<ClassSymbol> classes = new ListBuffer<ClassSymbol>();
              try {
                   // parse all files
                   ListBuffer<Tree> trees = new ListBuffer<Tree>();
                   for (List<SpoonInputStream> l = filenames; l.nonEmpty(); l = l.tail) {
                        trees.append(parse(l.head.getFileName(),l.head.getStream()));
                   // enter symbols for all files
                   List<Tree> roots = trees.toList();
                   if (errorCount() == 0)
                        enter.main(roots);
                   // If generating source, remember the classes declared in
                   // the original compilation units listed on the command line.
                   List<ClassDef> rootClasses = null;
                   if (sourceOutput || stubOutput) {
                        ListBuffer<ClassDef> cdefs = new ListBuffer<ClassDef>();
                        for (List<Tree> l = roots; l.nonEmpty(); l = l.tail) {
                             for (List<Tree> defs = ((TopLevel) l.head).defs; defs
                                       .nonEmpty(); defs = defs.tail) {
                                  if (defs.head instanceof ClassDef)
                                       cdefs.append((ClassDef) defs.head);
                        rootClasses = cdefs.toList();
                   while (todo.nonEmpty()) {
                        Env<AttrContext> env = todo.next();
                        // save tree prior to rewriting
                        Tree untranslated = env.tree;
                        // attribution phase
                        if (verbose)
                             printVerbose("checking.attribution", env.enclClass.sym);
                        Name prev = log.useSource(env.enclClass.sym.sourcefile);
                        attr.attribClass(env.tree.pos, env.enclClass.sym);
                   return trees.toList();
              } catch (Abort ex) {
                   ex.printStackTrace();
              if (verbose)
                   printVerbose("total", Long.toString(System.currentTimeMillis()
                             - msec));
              int errCount = errorCount();
              if (errCount == 1)
                   printerCount("error", errCount);
              else
                   printerCount("error.plural", errCount);
              if (log.nwarnings == 1)
                   printerCount("warn", log.nwarnings);
              else
                   printerCount("warn.plural", log.nwarnings);
              return null;
         private void printerCount(String str, int val) {
              System.err.println(str + " - " + val);
         private void printVerbose(String arg0, Object obj) {
              System.out.println(arg0 + " - " + obj.toString());
    --- NEW FILE: CtBuilder.java ---
    package spoon.support.builder;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.Stack;
    import java.util.TreeSet;
    import spoon.query.Query;
    import spoon.query.TypeFilter;
    import spoon.reflect.CtFactory;
    import spoon.reflect.code.BinaryOperatorKind;
    import spoon.reflect.code.CtAbstractInvocation;
    import spoon.reflect.code.CtArrayAccess;
    import spoon.reflect.code.CtAssert;
    import spoon.reflect.code.CtAssignment;
    import spoon.reflect.code.CtBinaryOperator;
    [...1760 lines suppressed...]
                var.setSimpleName(tree.sym.name.toString());
                var.setModifiers(getModifiers(tree.mods.flags));
                enter(var, tree);
                scan(tree.init);
                exit(var, tree);
        @Override
        public void visitWhileLoop(WhileLoop tree) {
            CtWhile whileLoop = new CtWhileImpl();
            enter(whileLoop, tree);
            builderContext.loopParameter = 1;
            scan(tree.cond);
            builderContext.loopParameter = 0;
            scan(tree.body);
            exit(whileLoop, tree);
    }

  • What is the use of Generic class in java

    hi everyone,
    i want to know that
    what is the use of Generic class in java ?
    regards,
    dhruvang

    Simplistically...
    A method is a block of code that makes some Objects in the block of code abstract (those abstract Objects are the parameters of the method). This allows us to reuse the method passing in different Objects (arguments) each time.
    In a similar way, Generics allows us to take a Class and make some of the types in the class abstract. (These types are the type parameters of the class). This allows us to reuse the class, passing in different types each time we use it.
    We write type parameters (when we declare) and type arguments (when we use) inside < >.
    For example the List class has a Type Parameter which makes the type of the things in the list become abstract.
    A List<String> is a list of Strings, it has a method "void add(String)" and a method "String get(int)".
    A List<File> is a list of Files, it has a method "void add(File)" and a method "File get(int)".
    List is just one class (interface actually but don't worry about that), but we can specify different type arguments which means the methods use this abstract type rather than a fixed concrete type in their declarations.
    Why?
    You spend a little more effort describing your types (List<String> instead of just List), and as a benefit, you, and anyone else who reads your code, and the compiler (which also reads your code) know more accurately the types of things. Because more detail is known, the compiler is able to tell you when you screw up (as opposed to finding out at runtime). And people understand your code better.
    Once you get used to them, its a bit like the difference between black and white TV, and colour TV. When you see code that doesn't specify the type parameters, you just get the feeling that you are missing out on something. When I see an API with List as a return type or argument type, I think "List of what?". When I see List<String>, I know much more about that parameter or return type.
    Bruce

  • First use of jsp and java bean and "Unable to compile class for JSP" error

    Hi,
    I am trying to create my first jsp + java bean and I get a basic error (but I have no clue what it depends on exactly). Tomcat seems to cannot find my class file in the path. Maybe it is because I did not create a web.xml file. Did I forgot to put a line in my jsp file to import my bean?
    Thank you very much for your help.
    Here is my error:
    An error occurred at line: 2 in the jsp file: /login.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    /usr/local/tomcat/jakarta-tomcat-5/build/work/Catalina/localhost/test/org/apache/jsp/login_jsp.java:43: cannot resolve symbol
    symbol : class CMBConnect
    location: class org.apache.jsp.login_jsp
    CMBConnect test = null;
    I only have this in my directory:
    test/login.jsp
    test/WEB-INF/classes/CMBConnect.java
    test/WEB-INF/classes/CMBConnect.class
    Do I need to declare another directory in classes to put my class file in it and package my bean differently?
    Here is my login.jsp:
    <%@ page errorPage="error.jsp" %>
    <jsp:useBean id="test" type="CMBConnect" scope="session" />
    <html>
    <head>
    <title>my test</title>
    </head>
    <body>
    <h3>Login information</h3>
    <b><%=session.getValue("customerinfo.message")%></b>
    <form> ....... </form>
    </body>
    </html>
    and here is my CMBConnect.java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class CMBConnect
    public CMBConnect () { }
    public String openConnection(String id, String password) {
    String returnText = "";
    try {
    Connection con = null;
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection("jdbc:oracle:thin:@myserver.abc.com:1521:TEST", id, password);
    if(con.isClosed())
    returnText = "Cannot connect to Oracle server using TCP/IP...";
    else
    returnText = "Connection successful";
    } catch (Exception e) { returnText = returnText + e; }
    return returnText;
    Thanks again!

    Thanks for you help
    I created the package and I get this error this time:
    javax.servlet.ServletException: bean test not found within scope
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:822)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:755)
         org.apache.jsp.login_jsp._jspService(login_jsp.java:68)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:268)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:277)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:223)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

  • Only to import  JAVA CLASS  and JAVA SOURCE  from .DMP file using IMPDP

    hi,
    I have a schema X, In that schema some of the *"JAVA CLASS" and "JAVA SOURCE"* objects are missing ..
    The procedures ,functions..etc objects were updated at X schema..
    I have 1 dmp file of Y schema , containing the missing "JAVA CLASS" and "JAVA SOURCE" s.. Can I import the the same to the schema X using IMPDP
    i tried using INCLUDE clause but it is not working
    eg:
    impdp john1/john1@me11g22 directory=datadump dumpfile=DEVF2WAR.DMP remap_schema=devf2war:john INCLUDE="JAVA CLASS","JAVA CLASS"but error..
    ORA-39001: invalid argument value
    ORA-39041: Filter  "INCLUDE" either identifies all object types or no object types.regards,
    jp

    Double post: IMPDP to import  JAVA CLASS  and JAVA SOURCE from .DMP file
    Already replied.
    Regards
    Gokhan

  • Binding XML to java types generated using Oracle Class Gen

    Hi,
    how can you bind an XML to the java types generated using the class gen provided byOracle.
    I am using oracle 9i production. as part of my design, i have to read an xml input in my java class and use the contents to create some records and send a response xml back.
    The latter part of i can do as the java types provide setter methods to set the data and conversion to xml.
    Jaxb can be using to bind xml to java datatypes but its not supported in Oracle9i.
    What are the alternatives for achieving the same?
    Thanks
    Ashwin

    Hi Ashwin,
    This is a bit outside my area of expertise, but I did run an older version of TopLink in the Oracle database java VM a few years back so I'll base my advice on that. Hopefully other forum members can correct me if I steer you wrong.
    First you will need to set up your XML environment:
    I believe the Oracle 9i database includes a JDK 1.3 VM. You will first need to determine if the VM includes any JAXP APIs. I believe there is an SQL query that allows you to query the classes available in the VM. First check if javax.xml.parsers.DocumentBuilderFactory is present.
    If the JAXP APIs are already present in the database you will need to do the following. First load the class javax.xml.namespace.QName into the database. You can extract this from xmlparserv2.jar or from Suns Java Web Service Developer Pack jax-qname.jar. Then you will need to load the JAXB APIs. You can load xml.jar or jaxb-api.jar from Sun's JWSDP.
    If the JAXP APIs are not present you will need to load the 10.1.3 version of the XDK jars (these are shipped with the 10.1.3 TopLink install). Load xmlparserv2.jar and xml.jar into the database.
    Second you will need to setup your TopLink environment:
    Load toplink.jar into the database. If the JAXP APIs were already present and you didn't load the 10.1.3 XDK jars into the database you will need to set the following System property.
    toplink.xml.platform=oracle.toplink.platform.xml.jaxp.JAXPPlatform-Blaise

  • How to use funchtion diffInJulianDays() of Java Date class?

    Who has ever used this function successful?
    There are three parameters for the function. The second and third parameter are of int[] type. How can I define this kind of parameter since I don't know its exact length.

    Hello Vishal,
    Let-me try help you.
    I don´t know if that´s the best solution, but when I use this class, i do as follow.
    First I create the container, and after the grid (with the "I_PARENT" parameter)
    DATA: r_container TYPE REF TO cl_gui_custom_container,
                r_grid          TYPE REF TO cl_gui_alv_grid.
      CREATE OBJECT r_container
        EXPORTING
          container_name = 'CONTAINER1'.
      CREATE OBJECT r_grid
        EXPORTING
          i_parent = r_container.
    The parameter i_parent associate the container with the grid.
    Don´t forget to built the container using the screen painter (or the screen element´s list, but the screen painter is easer).
    I hope it helps you.

  • How to use excel api in java?

    I need to use excel api in Java to generate data in excel format. Can any one tell any of the use ful Excel api that we can down load from net? i have read about Apache's POi-hssf-Java api. But the jar i downloaaded from Apache site is not working ? Can anybody please send me the jar for taht Api ?

    Hi,
    In fact i was not clear about whcih jar file to download from the apache site. i found one folder structure like this
    -parent
    -bin
    -src
    All these folders contained some zip files. i took the zip files and extracted them. And i set teh class path also . But when i tried to import in java programs ,these jar files are giving compilation errors

  • Not able to get group name by using memberof class, getting Total groups as 0 even I am member of that group.

    Not able to get group name by using memberof class, getting Total groups as 0 even I am member of that group. Through this memberof class I am trying to find full qualified name(DN) of my group.
    code I have used:
    //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(CN=Username))";
                   //Specify the Base for the search
                   String searchBase = "";
    Also I have used,
                 String searchFilter = "(&(objectClass=user)(CN=Username))";
                   //Specify the Base for the search
                   String searchBase = "ou=ibmgroups,o=ibm.com";
    But in both cases I am getting value for Total groups as 0.
    Code Reference:
    * memberof.java
    * December 2004
    * Sample JNDI application to determine what groups a user belongs to
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    public class memberof     {
         public static void main (String[] args)     {
              Hashtable env = new Hashtable();
              String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
              String adminPassword = "XXXXXXX";
              String ldapURL = "ldap://mydc.antipodes.com:389";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   //Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   //Create the search controls          
                   SearchControls searchCtls = new SearchControls();
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(CN=Andrew Anderson))";
                   //Specify the Base for the search
                   String searchBase = "DC=antipodes,DC=com";
                   //initialize counter to total the group members
                   int totalResults = 0;
                   //Specify the attributes to return
                   String returnedAtts[]={"memberOf"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Search for objects using the filter
                   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
                   //Loop through the search results
                   while (answer.hasMoreElements()) {
                        SearchResult sr = (SearchResult)answer.next();
                        System.out.println(">>>" + sr.getName());
                        //Print out the groups
                        Attributes attrs = sr.getAttributes();
                        if (attrs != null) {
                             try {
                                  for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
                                       Attribute attr = (Attribute)ae.next();
                                       System.out.println("Attribute: " + attr.getID());
                                       for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) {
                                            System.out.println(" " +  totalResults + ". " +  e.next());
                             catch (NamingException e)     {
                                  System.err.println("Problem listing membership: " + e);
                   System.out.println("Total groups: " + totalResults);
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem searching directory: " + e);
    Any help will be highly appreciated.

    Not able to get group name by using memberof class, getting Total groups as 0 even I am member of that group. Through this memberof class I am trying to find full qualified name(DN) of my group.
    code I have used:
    //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(CN=Username))";
                   //Specify the Base for the search
                   String searchBase = "";
    Also I have used,
                 String searchFilter = "(&(objectClass=user)(CN=Username))";
                   //Specify the Base for the search
                   String searchBase = "ou=ibmgroups,o=ibm.com";
    But in both cases I am getting value for Total groups as 0.
    Code Reference:
    * memberof.java
    * December 2004
    * Sample JNDI application to determine what groups a user belongs to
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    public class memberof     {
         public static void main (String[] args)     {
              Hashtable env = new Hashtable();
              String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
              String adminPassword = "XXXXXXX";
              String ldapURL = "ldap://mydc.antipodes.com:389";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   //Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   //Create the search controls          
                   SearchControls searchCtls = new SearchControls();
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(CN=Andrew Anderson))";
                   //Specify the Base for the search
                   String searchBase = "DC=antipodes,DC=com";
                   //initialize counter to total the group members
                   int totalResults = 0;
                   //Specify the attributes to return
                   String returnedAtts[]={"memberOf"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Search for objects using the filter
                   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
                   //Loop through the search results
                   while (answer.hasMoreElements()) {
                        SearchResult sr = (SearchResult)answer.next();
                        System.out.println(">>>" + sr.getName());
                        //Print out the groups
                        Attributes attrs = sr.getAttributes();
                        if (attrs != null) {
                             try {
                                  for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
                                       Attribute attr = (Attribute)ae.next();
                                       System.out.println("Attribute: " + attr.getID());
                                       for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) {
                                            System.out.println(" " +  totalResults + ". " +  e.next());
                             catch (NamingException e)     {
                                  System.err.println("Problem listing membership: " + e);
                   System.out.println("Total groups: " + totalResults);
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem searching directory: " + e);
    Any help will be highly appreciated.

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

Maybe you are looking for

  • OLE Container linked documents conversion to Web Forms

    We have developed a form within our Oracle 6i application which allows users to navigate directly from the Forms application to relevant documents. We use an OLE container and the documents (Word, Excel, PDF etc) are linked rather than embedded in th

  • FCP X opens but no window appears?

    Upon clicking FCP X, the icon jumps up and down, but then stops, but then no windows appear? Not even the little start up one. Any help?

  • Real time interview questions

    Hi gurus Can anyone of u pls give answers for the following real time interview questions. 1.How do you implement a new object required by ur Client...and what are all the proccess up to Production Server....? 2.What is the Role played by RFC is SAP

  • Need utilities class for application server file system (i.e. unix etc)

    I need to do things to directories and files on the application server. Is there an SAP class with methods for the application server file system (i.e. unix or whatever) with functionality similiar to what is provided by the methods of CL_GUI_FRONTEN

  • MATSHITA DVD-RAM UJ-875S - Anyone know which media are compatible with this

    Hi, I bought the Matshita DVD-RAM US-875S from the PowerBook Guy and installed it in my G4 Pismo. I have corresponded with their support--who reply, but without actually answering. On PowerBook Guy's site, the thing is described as a Superdrive DL DV