summaryrefslogtreecommitdiff
path: root/db/javajs.cpp
blob: 34156707d9f6fc73b838534a9039458aa19242ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// java.cpp

/**
*    Copyright (C) 2008 10gen Inc.
*  
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*  
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*  
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "stdafx.h"
#include "javajs.h"
#include <iostream>
#include <map>
#include <list>

using namespace boost::filesystem;          

//#define JNI_DEBUG 1

#ifdef JNI_DEBUG
#undef JNI_DEBUG
#define JNI_DEBUG(x) cerr << x << endl
#else
#undef JNI_DEBUG
#define JNI_DEBUG(x) 
#endif



#ifdef J_USE_OBJ
#include "jsobj.h"
#pragma message("warning: including jsobj.h")
#endif

#include "../grid/message.h"
#include "db.h"

using namespace std;

#if defined(_WIN32)
/* [dm] this being undefined without us adding it here means there is 
        no tss cleanup on windows for boost lib?
        we don't care for now esp on windows only

		the boost source says:

		  This function's sole purpose is to cause a link error in cases where
		  automatic tss cleanup is not implemented by Boost.Threads as a
		  reminder that user code is responsible for calling the necessary
		  functions at the appropriate times (and for implementing an a
		  tss_cleanup_implemented() function to eliminate the linker's
		  missing symbol error).

		  If Boost.Threads later implements automatic tss cleanup in cases
		  where it currently doesn't (which is the plan), the duplicate
		  symbol error will warn the user that their custom solution is no
		  longer needed and can be removed. 
*/
extern "C" void tss_cleanup_implemented(void) {
	//cout << "tss_cleanup_implemented called" << endl;
}
#endif

JavaJSImpl * JavaJS = 0;

void myJNIClean( JNIEnv * env ){
  JavaJS->detach( env );
}

JavaJSImpl::JavaJSImpl() {
	JavaJSImpl(null);
}

