Can't create Java VM ?

Hi,
I tried to invoke JavaVM in C. And use the example from http://java.sun.com/docs/books/tutorial/native1.1/invoking/invo.html.
But when runed it after compiled it in Win32 with VC6.
It just can't create the VM. The following is the source:
========================================
#include <jni.h>
#ifdef _WIN32
#define PATH_SEPARATOR ';'
#else /* UNIX */
#define PATH_SEPARATOR ':'
#endif
#define USER_CLASSPATH "." /* where Prog.class is */
main() {
     JNIEnv *env;
     JavaVM *jvm;
     jint res;
     jclass cls;
     jmethodID mid;
     jstring jstr;
     jobjectArray args;
     char classpath[1024];
     JavaVMInitArgs vm_args;
     JavaVMOption options[4];
     options[0].optionString = "-Djava.compiler=NONE"; /* disable JIT */
     options[1].optionString = "-Djava.class.path=.";                     /* user classes */
     options[2].optionString = "-Djava.library.path=.";                /* set native library path */
     options[3].optionString = "-verbose:jni"; /* print JNI-related messages */
     vm_args.version = JNI_VERSION_1_2;
     vm_args.options = options;
     vm_args.nOptions = 4;
     vm_args.ignoreUnrecognized = 1;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
/* Append USER_CLASSPATH to the end of default system class path */
//sprintf(classpath, "%ls%c%s", vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH);
//vm_args.classpath = casspath;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
exit(1);
cls = (*env)->FindClass(env, "Prog");
if (cls == 0) {
fprintf(stderr, "Can't find Prog class\n");
exit(1);
mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
//mid = (*env)->GetMethodID(cls, "Yup","(I)Ljava/lang/String;"); /* Search the Method of class*/
if (mid == 0) {
fprintf(stderr, "Can't find Prog.main\n");
exit(1);
jstr = (*env)->NewStringUTF(env, " from C!");
if (jstr == 0) {
fprintf(stderr, "Out of memory\n");
exit(1);
args = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), jstr);
if (args == 0) {
fprintf(stderr, "Out of memory\n");
exit(1);
(*env)->CallStaticVoidMethod(env, cls, mid, args);
(*jvm)->DestroyJavaVM(jvm);
========================================
Would you please to tell me why it failed and please show me a simple example ?
Best regards,
Eric

I have the same problem,
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void **)&env,
nv, &vm_args);
if (res < 0) {
fprintf(stderr, "Can't create Java VM: %d\n",
%d\n", res);
exit(1);
res is -1...but I'm not using windows, I'm using Linux
and Solaris...Hi there,
I also have problem calling JNI_CreateJavaVM on Linux (returns -1). Have you been able to solve this in the meantime?

Similar Messages

  • Can't create Java VM [Code :- 3 ] with JNI_CreateJavaVM()

    hello all,
    I am trying to create an inctance of JVM from C/CPP ( iam using VC++ editor) on windows. My code to create JVM is :
    res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
    as a reasult of this call, -3 is returned to res.
    please help me to create a JVM and/or call a java class from C/CPP
    Thanks in advance,
    Soujanya.R

    I tried to run it this way :-
    #include <jni.h>
    #include <windows.h>
    #define JNI_EVERSION (-3) /* JNI version error */
    #define PATH_SEPARATOR ';'
    #define USER_CLASSPATH "." /* where Prog.class is */
    void main() {
              JNIEnv *env;
              JavaVM jvm = (JavaVM )0;
              jint res;
              jclass cls;
              jmethodID mid;
              jstring jstr;
              jobjectArray args;
              HINSTANCE hVM = NULL;
              JavaVMInitArgs vm_args;
              JavaVMOption options[4];
              printf("\noptions");
              options[1].optionString = "-Djava.class.path=C:/j2sdk1.4.1_07/jre/lib/rt.jar;E:/test/c/Debug/"; /* user classes */
              options[2].optionString = "-Djava.library.path=lib"; /* set native library path */
              options[0].optionString = "-Djava.compiler=NONE";
              //options[1].optionString = "-Djava.class.path=c:\\My Folder"; /* user classes */
              //options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_04\\include";
              options[3].optionString = "-verbose:jni";
              printf("\nversion info");
              vm_args.version = JNI_VERSION_1_2;
              vm_args.options = options;
              vm_args.nOptions = 4;
              vm_args.ignoreUnrecognized = TRUE;
              printf("\ncreate");
              hVM = LoadLibrary("C:/j2sdk1.4.1_07/jre/bin/client/jvm.dll");
              if (hVM == NULL)
                   printf("hVM is null ");
              res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
              if (res < 0) {
                   fprintf(stderr, "Can't create Java VM \n",res);
                   exit(1);
              cls = env->FindClass("HelloWorld");
              //cls = env.FindClass(env,"helloWorldClass");
              if (cls == 0) {
                   fprintf(stderr, "Can't find Prog class\n");
                   exit(1);
              mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
              if (mid == 0) {
                   fprintf(stderr, "Can't find Prog.main\n");
                   exit(1);
              jstr = env->NewStringUTF(" from C!");
              if (jstr == 0) {
                   fprintf(stderr, "Out of memory\n");
                   exit(1);
              args = env->NewObjectArray(1, (*env).FindClass("java/lang/String"), jstr);
              if (args == 0) {
                   fprintf(stderr, "Out of memory\n");
                   exit(1);
              env->CallStaticVoidMethod(cls, mid, args);
              jvm->DestroyJavaVM();
    I could run the program.
    You need to have the C:\j2sdk1.4.1_07\lib\jvm.lib entries in Project->Settings->Link Tab
    When you open the Settings dialog box you will see Win32Debug in the
    drop down . You need to provide the entries for that page .
    Then change the drop down to Win32 Release and make an entry similarly there too.
    You should be able to run your code.
    Vishal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Can't create Java Object in ASP

    Hi:
    I'm attempting to incorporate a Java class that uses the following packages into an .ASP page
    import java.security.*;
    import java.io.*;
    import java.net.URLDecoder;
    import java.util.*;
    import javax.crypto.*;
    import com.sun.crypto.provider.SunJCE;
    After compiling the file, registering with javareg.exe, and copying it to \winnt\trustlib\, I attempt to view the .ASP page and get the following:
    Error Type:
    Server object, ASP 0177 (0x80040111)
    ClassFactory cannot supply requested class
    I believe I need to reference various .JAR files, either when I use javareg.exe or within the .ASP.
    Can anyone offer any insight into what the ClassFactory might be expecting?
    Thanks,
    Joel

    I am repeatedly getting the following error:
    Server object, ASP 0177 (0x80040111)
    ClassFactory cannot supply requested class
    I have checked my classpaths, and the paths do include the one that the class does reside on. In a reply posted by somebody earlier it was mentioned to check whether it was on the ASP classpath. What is this classpath?
    Thanks for your help. This is very frustrating as it should be working!

  • How can i create java.awt.Image Serialized To write it in A socket

    I want to write the Object of Image in Socket ...
    What i want to do is I am caturing A screen Shot of one Client Side and Want display it on the Other Client End..

    Since the image is transmitted in byte[], no need to use Ojbect write or read
    I am doing the same thing but i am not able recreate
    the Image at reading the Obj from the Sockets
    BufferedImage bImage= robot.createScreenCapture(new
    Rectangle(600,800));
    img = this.createImage(bImage.getSource());
    PixelGrabber pix = new PixelGrabber(img
    ,0,0,-1,-1,true);
    pix.startGrabbing();
    pix.imageComplete(pix.status());
    obj.writeObject(pix.getPixels());
    Object obj = objStream.readObject();
    int []pix =(int [])obj;
    Image Reimgage = createImage(new
    MemoryImageSource(600,800,pix,600,800));
    // When i recreate this Image ... it does not Show me
    any thing..

  • Help Needed in Creating Java Class and Java Stored Procedures

    Hi,
    Can anyone tell how can i create Java Class, Java Source and Java Resource in Oracle Database.
    I have seen the Documents. But i couldn't able to understand it correctly.
    I will be helpful when i get some Examples for creating a Java Class, Java Source and Stored Procedures with Java with details.
    Is that possible to Create a Java class in the oracle Database itself ?.
    Where are the files located for the existing Java Class ?..
    Help Needed Please.
    Thanks,
    Murali.v

    Hi Murali,
    Heres a thread which discussed uploading java source file instead of runnable code on to the database, which might be helpful :
    Configure deployment to a database to upload the java file instead of class
    The files for the java class you created in JDev project is located in the myworks folder in jdev, eg, <jdev_home>\jdev\mywork\Application1\Project1\src\project1
    Hope this helps,
    Sunil..

  • Can't create JVM from JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

    I'm new in using JNI. When i compile the C program that invoke the JAVA program, everthing goes fine. I can obtain the the "exe" from the compilation.
    But when i run the "exe" file it display "can't create Java VM". Here is the part of the code in C program:
    ........//other code
    JNI_VERSION_1_2
    JavaVMInitArgs vm_args;
    JavaVMOption options[1];
    options[0].optionString =
    "-Djava.class.path=" USER_CLASSPATH;
    vm_args.version = 0x00010002;
    vm_args.options = options;
    vm_args.nOptions = 1;
    vm_args.ignoreUnrecognized = JNI_TRUE;
    /* Create the Java VM */
    res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (res < 0) {
    fprintf(stderr, "Can't create Java VM\n");
    exit(1);
    .......//other code
    I'm using JDK1.3, and windows ME.
    Can anyone tell me the problem?

    I think you need to get the address of the create function from the jvm.dll at runtime and call that: this works for me:
         HINSTANCE handle;
         JavaVMOption options[5];
         char JREHome[MAX_PATH];
         char JVMPath[MAX_PATH];                                        
         char classpathOption[MAX_PATH];
         char librarypathOption[MAX_PATH];
         if(!GetPublicJREHome(JREHome, MAX_PATH))
              LogError("Could not locate JRE");
              abort();
         strcpy(JVMPath,JREHome);
         strcat(JVMPath,"\\bin\\client\\jvm.dll");
        if ((handle=LoadLibrary(JVMPath))==0)
              LogError("Error loading: %s", JVMPath);
              abort();
        CreateJavaVM_t pfnCreateJavaVM=(CreateJavaVM_t)GetProcAddress(handle,"JNI_CreateJavaVM");
        if (pfnCreateJavaVM==0)
              LogError("Error: can't find JNI interfaces in: %s",JVMPath);
              abort();
         strcpy(classpathOption,"-Djava.class.path=");
         strcat(classpathOption,dir);
         strcat(classpathOption,";");
         strcat(classpathOption,JREHome);
         strcat(classpathOption,"\\lib");
         strcat(classpathOption,";");
         strcat(classpathOption,JREHome);
         strcat(classpathOption,"\\lib\\comm.jar");
         strcpy(librarypathOption,"-Djava.library.path=");
         strcat(librarypathOption,JREHome);
         strcat(librarypathOption,"\\lib");
         OutputDebugString("classpath option=");
         OutputDebugString(classpathOption);
         OutputDebugString("\n");
         OutputDebugString("librarypath option=");
         OutputDebugString(librarypathOption);
         OutputDebugString("\n");
         options[0].optionString=classpathOption;     
         options[1].optionString=librarypathOption;     
         options[2].optionString="vfprintf";
         options[2].extraInfo=_vfprintf_;
         options[3].optionString="exit";
         options[3].extraInfo=_exit_;
         options[4].optionString="abort";
         options[4].extraInfo=_abort_;
        vmArgs.version  = JNI_VERSION_1_2;
        vmArgs.nOptions = 5;
        vmArgs.options  = options;
        vmArgs.ignoreUnrecognized = false;
        if(pfnCreateJavaVM(&jvm,(void**)&env, &vmArgs)!=0)
              LogError("Could not create VM");
              abort();
         }

  • Cant create Java VM

    When i try to start Sun Java Studio Creator, it gives me an error saying "Can't create Java VM" on Windows 2000 Professional platform. Can you please let me know what is the problem?
    Thanks

    I had JDK 142_03 installed. I couldnt find jv.dll in winnt/system32.
    I had "cant create Java VM" problem all of a sudden without any changes to my JDK or path settings. It was working fine before and gave me this problem all of a sudden when i tried to restart the IDE. However, i did uninstall and reinstall Creator.
    The Tutorial link in Welcome window doesnt send the URL to browser if i click the same more than once. (It sends the URL for the first time the IDE starts)
    Two more questions :
    1. What is the reason behind the sample web services in Server Navigator getting disappeared in the IDE all of a sudden? (happened few times for me)
    2. The Deployment server fails to start so many times from the IDE and when i try to start using "Start default server". (most of the times log shows me JMS Exceptions). How about Add deployment server features??
    [#|2004-06-07T15:47:19.691+0530|WARNING|sun-appserver-pe8.0.0_01|javax.enterprise.system.core|_ThreadID=10;|CORE5061: Exception :
    com.sun.appserv.server.ServerLifecycleException: [C4003]: Error occurred on connection creation [127.0.0.1:7676]. - cause: java.net.ConnectException: Connection refused: connect
         at com.sun.enterprise.jms.JmsProviderLifecycle.checkProviderStartup(JmsProviderLifecycle.java:415)
         at com.sun.enterprise.jms.JmsProviderLifecycle.onShutdown(JmsProviderLifecycle.java:433)
         at com.sun.enterprise.server.ApplicationServer.onShutdown(ApplicationServer.java:400)
         at com.sun.enterprise.server.PEMain.run(PEMain.java:233)
         at com.sun.enterprise.server.PEMain.main(PEMain.java:172)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.apache.commons.launcher.ChildMain.run(ChildMain.java:269)
    Caused by: com.sun.messaging.jms.JMSException: [C4003]: Error occurred on connection creation [127.0.0.1:7676]. - cause: java.net.ConnectException: Connection refused: connect
         at com.sun.messaging.jmq.jmsclient.ExceptionHandler.getJMSConnectException(ExceptionHandler.java:233)
         at com.sun.messaging.jmq.jmsclient.ExceptionHandler.handleConnectException(ExceptionHandler.java:180)
         at com.sun.messaging.jmq.jmsclient.PortMapperClient.readBrokerPorts(PortMapperClient.java:172)
         at com.sun.messaging.jmq.jmsclient.PortMapperClient.init(PortMapperClient.java:97)
         at com.sun.messaging.jmq.jmsclient.PortMapperClient.<init>(PortMapperClient.java:50)
         at com.sun.messaging.jmq.jmsclient.protocol.tcp.TCPConnectionHandler.<init>(TCPConnectionHandler.java:53)
         at com.sun.messaging.jmq.jmsclient.protocol.tcp.TCPStreamHandler.openConnection(TCPStreamHandler.java:102)
         at com.sun.messaging.jmq.jmsclient.ConnectionInitiator.createConnectionOld(ConnectionInitiator.java:271)
         at com.sun.messaging.jmq.jmsclient.ConnectionInitiator.createConnection(ConnectionInitiator.java:107)
         at com.sun.messaging.jmq.jmsclient.ConnectionInitiator.createConnection(ConnectionInitiator.java:92)
         at com.sun.messaging.jmq.jmsclient.ProtocolHandler.init(ProtocolHandler.java:562)
         at com.sun.messaging.jmq.jmsclient.ProtocolHandler.<init>(ProtocolHandler.java:1102)
         at com.sun.messaging.jmq.jmsclient.ConnectionImpl.openConnection(ConnectionImpl.java:1741)
         at com.sun.messaging.jmq.jmsclient.ConnectionImpl.init(ConnectionImpl.java:588)
         at com.sun.messaging.jmq.jmsclient.ConnectionImpl.<init>(ConnectionImpl.java:274)
         at com.sun.messaging.jmq.jmsclient.UnifiedConnectionImpl.<init>(UnifiedConnectionImpl.java:33)
         at com.sun.messaging.jmq.jmsclient.QueueConnectionImpl.<init>(QueueConnectionImpl.java:32)
         at com.sun.messaging.ConnectionFactory.createQueueConnection(ConnectionFactory.java:72)
         at com.sun.messaging.jmq.admin.jmsspi.JMSAdminImpl.pingProvider(JMSAdminImpl.java:734)
         at com.sun.enterprise.jms.JmsProviderLifecycle.waitForJmsProvider(JmsProviderLifecycle.java:324)
         at com.sun.enterprise.jms.JmsProviderLifecycle.checkProviderStartup(JmsProviderLifecycle.java:384)
         ... 9 more
    Caused by: java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
         at java.net.Socket.connect(Socket.java:452)
         at java.net.Socket.connect(Socket.java:402)
         at java.net.Socket.<init>(Socket.java:309)
         at java.net.Socket.<init>(Socket.java:124)
         at com.sun.messaging.jmq.jmsclient.PortMapperClient.readBrokerPorts(PortMapperClient.java:152)
         ... 27 more
    |#]
    Thanks

  • I can't create the JVM using JNI_CreateJavaVM

    I'm very much new to the JNI on Windows 2000. When I compiled the example invoke.c program that invoke the java program, it generated invoke.exe file. but when I run the this executable file, it always shows "Can't create Java VM". I tried other samples, but the result is same. I am also sure that I copy jvm.dll from jdk1.2.2\jre\bin\classic to the same folder with invoke.exe file.
    I use JDK1.2.2 and Microsoft Visual Studio 6.0 C++. Please let me know what's going on about the following program?
    #include <jni.h>
    #define USER_CLASSPATH "." /* where Prog.class is */
    int main() {
    JNIEnv *env;
    JavaVM *jvm;
    jint res;
    jclass cls;
    jmethodID mid;
    jstring jstr;
    jclass stringClass;
    jobjectArray args;
    JavaVMInitArgs vm_args;
    JavaVMOption options[1];
    options[0].optionString =
    "-Djava.class.path=" USER_CLASSPATH;
    vm_args.version = JNI_VERSION_1_2;
    vm_args.options = options;
    vm_args.nOptions = 1;
    vm_args.ignoreUnrecognized = JNI_TRUE;
    /* Create the Java VM */
    res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (res < 0) {
    fprintf(stderr, "Can't create Java VM\n");
    exit(1);
    cls = (*env)->FindClass(env, "Prog");
    if (cls == 0) {
    goto destroy;
    mid = (*env)->GetStaticMethodID(env, cls, "main",
    "([Ljava/lang/String;)V");
    if (mid == 0) {
    goto destroy;
    jstr = (*env)->NewStringUTF(env, " from C!");
    if (jstr == 0) {
    goto destroy;
    stringClass = (*env)->FindClass(env, "java/lang/String");
    args = (*env)->NewObjectArray(env, 1, stringClass, jstr);
    if (args == 0) {
    goto destroy;
    (*env)->CallStaticVoidMethod(env, cls, mid, args);
    destroy:
    if ((*env)->ExceptionOccurred(env)) {
    (*env)->ExceptionDescribe(env);
    (*jvm)->DestroyJavaVM(jvm);
    return 0;

    Are you sure you are using the correct jvm.dll?
    Remove any jvm.dll files you copied to your .exe directory and set your Path so that is using the jdk1.3 hotspot jvm.dll.
    You said you were using windows so the default location of your jdk is C:\jdk1.3.1 To set your path to the correct location use this command:
    set Path=%Path%;C:\jdk1.3.1\jre\bin\hotspot
    If your jdk is installed somewhere else replace C:\jdk1.3.1 with the root path to your jdk.
    If that doesn't work there may be a conflict with the way you compiled the program.

  • How can I install java framework manually?

    After deleting java folders how can I create java framework manually.

    macnewuser13 wrote:
    I am not worried about security issue.
    I just want to run Java Applet in any of my browsers.
    Our Application is should work in browser as an applet that is the first thing.
    Security is second issue.
    So please tell me which is the mininum Java Version I can install in Mac OS to avoid this security checking.
    If choose Snow Leopard also same issue it will have?
    I want to run Java Applet some how in any of Mac OS with any Java version above 1.6.0
    The Security issue is over (for now, but I'm confident it will be back).  You can safely update to either Java SE 7u15 at Oracle or Java for Mac OS X 10.6 Update 13 from Apple using Software Update or both. You can switch the browser plugin back and forth between the two by following these instructions that baltwo mentioned before.
    All the experts are telling us that Java for the browser is dead, so if you are involved in the development of such Applets, you need to find a different solution or a new job.

  • How can I create a java.awt.Image from ...

    Hi all,
    How can I create a java.awt.Image from a drawing on a JPanel?
    Thanks.

    JPanel p;
    BufferedImage image =
        new BufferedImage(p.getWidth(), p.getHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    p.paint(g);
    g.dispose();

  • Java.sql.SQLException: can't create statement from closed connection

    java.sql.SQLException: can't create statement from closed connection.
    at com.caucho.sql.QPooledConnectionImpl.prepareStatement(QPooledConnecti onImpl.java:411)
    I am getting this error with my JSP's, i am running on Resin on Win2k, and MySql as backend.
    Has anyone else also faced this issue ?
    Looking for someone to help me to solve this issue.
    rc

    Looking for someone to help me to solve this issue.Maybe you are closing the connections. You might want to verify that you are not doing that. Or if you are that that is the correct way to return the connection to the pool.
    Or you could have stale connections. Some databases will time out connections if the connection is no used in a while. (This is a good thing.) But this means connection pools must do something with connections that are not used for a while. The pools usually have a configuration option(s) which allows you to set up a keep alive message which keeps the database from closing the connection.

  • What type of files can we create in Java?

    In general what type of files can we create in Java?
    For example, we can create .dat and .txt files as follows:
    DataOutputStream ostream;
    ostream = new DataOutputStream(new FileOutputStream("myfile1.dat"));
    or
    ostream = new DataOutputStream(new FileOutputStream("myfile2.txt"));
    Can we create ASCII?
    Thank you in advance for your answers.

    In general what type of files can we create in Java?You know that a file is nothing more than a series of ones and zeros, with eight of those bundled together as something called a byte. What they actually mean is what you make them to mean. Short: you can write and read any file type you like, but doing that semantically correct it is your responsibility.

  • Can we create installer for  Java projects ?

    when we create any desktop application using swing. Can we create installer for that application that will include all the files, which is required to run that application including data base. Data base is Mysql and in some case it might be MS Access.
    We can create the jar files for this and deploy. But other then this ...
    Is it possible to create ?? If anybody have idea then plz give me steps how to do this ??
    welcome in advance for reply...

    MukeshSinghRathaur wrote:
    when we create any desktop application using swing. Use [Java Web Start|http://www.java.com/en/download/faq/java_webstart.xml] *(<- link)*
    ..If anybody have idea then plz give me steps how to do this ??Please take the effort to type all 6 letter of the word 'please'. Also - one '?' indicates a question, whereas 2 or more often indicates a bozo.
    Do some research, ask a specific question. These forums are not designed as a 'help-desk' where people will hold your hand and tutor you as to how to do things.

  • Can I create a cert with the Java API only?

    I'm building a client/server app that will use SSL and client certs for authenticating the client to the server. I'd like for each user to be able to create a keypair and an associated self-signed cert that they can provide to the server through some other means, to be included in the server's trust store.
    I know how to generate a key pair with an associated self-signed cert via keytool, but I'd prefer to do it directly with the Java APIs. From looking at the Javadocs, I can see how to generate a keypair and how to generate a cert object using an encoded representation of the cert ( e.g. java.security.cert.CertificateFactory.generateCertififcate() ).
    But how can I create this encoded representation of the certificate that I need to provide to generateCertificate()? I could do it with keytool and export the cert to a file, but is there no Java API that can accomplish the same thing?
    I want to avoid having the user use keytool. Perhaps I can execute the appropriate keytool command from the java code, using Runtime.exec(), but again a pure java API approach would be better. Is there a way to do this all with Java? If not, is executing keytool via Runtime.exec() the best approach?

    There is no solution available with the JDK. It's rather deficient wrt certificate management, as java.security.cert.CertificateFactory is a factory that only deals in re-treads. That is, it doesn't really create certs. Rather it converts a DER encoded byte stream into a Java Certificate object.
    I found two ways to create a certificate from scratch. The first one is an all Java implementation of what keytool does. The second is to use Runtime.exec(), which you don't want to do.
    1. Use BouncyCastle, a free open source cryptography library that you can find here: http://www.bouncycastle.org/ There are examples in the documentation that show you how to do just about anything you want to do. I chose not to use it, because my need was satisfied with a lighter approach, and I didn't want to add a dependency unnecessarily. Also Bouncy Castle requires you to use a distinct version with each version of the JDK. So if I wanted my app to work with JDK 1.4 or later, I would have to actually create three different versions, each bundled with the version of BouncyCastle that matches the version of the target JDK.
    2. I created my cert by using Runtime.exec() to invoke the keytool program, which you say you don't want to do. This seemed like a hack to me, so I tried to avoid it; but actually I think it was the better choice for me, and I've been happy with how it works. It may have some backward compatibility issues. I tested it on Windows XP and Mac 10.4.9 with JDK 1.6. Some keytool arguments changed with JDK versions, but I think they maintained backward compatibility. I haven't checked it, and I don't know if I'm using the later or earlier version of the keytool arguments.
    Here's my code.
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import javax.security.auth.x500.X500Principal;
    import javax.swing.JOptionPane;
    public class CreateCertDemo {
         private static void createKey() throws IOException,
          KeyStoreException, NoSuchAlgorithmException, CertificateException{
         X500Principal principal;
         String storeName = ".keystore";
         String alias = "keyAlias";
         principal = PrincipalInfo.getInstance().getPrincipal();
         String validity = "10000";
         String[] cmd = new String[]{ "keytool", "-genKey", "-alias", alias, "-keyalg", "RSA",
            "-sigalg", "SHA256WithRSA", "-dname", principal.getName(), "-validity",
            validity, "-keypass", "keyPassword", "-keystore",
            storeName, "-storepass", "storePassword"};
         int result = doExecCommand(cmd);
         if (result != 0){
              String msg = "An error occured while trying to generate\n" +
                                  "the private key. The error code returned by\n" +
                                  "the keytool command was " + result + ".";
              JOptionPane.showMessageDialog(null, msg, "Key Generation Error", JOptionPane.WARNING_MESSAGE);
         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
         ks.load(new FileInputStream(storeName), "storePassword".toCharArray());
            //return ks from the method if needed
    public static int doExecCommand(String[] cmd) throws IOException{
              Runtime r = Runtime.getRuntime();
              Process p = null;
              p = r.exec(cmd);
              FileOutputStream outFos = null;
              FileOutputStream errFos = null;
              File out = new File("keytool_exe.out");
              out.createNewFile();
              File err = new File("keytool_exe.err");
              err.createNewFile();
              outFos = new FileOutputStream(out);
              errFos = new FileOutputStream(err);
              StreamSink outSink = new StreamSink(p.getInputStream(),"Output", outFos );
              StreamSink errSink = new StreamSink(p.getErrorStream(),"Error", errFos );
              outSink.start();
              errSink.start();
              int exitVal = 0;;
              try {
                   exitVal = p.waitFor();
              } catch (InterruptedException e) {
                   return -100;
              System.out.println (exitVal==0 ?  "certificate created" :
                   "A problem occured during certificate creation");
              outFos.flush();
              outFos.close();
              errFos.flush();
              errFos.close();
              out.delete();
              err.delete();
              return exitVal;
         public static void main (String[] args) throws
              KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
              createKey();
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    //Adapted from Mike Daconta's StreamGobbler at
    //http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
    public class StreamSink extends Thread
        InputStream is;
        String type;
        OutputStream os;
        public StreamSink(InputStream is, String type)
            this(is, type, null);
        public StreamSink(InputStream is, String type, OutputStream redirect)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    System.out.println(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.security.auth.x500.X500Principal;
    public class PrincipalInfo {
         private static String defInfoString = "CN=Name, O=Organization";
         //make it a singleton.
         private static class PrincipalInfoHolder{
              private static PrincipalInfo instance = new PrincipalInfo();
         public static PrincipalInfo getInstance(){
              return PrincipalInfoHolder.instance;
         private PrincipalInfo(){
         public X500Principal getPrincipal(){
              String fileName = "principal.der";
              File file = new File(fileName);
              if (file.exists()){
                   try {
                        return new X500Principal(new FileInputStream(file));
                   } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
              }else{
                   return new X500Principal(defInfoString);
         public void savePrincipal(X500Principal p) throws IOException{
              FileOutputStream fos = new FileOutputStream("principal.der");
              fos.write(p.getEncoded());
              fos.close();
    }Message was edited by:
    MidnightJava
    Message was edited by:
    MidnightJava

  • Can I create Oracle Database using Java ???

    HI ...
    Can I create a Database using Java... ? If yes can any one tell me how ? I mean provide some codeing help... ???

    If you mean a table yes, since the create table statement is exactly that, an SQL statement, if you mean an SID then I would have to say (AFAIK) no.

Maybe you are looking for