JOI_RetCode JavaObjectInterfaceTM::initJVM()
{
  jint result;

  if ((_tlp_jenv != 0) && (_tlv_jenv_set)) {
    return JOI_OK;
  }

  if (jvm_ == NULL)
  {
    jsize jvm_count = 0;
    // Is there an existing JVM already created?
    result = JNI_GetCreatedJavaVMs (&jvm_, 1, &jvm_count);
    if (result != JNI_OK)
      return JOI_ERROR_CHECK_JVM;      
      
    if (jvm_count == 0)
    {
      // No - create a new one.
      result = createJVM();
      if (result != JNI_OK)
        return JOI_ERROR_CREATE_JVM;
        
      needToDetach_ = false;
        
      return JOI_OK;
    }
  }
  
  // We found a JVM, can we use it?
  result = jvm_->GetEnv((void**) &_tlp_jenv, JNI_VERSION_1_6);
  switch (result)
  {
    case JNI_OK:
      break;
    
    case JNI_EDETACHED:
      fprintf(stderr,"initJVM: Detached, Try 2 attach\n");
      result = jvm_->AttachCurrentThread((void**) &_tlp_jenv, NULL);   
      if (result != JNI_OK)
      {
        fprintf(stderr,"initJVM: Error in attaching\n");
        return JOI_ERROR_ATTACH_JVM;
      }
      
      needToDetach_ = true;
      break;
       
    case JNI_EVERSION:
      return JOI_ERROR_JVM_VERSION;
      break;
      
    default:
      return JOI_ERROR_ATTACH_JVM;
      break;
  }

  _tlv_jenv_set = true;
  return JOI_OK;
}
示例#2
0
jint nativeRouting(const char* obfPath,
    jdouble slat, jdouble slon, jdouble elat, jdouble elon) {
  JNIEnv* e = createJVM();
  print("JVM started %d",  e->GetVersion());

  jclass objclass = e->FindClass("java/lang/Object");  
  if(checkException(e)) return -1;
  print("Object class found");


  jclass c = e->FindClass("net/osmand/router/TestRouting");
  if(checkException(e)) return -1;

  jmethodID m = e->GetStaticMethodID(c, "calculateRoute", "(Ljava/lang/String;DDDD)V");
  if(checkException(e)) return -1;

  jstring obfstr = createString(e, obfPath);
  e->CallStaticVoidMethod(c, m, obfstr, slat, slon, elat, elon);
  if(checkException(e)) return -1;
  // vm->DestroyJavaVM();
  // globalE = NULL;
  // vm = NULL;
  return 0;

}
示例#3
0
/**
 * Initializes the IO subsystem.
 *
 * @param  classPath   the class path with which to start the embedded JVM
 * @param  args        extra arguments to pass to the embedded JVM
 * @param  argc        the number of extra arguments in 'args
 */