JavaJSImpl::JavaJSImpl(const char *appserverPath){
  _jvm = 0; 
  _mainEnv = 0;
  _dbhook = 0;

  const char * ed = findEd(appserverPath);
  stringstream ss;

#if defined(_WIN32)
  char colon = ';';
#else
  char colon = ':';
#endif

  ss << "-Djava.class.path=.";
  ss << colon << ed << "/build/";
  
  {
    path includeDir(ed);
    includeDir /= "include";
    directory_iterator end;
    directory_iterator i(includeDir);
    while( i != end ) {
      path p = *i;
      ss << colon << p.string();
      i++;
    }
  }

#if defined(_WIN32)
  ss << colon << "C:\\Program Files\\Java\\jdk1.6.0_05\\lib\\tools.jar";
#else
  ss << colon << "/opt/java/lib/tools.jar";
#endif

  if( getenv( "CLASSPATH" ) )
    ss << colon << getenv( "CLASSPATH" );

  string s = ss.str();
  char * p = (char *)malloc( s.size() * 4 );
  strcpy( p , s.c_str() );
  char *q = p;
#if defined(_WIN32)
  while( *p ) {
    if( *p == '/' ) *p = '\\';
    p++;
  }
#endif

  JavaVMOption * options = new JavaVMOption[3];
  options[0].optionString = q;
  options[1].optionString = (char*)"-Djava.awt.headless=true";
  options[2].optionString = (char*)"-Xmx300m";
// -Xcheck:jni  

  _vmArgs = new JavaVMInitArgs();
  _vmArgs->version = JNI_VERSION_1_4;
  _vmArgs->options = options;
  _vmArgs->nOptions = 3;
  _vmArgs->ignoreUnrecognized = JNI_FALSE;

  log() << "Creating JVM" << endl;
  jint res = JNI_CreateJavaVM( &_jvm, (void**)&_mainEnv, _vmArgs );

  if( res ) {
	  cout << "using classpath: " << q << endl;
	  cerr
		  << "res : " << res << " " 
		  << "_jvm : " << _jvm  << " " 
		  << "_env : " << _mainEnv << " "
		  << endl;
  }

  jassert( res == 0 );
  jassert( _jvm > 0 );
  jassert( _mainEnv > 0 );    

  _envs = new boost::thread_specific_ptr<JNIEnv>( myJNIClean );
  assert( ! _envs->get() );
  _envs->reset( _mainEnv );

  _dbhook = findClass( "ed/db/JSHook" );
  if( _dbhook == 0 )
    log() << "using classpath: " << q << endl;
  jassert( _dbhook );

  {
    jmethodID init = _mainEnv->GetStaticMethodID( _dbhook ,  "init" , "(Ljava/lang/String;)V" );
    jassert( init );
    _mainEnv->CallStaticVoidMethod( _dbhook , init , _getEnv()->NewStringUTF( ed ) );
  }

  _dbjni = findClass( "ed/db/DBJni" );
  jassert( _dbjni );

  _scopeCreate = _mainEnv->GetStaticMethodID( _dbhook , "scopeCreate" , "()J" );
  _scopeReset = _mainEnv->GetStaticMethodID( _dbhook , "scopeReset" , "(J)Z" );
  _scopeFree = _mainEnv->GetStaticMethodID( _dbhook , "scopeFree" , "(J)V" );

  _scopeGetNumber = _mainEnv->GetStaticMethodID( _dbhook , "scopeGetNumber" , "(JLjava/lang/String;)D" );
  _scopeGetString = _mainEnv->GetStaticMethodID( _dbhook , "scopeGetString" , "(JLjava/lang/String;)Ljava/lang/String;" );
  _scopeGetBoolean = _mainEnv->GetStaticMethodID( _dbhook , "scopeGetBoolean" , "(JLjava/lang/String;)Z" );
  _scopeGetType = _mainEnv->GetStaticMethodID( _dbhook , "scopeGetType" , "(JLjava/lang/String;)B" );
  _scopeGetObject = _mainEnv->GetStaticMethodID( _dbhook , "scopeGetObject" , "(JLjava/lang/String;Ljava/nio/ByteBuffer;)I" );
  _scopeGuessObjectSize = _mainEnv->GetStaticMethodID( _dbhook , "scopeGuessObjectSize" , "(JLjava/lang/String;)J" );
  
  _scopeSetNumber = _mainEnv->GetStaticMethodID( _dbhook , "scopeSetNumber" , "(JLjava/lang/String;D)Z" );
  _scopeSetBoolean = _mainEnv->GetStaticMethodID( _dbhook , "scopeSetBoolean" , "(JLjava/lang/String;Z)Z" );
  _scopeSetString = _mainEnv->GetStaticMethodID( _dbhook , "scopeSetString" , "(JLjava/lang/String;Ljava/lang/String;)Z" );
  _scopeSetObject = _mainEnv->GetStaticMethodID( _dbhook , "scopeSetObject" , "(JLjava/lang/String;Ljava/nio/ByteBuffer;)Z" );

  _functionCreate = _mainEnv->GetStaticMethodID( _dbhook , "functionCreate" , "(Ljava/lang/String;)J" );
  _invoke = _mainEnv->GetStaticMethodID( _dbhook , "invoke" , "(JJ)I" );

  jassert( _scopeCreate );  
  jassert( _scopeReset );
  jassert( _scopeFree );

  jassert( _scopeGetNumber );
  jassert( _scopeGetString );
  jassert( _scopeGetObject );
  jassert( _scopeGetBoolean );
  jassert( _scopeGetType );
  jassert( _scopeGuessObjectSize );

  jassert( _scopeSetNumber );
  jassert( _scopeSetBoolean );
  jassert( _scopeSetString );
  jassert( _scopeSetObject );

  jassert( _functionCreate );
  jassert( _invoke );
  
  JNINativeMethod * nativeSay = new JNINativeMethod();
  nativeSay->name = (char*)"native_say";
  nativeSay->signature = (char*)"(Ljava/nio/ByteBuffer;)V";
  nativeSay->fnPtr = (void*)java_native_say;
  _mainEnv->RegisterNatives( _dbjni , nativeSay , 1 );


  JNINativeMethod * nativeCall = new JNINativeMethod();
  nativeCall->name = (char*)"native_call";
  nativeCall->signature = (char*)"(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I";
  nativeCall->fnPtr = (void*)java_native_call;
  _mainEnv->RegisterNatives( _dbjni , nativeCall , 1 );

}