void CIO_initialize(char *classPath, char** args, int argc) {
    /*
     * Create the embedded Java VM now
     */
    jint createJVM(JavaVM **, void **env, void *args);
    JavaVMInitArgs vm_args;
    JavaVMOption   options[MAX_JVM_ARGS + 1];

    char *buf = (char *)malloc(strlen("-Djava.class.path=")+strlen(classPath)+strlen(":hosted-support/classes")+1);
    sprintf(buf, "-Djava.class.path=%s%chosted-support%cclasses", classPath, (char)pathSeparatorChar, (char)fileSeparatorChar);

    // A version 1.4 Java VM is required
    vm_args.version = JNI_VERSION_1_4;

    vm_args.options  = options;
    options[0].optionString = buf;
    vm_args.nOptions = 1;

    /*
     * Disable the JIT as it has stability problems on at least one platform (Solaris)
     * and the slow down is not noticeable anyway.
     * 
     * Try it on again. It makes a 20% difference with the suite creator.
     * if there is trouble, users can disable from command line:
     * -J-Djava.compiler=NONE
     */
            /*  options[vm_args.nOptions++].optionString = "-Djava.compiler=NONE";*/

    /*
     * Add command line oprtions.
     */
    while (argc-- != 0) {
        options[vm_args.nOptions++].optionString = *args;
        args++;
    }
/*
{
int i;
fprintf(stderr, "Starting embedded JVM with options \"");
for (i = 0; i != vm_args.nOptions; i++) {
    fprintf(stderr, "%s ", vm_args.options[i].optionString);
}
fprintf(stderr, "\"\n");
}
*/
    createJVM(&jvm, (void**)&JNI_env, &vm_args);

    if (JNI_env != null) {
        channelIO_clazz = (*JNI_env)->FindClass(JNI_env, "com/sun/squawk/vm/ChannelIO");
        jni_assume(channelIO_clazz != null, "Can't find com.sun.squawk.vm.ChannelIO");

        channelIO_execute = (*JNI_env)->GetStaticMethodID(JNI_env, channelIO_clazz, "execute", "(IIIIIIIIILjava/lang/Object;Ljava/lang/Object;)I");
        jni_assume(channelIO_execute != null, "Couldn't find method: channelIO_execute()");

    } else {
        fprintf(stderr, "Warning: Error creating Java VM -- I/O subsystem will be disabled\n");
    }
}
示例#4
0
文件: java.cpp 项目: Davi09/node-java
v8::Local<v8::Value> Java::ensureJvm() {
  if(!m_jvm) {
    v8::Local<v8::Value> result = createJVM(&this->m_jvm, &this->m_env);
    assert(result->IsNull());
    return result;
  }

  return Nan::Null();
}
示例#5
0
int main(int argc, char* argv[])
{
	SERVICE_TABLE_ENTRY dispatchTable[] = {
        {SERVICENAME, serviceMain },
        {NULL, NULL }
    };
	if(argc > 1) {
		if(_tcsicmp(_T("-run"), argv[1]) == 0) {
			bStandAlone = TRUE;
			fillCP();
			if (argc > 2) {
				if (*(argv[2]+strlen(argv[2])-1) == '\\')
					*(argv[2]+strlen(argv[2])-1) = 0;
				installDir = _strdup(argv[2]);
			} 				

			if (createJVM()) {
				run();
			}
			cleanup();
		} else if(_tcsicmp(_T("-install"), argv[1]) == 0 || _tcsicmp(_T("-installa"), argv[1]) == 0) {
			// TODO use strstr
			// if (strstr(argv[1], _T("-install")) == argv[1])
			if (argc < 3) {
				usage();
				return -1;
			}
			scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
			installService(argc<5?SERVICENAME:argv[4], argc<6?SERVICENAME:argv[5],
				argc<7?argv[0]:argv[6], NULL, 0, argv[2], argc<4?NULL:argv[3], argc<8?NULL:argsToLine(argc-7, argv+7),
				_tcsicmp(_T("-installa"), argv[1]) == 0?"rogatkin/app/Main":NULL);
			CloseServiceHandle(scm);
		} else if(_tcsicmp(_T("-uninstall"), argv[1]) == 0) {
			scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
			unistallService(argc>2?argv[2]:SERVICENAME);
			CloseServiceHandle(scm);
		} else if(_tcsicmp(_T("-help"), argv[1]) == 0)
			usage();
	} else {
		if (!StartServiceCtrlDispatcher(dispatchTable)) {
			logServiceMessage(_T("StartServiceCtrlDispatcher failed."), EVENTLOG_ERROR_TYPE);
		}
	}

	return 0;
}
示例#6
0
/* This is called when the service control manager starts the service.
* The service stops when this method returns so there is a wait on an
* event at the end of this method.
*/
void CALLBACK serviceMain(DWORD dwArgc, LPTSTR *lpszArgv) {
	if (!fillCP()) {
        cleanup();
		return;
    }

	if (!createJVM()) {
        cleanup();
		return;
    }
	
    serviceStatusHandle = RegisterServiceCtrlHandler(
		TEXT(SERVICENAME),
		(LPHANDLER_FUNCTION)serviceCtrl);
	
    if(!serviceStatusHandle) {
        cleanup();
		return;
    }
	
    serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    serviceStatus.dwServiceSpecificExitCode = 0;
	
    if(!sendStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 1, SVC_START_TIMEOUT)) {
        cleanup();
		return;
    }
    if(!sendStatusToSCMgr(SERVICE_RUNNING, NO_ERROR, 0, 0)) {
        cleanup();
		return;
    }
	run();
    if(serviceStatusHandle != 0) {
        sendStatusToSCMgr(SERVICE_STOPPED, NO_ERROR, 0, 0);
    }
    return;
}
JOI_RetCode JavaObjectInterface::initJVM()
{
  jint result;
  if (jvm_ == NULL)
  {
    jsize jvm_count = 0;
    // Is there an existing JVM already created?
    result = JNI_GetCreatedJavaVMs (&jvm_, 1, &jvm_count);
    if (result != JNI_OK)
    {
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_CHECK_JVM));
      return JOI_ERROR_CHECK_JVM;      
    }
    if (jvm_count == 0)
    {
      // No - create a new one.
      result = createJVM();
      if (result != JNI_OK)
      {
         GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_CHECK_JVM));
         return JOI_ERROR_CREATE_JVM;
      }
        
      needToDetach_ = false;
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Created a new JVM.");
    }
    char *jniHandleCapacityStr =  getenv("TRAF_JNIHANDLE_CAPACITY");
    if (jniHandleCapacityStr != NULL)
       jniHandleCapacity_ = atoi(jniHandleCapacityStr);
    if (jniHandleCapacity_ == 0)
        jniHandleCapacity_ = TRAF_DEFAULT_JNIHANDLE_CAPACITY;
  }
  if (jenv_  == NULL)
  {
  // We found a JVM, can we use it?
  result = jvm_->GetEnv((void**) &jenv_, JNI_VERSION_1_6);
  switch (result)
  {
    case JNI_OK:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attached to an existing JVM.");
      break;
    
    case JNI_EDETACHED:
      result = jvm_->AttachCurrentThread((void**) &jenv_, NULL);   
      if (result != JNI_OK)
        return JOI_ERROR_ATTACH_JVM;
      
      needToDetach_ = true;
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attached to an existing JVM from another thread.");
      break;
       
    case JNI_EVERSION:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Attaching to a JVM of the wrong version.");
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_JVM_VERSION));
      return JOI_ERROR_JVM_VERSION;
      break;
      
    default:
      QRLogger::log(CAT_SQL_HDFS_JNI_TOP, LL_DEBUG, "Unknown error Attaching to an existing JVM.");
      GetCliGlobals()->setJniErrorStr(getErrorText(JOI_ERROR_ATTACH_JVM));
      return JOI_ERROR_ATTACH_JVM;
      break;
  }
  }
  jclass lJavaClass;
  if (gThrowableClass == NULL)
  {
     lJavaClass = jenv_->FindClass("java/lang/Throwable");
     if (lJavaClass != NULL)
     {
        gThrowableClass  = (jclass)jenv_->NewGlobalRef(lJavaClass);
        jenv_->DeleteLocalRef(lJavaClass);
        gGetStackTraceMethodID  = jenv_->GetMethodID(gThrowableClass,
                      "getStackTrace",
                      "()[Ljava/lang/StackTraceElement;");
        gThrowableToStringMethodID = jenv_->GetMethodID(gThrowableClass,
                      "toString",
                      "()Ljava/lang/String;");
     }
  }
  if (gStackTraceClass == NULL)
  {
     lJavaClass =  (jclass)jenv_->FindClass("java/lang/StackTraceElement");
     if (lJavaClass != NULL)
     {
        gStackTraceClass = (jclass)jenv_->NewGlobalRef(lJavaClass);
        jenv_->DeleteLocalRef(lJavaClass);
        gStackFrameToStringMethodID  = jenv_->GetMethodID(gStackTraceClass,
                      "toString",
                      "()Ljava/lang/String;");
     }
  }                  
  return JOI_OK;
}
示例#8
0
/**
 * Starts the Java virual machine.
 *
 * @return true if successful, false otherwise
 */