JavaJSImpl::~JavaJSImpl(){
  if ( _jvm ){
    _jvm->DestroyJavaVM();
    cerr << "Destroying JVM" << endl;
  }
}

// scope

jlong JavaJSImpl::scopeCreate(){ 
  return _getEnv()->CallStaticLongMethod( _dbhook , _scopeCreate );
}

jboolean JavaJSImpl::scopeReset( jlong id ){
  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeReset );
}

void JavaJSImpl::scopeFree( jlong id ){
  _getEnv()->CallStaticVoidMethod( _dbhook , _scopeFree );
}

// scope setters

int JavaJSImpl::scopeSetBoolean( jlong id , const char * field , jboolean val ) {
  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeSetNumber , id , _getEnv()->NewStringUTF( field ) , val );
}

int JavaJSImpl::scopeSetNumber( jlong id , const char * field , double val ){
  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeSetNumber , id , _getEnv()->NewStringUTF( field ) , val );
}

int JavaJSImpl::scopeSetString( jlong id , const char * field , const char * val ){
  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeSetString , id , _getEnv()->NewStringUTF( field ) , _getEnv()->NewStringUTF( val ) );
}

int JavaJSImpl::scopeSetObject( jlong id , const char * field , JSObj * obj ){
  jobject bb = 0;
  if ( obj ){
    //cout << "from c : " << obj->toString() << endl;
    bb = _getEnv()->NewDirectByteBuffer( (void*)(obj->objdata()) , (jlong)(obj->objsize()) );
    jassert( bb );
  }

  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeSetObject , id , _getEnv()->NewStringUTF( field ) , bb );
}

// scope getters

char JavaJSImpl::scopeGetType( jlong id , const char * field ){
  return _getEnv()->CallStaticByteMethod( _dbhook , _scopeGetType , id , _getEnv()->NewStringUTF( field ) );
}

double JavaJSImpl::scopeGetNumber( jlong id , const char * field ){
  return _getEnv()->CallStaticDoubleMethod( _dbhook , _scopeGetNumber , id , _getEnv()->NewStringUTF( field ) );
}

jboolean JavaJSImpl::scopeGetBoolean( jlong id , const char * field ){
  return _getEnv()->CallStaticBooleanMethod( _dbhook , _scopeGetBoolean , id , _getEnv()->NewStringUTF( field ) );
}

string JavaJSImpl::scopeGetString( jlong id , const char * field ) {
  jstring s = (jstring)_getEnv()->CallStaticObjectMethod( _dbhook , _scopeGetString , id , _getEnv()->NewStringUTF( field ) );
  if ( ! s )
    return "";
  
  const char * c = _getEnv()->GetStringUTFChars( s , 0 );
  string retStr(c);
  _getEnv()->ReleaseStringUTFChars( s , c );
  return retStr;
}

#ifdef J_USE_OBJ
JSObj JavaJSImpl::scopeGetObject( jlong id , const char * field ) 
{
  int guess = _getEnv()->CallStaticIntMethod( _dbhook , _scopeGuessObjectSize , id , _getEnv()->NewStringUTF( field ) );

  char * buf = (char *) malloc(guess);
  jobject bb = _getEnv()->NewDirectByteBuffer( (void*)buf , guess );
  jassert( bb );
  
  int len = _getEnv()->CallStaticIntMethod( _dbhook , _scopeGetObject , id , _getEnv()->NewStringUTF( field ) , bb );
  //cout << "len : " << len << endl;
  jassert( len > 0 && len < guess ); 

  JSObj obj(buf, true);
  assert( obj.objsize() <= guess );
  return obj;
}
#endif

// other

jlong JavaJSImpl::functionCreate( const char * code ){
  jstring s = _getEnv()->NewStringUTF( code );  
  jassert( s );
  jlong id = _getEnv()->CallStaticLongMethod( _dbhook , _functionCreate , s );
  return id;
}
 
int JavaJSImpl::invoke( jlong scope , jlong function ){
  return _getEnv()->CallStaticIntMethod( _dbhook , _invoke , scope , function );
}

// --- fun run method

void JavaJSImpl::run( const char * js ){
  jclass c = findClass( "ed/js/JS" );
  jassert( c );
  
  jmethodID m = _getEnv()->GetStaticMethodID( c , "eval" , "(Ljava/lang/String;)Ljava/lang/Object;" );
  jassert( m );
  
  jstring s = _getEnv()->NewStringUTF( js );
  cout << _getEnv()->CallStaticObjectMethod( c , m , s ) << endl;
}

void JavaJSImpl::printException(){
  jthrowable exc = _getEnv()->ExceptionOccurred();
  if ( exc ){
    _getEnv()->ExceptionDescribe();
    _getEnv()->ExceptionClear();
  }

}

JNIEnv * JavaJSImpl::_getEnv(){
  JNIEnv * env = _envs->get();
  if ( env )
    return env;

  int res = _jvm->AttachCurrentThread( (void**)&env , (void*)&_vmArgs );
  jassert( res == 0 );
  _envs->reset( env );
  return env;
}

void jasserted(const char *msg, const char *file, unsigned line) { 
  cout << "jassert failed " << msg << " " << file << " " << line << endl;
  if ( JavaJS ) JavaJS->printException();
  throw AssertionException();
}


const char* findEd(const char *path) {

#if defined(_WIN32)
	log() << "    WIN32 default : c:/l/ed/" << endl;
	return "c:/l/ed";
#else

	if (!path) {
		return findEd();
	}
	
	cout << "Appserver location specified : " << path << endl;
	
	if (!path) {
		cout << "   invalid appserver location : " << path << " : terminating - prepare for bus error" << endl;
		return 0;
	}
	
	DIR *testDir = opendir(path);

	if (testDir) { 
		cout << "   found directory for appserver : " << path << endl;
		closedir(testDir);
		return path;
	}
	else {
		cout << "   ERROR : not a directory for specified appserver location : " << path << " - prepare for bus error" << endl;
		return null;
	}
#endif
}

const char * findEd(){

	cout << "Appserver location not specified.  Searching.... " << endl;

#if defined(_WIN32)
	log() << "    WIN32 default : c:/l/ed/" << endl;
	return "c:/l/ed";
#else

  static list<const char*> possibleEdDirs;
  if ( ! possibleEdDirs.size() ){
    possibleEdDirs.push_back( "../../ed/ed/" ); // this one for dwight dev box
    possibleEdDirs.push_back( "../ed/" );
    possibleEdDirs.push_back( "../../ed/" );
  }

  for ( list<const char*>::iterator i = possibleEdDirs.begin() ; i != possibleEdDirs.end(); i++ ){
    const char * temp = *i;
    DIR * test = opendir( temp );
    if ( ! test )
      continue;
    
    closedir( test );
	cout << "   found directory for appserver : " << temp << endl;
    return temp;
  }
  
  cout << "   ERROR : can't find directory for appserver - prepare for bus error" << endl;  
  return 0;
#endif
};

// ---

JNIEXPORT void JNICALL java_native_say(JNIEnv * env , jclass, jobject outBuffer ){
  JNI_DEBUG( "native say called!" );

  Message out( env->GetDirectBufferAddress( outBuffer ) , false );
  Message in;

  jniCallback( out , in );
}

JNIEXPORT jint JNICALL java_native_call(JNIEnv * env , jclass, jobject outBuffer , jobject inBuffer ){
  JNI_DEBUG( "native call called!" );
  
  Message out( env->GetDirectBufferAddress( outBuffer ) , false );
  Message in;

  jniCallback( out , in );

  JNI_DEBUG( "in.data : " << in.data );
  if ( in.data && in.data->len > 0 ){
    JNI_DEBUG( "copying data of len :" << in.data->len );
    memcpy( env->GetDirectBufferAddress( inBuffer ) , in.data , in.data->len );
    return in.data->len;
  }

  return 0;
}

// ----