int startJVM()
{
	JavaVMInitArgs vm_args;
	JavaVMOption *options;
	jint res;
	JNIEnv *env;
	jclass clazz;
	jmethodID method;

#ifdef WIN32
	HINSTANCE hVM;
#else
	void *libVM;
#endif

	if (maxHeap == NULL)
	{
	    options = (JavaVMOption *) malloc(sizeof(JavaVMOption) * 2);
	}
	else
	{
		options = (JavaVMOption *) malloc(sizeof(JavaVMOption) * 3);
	}

	/* Set up Java options. */
	options[0].optionString = classPath; /* Sets the Java classpath. */
	options[1].optionString = "-Xrs";    /* Set Java to not use a signal handler, (we use our own). */
	if (maxHeap != NULL)
	{
		options[2].optionString = maxHeap;
	}

	vm_args.options = options;
	vm_args.nOptions = maxHeap == NULL ? 2 : 3;
	vm_args.ignoreUnrecognized = JNI_FALSE;
	vm_args.version = JNI_VERSION_1_4;

	/* Load the JVM library and find the JNI_CreateJavaVM function. */
#ifdef WIN32
	SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
	hVM = LoadLibrary(jvmSo);
	if (hVM == NULL)
	{
		char *pch = jvmSo, *bch = NULL, *javaBin;

		/* Add the Java installation bin directory to the DLL search path so msvcr71.dll
		 * can be loaded when java.dll is loaded. See Java bug #6509291. */
		while ((pch = strstr(pch, "bin")) != NULL) bch = pch++;
		if (bch == NULL)
		{
			logMessage("ERROR: Unable to find 'bin/' directory in the Java installaion directory. This is "
				       "most likely a bug caused by a change in the Java installation layout. Please "
					   "report this with the Java version in use.");
			return 0;
		}

		javaBin = (char *) malloc(bch - jvmSo + 5);
		memset(javaBin, 0, bch - jvmSo + 5);
		strncpy(javaBin, jvmSo, bch - jvmSo);
		strcat(javaBin, "bin");

		logMessage("NORMAL: Adding '%s' to the DLL search path.\n");
		SetDllDirectory(javaBin);
		hVM = LoadLibraryEx(jvmSo, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
		if (hVM == NULL)
		{
			logMessage("ERROR: Unable to load library %s, error code %i.\n", jvmSo, GetLastError());
			return 0;
		}
	}
	createJVM = (CreateJavaVM)GetProcAddress(hVM, "JNI_CreateJavaVM");
#else
	libVM = dlopen(jvmSo, RTLD_LAZY);
	if (libVM == NULL)
	{
		logMessage("ERROR: Unable to load library %s.\n", jvmSo);
		perror("Error loading JVM library");
		return 0;
	}
	createJVM = (CreateJavaVM)dlsym(libVM, "JNI_CreateJavaVM");
#endif

	/* Create the JVM. */
	res = createJVM(&vm, (void **)&env, &vm_args);
	if (res < 0)
	{
		logMessage("ERROR: Failed to create JVM, response code is %i.\n", res);
		return 0;
	}
	logMessage("NORMAL: Successfully created Java virtual machine.\n");

	/* Find the start up class. */
	if ((clazz = (*env)->FindClass(env, CLASS_NAME)) == NULL)
	{
		logMessage("ERROR: Unable to find class %s.\n", CLASS_NAME);
		return 0;
	}

	/* Find start up method and invoke it. */
	if ((method = (*env)->GetStaticMethodID(env, clazz, STARTUP_METHOD, "()V")) == NULL)
	{
		logMessage("BUG: Unable to find method %s in class %s.\n", STARTUP_METHOD, CLASS_NAME);
		return 0;
	}
	(*env)->CallStaticVoidMethod(env, clazz, method, NULL);

	if ((*env)->ExceptionCheck(env))
	{
		logMessage("BUG: Exception thrown starting up rig client (called method %s on %s).\n", STARTUP_METHOD, CLASS_NAME);
		return 0;
	}

	return 1;
}