int javajstest() {
  
  const int debug = 0;

  JavaJSImpl& JavaJS = *::JavaJS;

  if ( debug ) cout << "about to create scope" << endl;
  jlong scope = JavaJS.scopeCreate();
  jassert( scope );
  if ( debug ) cout << "got scope" << endl;
         
  
  jlong func1 = JavaJS.functionCreate( "foo = 5.6; bar = \"eliot\"; abc = { foo : 517 }; " );
  jassert( ! JavaJS.invoke( scope , func1 ) );
  
  jassert( 5.6 == JavaJS.scopeGetNumber( scope , "foo" ) );
  jassert( ((string)"eliot") == JavaJS.scopeGetString( scope , "bar" ) );
  
  if ( debug ) cout << "func2 start" << endl;
  jassert( JavaJS.scopeSetNumber( scope , "a" , 5.17 ) );
  jassert( JavaJS.scopeSetString( scope , "b" , "eliot" ) );
  jlong func2 = JavaJS.functionCreate( "assert( 5.17 == a ); assert( \"eliot\" == b );" );
  jassert( ! JavaJS.invoke( scope , func2 ) );
  if ( debug ) cout << "func2 end" << endl;

  if ( debug ) cout << "func3 start" << endl;
  jlong func3 = JavaJS.functionCreate( "function(){ z = true; } " );
  jassert( func3 );
  jassert( ! JavaJS.invoke( scope , func3 ) );
  jassert( JavaJS.scopeGetBoolean( scope , "z" ) );
  if ( debug ) cout << "func3 done" << endl;

#ifdef J_USE_OBJ  
  
  if ( debug ) cout << "going to get object" << endl;
  JSObj obj = JavaJS.scopeGetObject( scope , "abc" );
  if ( debug ) cout << "done gettting object" << endl;
  
  if ( debug ){
    cout << "obj : " << obj.toString() << endl;
  }

  {
    time_t start = time(0);
    for ( int i=0; i<5000; i++ ){
      JavaJS.scopeSetObject( scope , "obj" , &obj );
    }
    time_t end = time(0);

	if( debug )
		cout << "time : " << (unsigned) ( end - start ) << endl;
  }
  
  if ( debug ) cout << "func4 start" << endl;    
  JavaJS.scopeSetObject( scope , "obj" , &obj );
  if ( debug ) cout << "\t here 1" << endl;
  jlong func4 = JavaJS.functionCreate( "tojson( obj );" );
  if ( debug ) cout << "\t here 2" << endl;
  jassert( ! JavaJS.invoke( scope , func4 ) );
  if ( debug ) cout << "func4 end" << endl;
  
  if ( debug ) cout << "func5 start" << endl;
  jassert( JavaJS.scopeSetObject( scope , "c" , &obj ) );
  jlong func5 = JavaJS.functionCreate( "assert( 517 == c.foo );" );
  jassert( func5 );
  jassert( ! JavaJS.invoke( scope , func5 ) );
  if ( debug ) cout << "func5 done" << endl;

#endif

  if ( debug ) cout << "func6 start" << endl;
  for ( int i=0; i<100; i++ ){
    double val = i + 5;
    JavaJS.scopeSetNumber( scope , "zzz" , val );
    jlong func6 = JavaJS.functionCreate( " xxx = zzz; " );
    jassert( ! JavaJS.invoke( scope , func6 ) );
	double n = JavaJS.scopeGetNumber( scope , "xxx" );
    jassert( val == n );
  }
  if ( debug ) cout << "func6 done" << endl;

  jlong func7 = JavaJS.functionCreate( "return 11;" );
  jassert( ! JavaJS.invoke( scope , func7 ) );
  assert( 11 == JavaJS.scopeGetNumber( scope , "return" ) );

  scope = JavaJS.scopeCreate();
  jlong func8 = JavaJS.functionCreate( "function(){ return 12; }" );
  jassert( ! JavaJS.invoke( scope , func8 ) );
  assert( 12 == JavaJS.scopeGetNumber( scope , "return" ) );

  
  return 0;

}

#if defined(_MAIN)
int main() { return javajstest(); }
#endif