Merge branch 'pr/1649'
[collectd.git] / src / java.c
1 /**
2  * collectd - src/java.c
3  * Copyright (C) 2009  Florian octo Forster
4  * Copyright (C) 2008  Justo Alonso Achaques
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at collectd.org>
21  *   Justo Alonso Achaques <justo.alonso at gmail.com>
22  **/
23
24 #include "collectd.h"
25
26 #include "plugin.h"
27 #include "common.h"
28 #include "filter_chain.h"
29
30 #include <jni.h>
31
32 #if !defined(JNI_VERSION_1_2)
33 # error "Need JNI 1.2 compatible interface!"
34 #endif
35
36 /*
37  * Types
38  */
39 struct cjni_jvm_env_s /* {{{ */
40 {
41   JNIEnv *jvm_env;
42   int reference_counter;
43 };
44 typedef struct cjni_jvm_env_s cjni_jvm_env_t;
45 /* }}} */
46
47 struct java_plugin_class_s /* {{{ */
48 {
49   char     *name;
50   jclass    class;
51   jobject   object;
52 };
53 typedef struct java_plugin_class_s java_plugin_class_t;
54 /* }}} */
55
56 #define CB_TYPE_CONFIG       1
57 #define CB_TYPE_INIT         2
58 #define CB_TYPE_READ         3
59 #define CB_TYPE_WRITE        4
60 #define CB_TYPE_FLUSH        5
61 #define CB_TYPE_SHUTDOWN     6
62 #define CB_TYPE_LOG          7
63 #define CB_TYPE_NOTIFICATION 8
64 #define CB_TYPE_MATCH        9
65 #define CB_TYPE_TARGET      10
66 struct cjni_callback_info_s /* {{{ */
67 {
68   char     *name;
69   int       type;
70   jclass    class;
71   jobject   object;
72   jmethodID method;
73 };
74 typedef struct cjni_callback_info_s cjni_callback_info_t;
75 /* }}} */
76
77 /*
78  * Global variables
79  */
80 static JavaVM *jvm = NULL;
81 static pthread_key_t jvm_env_key;
82
83 /* Configuration options for the JVM. */
84 static char **jvm_argv = NULL;
85 static size_t jvm_argc = 0;
86
87 /* List of class names to load */
88 static java_plugin_class_t  *java_classes_list = NULL;
89 static size_t                java_classes_list_len;
90
91 /* List of config, init, and shutdown callbacks. */
92 static cjni_callback_info_t *java_callbacks      = NULL;
93 static size_t                java_callbacks_num  = 0;
94 static pthread_mutex_t       java_callbacks_lock = PTHREAD_MUTEX_INITIALIZER;
95
96 static oconfig_item_t       *config_block = NULL;
97
98 /*
99  * Prototypes
100  *
101  * Mostly functions that are needed by the Java interface (``native'')
102  * functions.
103  */
104 static void cjni_callback_info_destroy (void *arg);
105 static cjni_callback_info_t *cjni_callback_info_create (JNIEnv *jvm_env,
106     jobject o_name, jobject o_callback, int type);
107 static int cjni_callback_register (JNIEnv *jvm_env, jobject o_name,
108     jobject o_callback, int type);
109 static int cjni_read (user_data_t *user_data);
110 static int cjni_write (const data_set_t *ds, const value_list_t *vl,
111     user_data_t *ud);
112 static int cjni_flush (cdtime_t timeout, const char *identifier, user_data_t *ud);
113 static void cjni_log (int severity, const char *message, user_data_t *ud);
114 static int cjni_notification (const notification_t *n, user_data_t *ud);
115
116 /* Create, destroy, and match/invoke functions, used by both, matches AND
117  * targets. */
118 static int cjni_match_target_create (const oconfig_item_t *ci, void **user_data);
119 static int cjni_match_target_destroy (void **user_data);
120 static int cjni_match_target_invoke (const data_set_t *ds, value_list_t *vl,
121     notification_meta_t **meta, void **user_data);
122
123 /*
124  * C to Java conversion functions
125  */
126 static int ctoj_string (JNIEnv *jvm_env, /* {{{ */
127     const char *string,
128     jclass class_ptr, jobject object_ptr, const char *method_name)
129 {
130   jmethodID m_set;
131   jstring o_string;
132
133   /* Create a java.lang.String */
134   o_string = (*jvm_env)->NewStringUTF (jvm_env,
135       (string != NULL) ? string : "");
136   if (o_string == NULL)
137   {
138     ERROR ("java plugin: ctoj_string: NewStringUTF failed.");
139     return (-1);
140   }
141
142   /* Search for the `void setFoo (String s)' method. */
143   m_set = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
144       method_name, "(Ljava/lang/String;)V");
145   if (m_set == NULL)
146   {
147     ERROR ("java plugin: ctoj_string: Cannot find method `void %s (String)'.",
148         method_name);
149     (*jvm_env)->DeleteLocalRef (jvm_env, o_string);
150     return (-1);
151   }
152
153   /* Call the method. */
154   (*jvm_env)->CallVoidMethod (jvm_env, object_ptr, m_set, o_string);
155
156   /* Decrease reference counter on the java.lang.String object. */
157   (*jvm_env)->DeleteLocalRef (jvm_env, o_string);
158
159   return (0);
160 } /* }}} int ctoj_string */
161
162 static jstring ctoj_output_string (JNIEnv *jvm_env, /* {{{ */
163     const char *string)
164 {
165   jstring o_string;
166
167   /* Create a java.lang.String */
168   o_string = (*jvm_env)->NewStringUTF (jvm_env,
169       (string != NULL) ? string : "");
170   if (o_string == NULL)
171   {
172     ERROR ("java plugin: ctoj_output_string: NewStringUTF failed.");
173     return NULL;
174   }
175
176   return (o_string);
177 } /* }}} int ctoj_output_string */
178
179 static int ctoj_int (JNIEnv *jvm_env, /* {{{ */
180     jint value,
181     jclass class_ptr, jobject object_ptr, const char *method_name)
182 {
183   jmethodID m_set;
184
185   /* Search for the `void setFoo (int i)' method. */
186   m_set = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
187       method_name, "(I)V");
188   if (m_set == NULL)
189   {
190     ERROR ("java plugin: ctoj_int: Cannot find method `void %s (int)'.",
191         method_name);
192     return (-1);
193   }
194
195   (*jvm_env)->CallVoidMethod (jvm_env, object_ptr, m_set, value);
196
197   return (0);
198 } /* }}} int ctoj_int */
199
200 static int ctoj_long (JNIEnv *jvm_env, /* {{{ */
201     jlong value,
202     jclass class_ptr, jobject object_ptr, const char *method_name)
203 {
204   jmethodID m_set;
205
206   /* Search for the `void setFoo (long l)' method. */
207   m_set = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
208       method_name, "(J)V");
209   if (m_set == NULL)
210   {
211     ERROR ("java plugin: ctoj_long: Cannot find method `void %s (long)'.",
212         method_name);
213     return (-1);
214   }
215
216   (*jvm_env)->CallVoidMethod (jvm_env, object_ptr, m_set, value);
217
218   return (0);
219 } /* }}} int ctoj_long */
220
221 static int ctoj_double (JNIEnv *jvm_env, /* {{{ */
222     jdouble value,
223     jclass class_ptr, jobject object_ptr, const char *method_name)
224 {
225   jmethodID m_set;
226
227   /* Search for the `void setFoo (double d)' method. */
228   m_set = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
229       method_name, "(D)V");
230   if (m_set == NULL)
231   {
232     ERROR ("java plugin: ctoj_double: Cannot find method `void %s (double)'.",
233         method_name);
234     return (-1);
235   }
236
237   (*jvm_env)->CallVoidMethod (jvm_env, object_ptr, m_set, value);
238
239   return (0);
240 } /* }}} int ctoj_double */
241
242 /* Convert a jlong to a java.lang.Number */
243 static jobject ctoj_jlong_to_number (JNIEnv *jvm_env, jlong value) /* {{{ */
244 {
245   jclass c_long;
246   jmethodID m_long_constructor;
247
248   /* Look up the java.lang.Long class */
249   c_long = (*jvm_env)->FindClass (jvm_env, "java/lang/Long");
250   if (c_long == NULL)
251   {
252     ERROR ("java plugin: ctoj_jlong_to_number: Looking up the "
253         "java.lang.Long class failed.");
254     return (NULL);
255   }
256
257   m_long_constructor = (*jvm_env)->GetMethodID (jvm_env,
258       c_long, "<init>", "(J)V");
259   if (m_long_constructor == NULL)
260   {
261     ERROR ("java plugin: ctoj_jlong_to_number: Looking up the "
262         "`Long (long)' constructor failed.");
263     return (NULL);
264   }
265
266   return ((*jvm_env)->NewObject (jvm_env,
267         c_long, m_long_constructor, value));
268 } /* }}} jobject ctoj_jlong_to_number */
269
270 /* Convert a jdouble to a java.lang.Number */
271 static jobject ctoj_jdouble_to_number (JNIEnv *jvm_env, jdouble value) /* {{{ */
272 {
273   jclass c_double;
274   jmethodID m_double_constructor;
275
276   /* Look up the java.lang.Long class */
277   c_double = (*jvm_env)->FindClass (jvm_env, "java/lang/Double");
278   if (c_double == NULL)
279   {
280     ERROR ("java plugin: ctoj_jdouble_to_number: Looking up the "
281         "java.lang.Double class failed.");
282     return (NULL);
283   }
284
285   m_double_constructor = (*jvm_env)->GetMethodID (jvm_env,
286       c_double, "<init>", "(D)V");
287   if (m_double_constructor == NULL)
288   {
289     ERROR ("java plugin: ctoj_jdouble_to_number: Looking up the "
290         "`Double (double)' constructor failed.");
291     return (NULL);
292   }
293
294   return ((*jvm_env)->NewObject (jvm_env,
295         c_double, m_double_constructor, value));
296 } /* }}} jobject ctoj_jdouble_to_number */
297
298 /* Convert a value_t to a java.lang.Number */
299 static jobject ctoj_value_to_number (JNIEnv *jvm_env, /* {{{ */
300     value_t value, int ds_type)
301 {
302   if (ds_type == DS_TYPE_COUNTER)
303     return (ctoj_jlong_to_number (jvm_env, (jlong) value.counter));
304   else if (ds_type == DS_TYPE_GAUGE)
305     return (ctoj_jdouble_to_number (jvm_env, (jdouble) value.gauge));
306   if (ds_type == DS_TYPE_DERIVE)
307     return (ctoj_jlong_to_number (jvm_env, (jlong) value.derive));
308   if (ds_type == DS_TYPE_ABSOLUTE)
309     return (ctoj_jlong_to_number (jvm_env, (jlong) value.absolute));
310   else
311     return (NULL);
312 } /* }}} jobject ctoj_value_to_number */
313
314 /* Convert a data_source_t to a org/collectd/api/DataSource */
315 static jobject ctoj_data_source (JNIEnv *jvm_env, /* {{{ */
316     const data_source_t *dsrc)
317 {
318   jclass c_datasource;
319   jmethodID m_datasource_constructor;
320   jobject o_datasource;
321   int status;
322
323   /* Look up the DataSource class */
324   c_datasource = (*jvm_env)->FindClass (jvm_env,
325       "org/collectd/api/DataSource");
326   if (c_datasource == NULL)
327   {
328     ERROR ("java plugin: ctoj_data_source: "
329         "FindClass (org/collectd/api/DataSource) failed.");
330     return (NULL);
331   }
332
333   /* Lookup the `ValueList ()' constructor. */
334   m_datasource_constructor = (*jvm_env)->GetMethodID (jvm_env, c_datasource,
335       "<init>", "()V");
336   if (m_datasource_constructor == NULL)
337   {
338     ERROR ("java plugin: ctoj_data_source: Cannot find the "
339         "`DataSource ()' constructor.");
340     return (NULL);
341   }
342
343   /* Create a new instance. */
344   o_datasource = (*jvm_env)->NewObject (jvm_env, c_datasource,
345       m_datasource_constructor);
346   if (o_datasource == NULL)
347   {
348     ERROR ("java plugin: ctoj_data_source: "
349         "Creating a new DataSource instance failed.");
350     return (NULL);
351   }
352
353   /* Set name via `void setName (String name)' */
354   status = ctoj_string (jvm_env, dsrc->name,
355       c_datasource, o_datasource, "setName");
356   if (status != 0)
357   {
358     ERROR ("java plugin: ctoj_data_source: "
359         "ctoj_string (setName) failed.");
360     (*jvm_env)->DeleteLocalRef (jvm_env, o_datasource);
361     return (NULL);
362   }
363
364   /* Set type via `void setType (int type)' */
365   status = ctoj_int (jvm_env, dsrc->type,
366       c_datasource, o_datasource, "setType");
367   if (status != 0)
368   {
369     ERROR ("java plugin: ctoj_data_source: "
370         "ctoj_int (setType) failed.");
371     (*jvm_env)->DeleteLocalRef (jvm_env, o_datasource);
372     return (NULL);
373   }
374
375   /* Set min via `void setMin (double min)' */
376   status = ctoj_double (jvm_env, dsrc->min,
377       c_datasource, o_datasource, "setMin");
378   if (status != 0)
379   {
380     ERROR ("java plugin: ctoj_data_source: "
381         "ctoj_double (setMin) failed.");
382     (*jvm_env)->DeleteLocalRef (jvm_env, o_datasource);
383     return (NULL);
384   }
385
386   /* Set max via `void setMax (double max)' */
387   status = ctoj_double (jvm_env, dsrc->max,
388       c_datasource, o_datasource, "setMax");
389   if (status != 0)
390   {
391     ERROR ("java plugin: ctoj_data_source: "
392         "ctoj_double (setMax) failed.");
393     (*jvm_env)->DeleteLocalRef (jvm_env, o_datasource);
394     return (NULL);
395   }
396
397   return (o_datasource);
398 } /* }}} jobject ctoj_data_source */
399
400 /* Convert a oconfig_value_t to a org/collectd/api/OConfigValue */
401 static jobject ctoj_oconfig_value (JNIEnv *jvm_env, /* {{{ */
402     oconfig_value_t ocvalue)
403 {
404   jclass c_ocvalue;
405   jmethodID m_ocvalue_constructor;
406   jobject o_argument;
407   jobject o_ocvalue;
408
409   m_ocvalue_constructor = NULL;
410   o_argument = NULL;
411
412   c_ocvalue = (*jvm_env)->FindClass (jvm_env,
413       "org/collectd/api/OConfigValue");
414   if (c_ocvalue == NULL)
415   {
416     ERROR ("java plugin: ctoj_oconfig_value: "
417         "FindClass (org/collectd/api/OConfigValue) failed.");
418     return (NULL);
419   }
420
421   if (ocvalue.type == OCONFIG_TYPE_BOOLEAN)
422   {
423     jboolean tmp_boolean;
424
425     tmp_boolean = (ocvalue.value.boolean == 0) ? JNI_FALSE : JNI_TRUE;
426
427     m_ocvalue_constructor = (*jvm_env)->GetMethodID (jvm_env, c_ocvalue,
428         "<init>", "(Z)V");
429     if (m_ocvalue_constructor == NULL)
430     {
431       ERROR ("java plugin: ctoj_oconfig_value: Cannot find the "
432           "`OConfigValue (boolean)' constructor.");
433       return (NULL);
434     }
435
436     return ((*jvm_env)->NewObject (jvm_env,
437           c_ocvalue, m_ocvalue_constructor, tmp_boolean));
438   } /* if (ocvalue.type == OCONFIG_TYPE_BOOLEAN) */
439   else if (ocvalue.type == OCONFIG_TYPE_STRING)
440   {
441     m_ocvalue_constructor = (*jvm_env)->GetMethodID (jvm_env, c_ocvalue,
442         "<init>", "(Ljava/lang/String;)V");
443     if (m_ocvalue_constructor == NULL)
444     {
445       ERROR ("java plugin: ctoj_oconfig_value: Cannot find the "
446           "`OConfigValue (String)' constructor.");
447       return (NULL);
448     }
449
450     o_argument = (*jvm_env)->NewStringUTF (jvm_env, ocvalue.value.string);
451     if (o_argument == NULL)
452     {
453       ERROR ("java plugin: ctoj_oconfig_value: "
454           "Creating a String object failed.");
455       return (NULL);
456     }
457   }
458   else if (ocvalue.type == OCONFIG_TYPE_NUMBER)
459   {
460     m_ocvalue_constructor = (*jvm_env)->GetMethodID (jvm_env, c_ocvalue,
461         "<init>", "(Ljava/lang/Number;)V");
462     if (m_ocvalue_constructor == NULL)
463     {
464       ERROR ("java plugin: ctoj_oconfig_value: Cannot find the "
465           "`OConfigValue (Number)' constructor.");
466       return (NULL);
467     }
468
469     o_argument = ctoj_jdouble_to_number (jvm_env,
470         (jdouble) ocvalue.value.number);
471     if (o_argument == NULL)
472     {
473       ERROR ("java plugin: ctoj_oconfig_value: "
474           "Creating a Number object failed.");
475       return (NULL);
476     }
477   }
478   else
479   {
480     return (NULL);
481   }
482
483   assert (m_ocvalue_constructor != NULL);
484   assert (o_argument != NULL);
485
486   o_ocvalue = (*jvm_env)->NewObject (jvm_env,
487       c_ocvalue, m_ocvalue_constructor, o_argument);
488   if (o_ocvalue == NULL)
489   {
490     ERROR ("java plugin: ctoj_oconfig_value: "
491         "Creating an OConfigValue object failed.");
492     (*jvm_env)->DeleteLocalRef (jvm_env, o_argument);
493     return (NULL);
494   }
495
496   (*jvm_env)->DeleteLocalRef (jvm_env, o_argument);
497   return (o_ocvalue);
498 } /* }}} jobject ctoj_oconfig_value */
499
500 /* Convert a oconfig_item_t to a org/collectd/api/OConfigItem */
501 static jobject ctoj_oconfig_item (JNIEnv *jvm_env, /* {{{ */
502     const oconfig_item_t *ci)
503 {
504   jclass c_ocitem;
505   jmethodID m_ocitem_constructor;
506   jmethodID m_addvalue;
507   jmethodID m_addchild;
508   jobject o_key;
509   jobject o_ocitem;
510
511   c_ocitem = (*jvm_env)->FindClass (jvm_env, "org/collectd/api/OConfigItem");
512   if (c_ocitem == NULL)
513   {
514     ERROR ("java plugin: ctoj_oconfig_item: "
515         "FindClass (org/collectd/api/OConfigItem) failed.");
516     return (NULL);
517   }
518
519   /* Get the required methods: m_ocitem_constructor, m_addvalue, and m_addchild
520    * {{{ */
521   m_ocitem_constructor = (*jvm_env)->GetMethodID (jvm_env, c_ocitem,
522       "<init>", "(Ljava/lang/String;)V");
523   if (m_ocitem_constructor == NULL)
524   {
525     ERROR ("java plugin: ctoj_oconfig_item: Cannot find the "
526         "`OConfigItem (String)' constructor.");
527     return (NULL);
528   }
529
530   m_addvalue = (*jvm_env)->GetMethodID (jvm_env, c_ocitem,
531       "addValue", "(Lorg/collectd/api/OConfigValue;)V");
532   if (m_addvalue == NULL)
533   {
534     ERROR ("java plugin: ctoj_oconfig_item: Cannot find the "
535         "`addValue (OConfigValue)' method.");
536     return (NULL);
537   }
538
539   m_addchild = (*jvm_env)->GetMethodID (jvm_env, c_ocitem,
540       "addChild", "(Lorg/collectd/api/OConfigItem;)V");
541   if (m_addchild == NULL)
542   {
543     ERROR ("java plugin: ctoj_oconfig_item: Cannot find the "
544         "`addChild (OConfigItem)' method.");
545     return (NULL);
546   }
547   /* }}} */
548
549   /* Create a String object with the key.
550    * Needed for calling the constructor. */
551   o_key = (*jvm_env)->NewStringUTF (jvm_env, ci->key);
552   if (o_key == NULL)
553   {
554     ERROR ("java plugin: ctoj_oconfig_item: "
555         "Creating String object failed.");
556     return (NULL);
557   }
558
559   /* Create an OConfigItem object */
560   o_ocitem = (*jvm_env)->NewObject (jvm_env,
561       c_ocitem, m_ocitem_constructor, o_key);
562   if (o_ocitem == NULL)
563   {
564     ERROR ("java plugin: ctoj_oconfig_item: "
565         "Creating an OConfigItem object failed.");
566     (*jvm_env)->DeleteLocalRef (jvm_env, o_key);
567     return (NULL);
568   }
569
570   /* We don't need the String object any longer.. */
571   (*jvm_env)->DeleteLocalRef (jvm_env, o_key);
572
573   /* Call OConfigItem.addValue for each value */
574   for (int i = 0; i < ci->values_num; i++) /* {{{ */
575   {
576     jobject o_value;
577
578     o_value = ctoj_oconfig_value (jvm_env, ci->values[i]);
579     if (o_value == NULL)
580     {
581       ERROR ("java plugin: ctoj_oconfig_item: "
582           "Creating an OConfigValue object failed.");
583       (*jvm_env)->DeleteLocalRef (jvm_env, o_ocitem);
584       return (NULL);
585     }
586
587     (*jvm_env)->CallVoidMethod (jvm_env, o_ocitem, m_addvalue, o_value);
588     (*jvm_env)->DeleteLocalRef (jvm_env, o_value);
589   } /* }}} for (i = 0; i < ci->values_num; i++) */
590
591   /* Call OConfigItem.addChild for each child */
592   for (int i = 0; i < ci->children_num; i++) /* {{{ */
593   {
594     jobject o_child;
595
596     o_child = ctoj_oconfig_item (jvm_env, ci->children + i);
597     if (o_child == NULL)
598     {
599       ERROR ("java plugin: ctoj_oconfig_item: "
600           "Creating an OConfigItem object failed.");
601       (*jvm_env)->DeleteLocalRef (jvm_env, o_ocitem);
602       return (NULL);
603     }
604
605     (*jvm_env)->CallVoidMethod (jvm_env, o_ocitem, m_addchild, o_child);
606     (*jvm_env)->DeleteLocalRef (jvm_env, o_child);
607   } /* }}} for (i = 0; i < ci->children_num; i++) */
608
609   return (o_ocitem);
610 } /* }}} jobject ctoj_oconfig_item */
611
612 /* Convert a data_set_t to a org/collectd/api/DataSet */
613 static jobject ctoj_data_set (JNIEnv *jvm_env, const data_set_t *ds) /* {{{ */
614 {
615   jclass c_dataset;
616   jmethodID m_constructor;
617   jmethodID m_add;
618   jobject o_type;
619   jobject o_dataset;
620
621   /* Look up the org/collectd/api/DataSet class */
622   c_dataset = (*jvm_env)->FindClass (jvm_env, "org/collectd/api/DataSet");
623   if (c_dataset == NULL)
624   {
625     ERROR ("java plugin: ctoj_data_set: Looking up the "
626         "org/collectd/api/DataSet class failed.");
627     return (NULL);
628   }
629
630   /* Search for the `DataSet (String type)' constructor. */
631   m_constructor = (*jvm_env)->GetMethodID (jvm_env,
632       c_dataset, "<init>", "(Ljava/lang/String;)V");
633   if (m_constructor == NULL)
634   {
635     ERROR ("java plugin: ctoj_data_set: Looking up the "
636         "`DataSet (String)' constructor failed.");
637     return (NULL);
638   }
639
640   /* Search for the `void addDataSource (DataSource)' method. */
641   m_add = (*jvm_env)->GetMethodID (jvm_env,
642       c_dataset, "addDataSource", "(Lorg/collectd/api/DataSource;)V");
643   if (m_add == NULL)
644   {
645     ERROR ("java plugin: ctoj_data_set: Looking up the "
646         "`addDataSource (DataSource)' method failed.");
647     return (NULL);
648   }
649
650   o_type = (*jvm_env)->NewStringUTF (jvm_env, ds->type);
651   if (o_type == NULL)
652   {
653     ERROR ("java plugin: ctoj_data_set: Creating a String object failed.");
654     return (NULL);
655   }
656
657   o_dataset = (*jvm_env)->NewObject (jvm_env,
658       c_dataset, m_constructor, o_type);
659   if (o_dataset == NULL)
660   {
661     ERROR ("java plugin: ctoj_data_set: Creating a DataSet object failed.");
662     (*jvm_env)->DeleteLocalRef (jvm_env, o_type);
663     return (NULL);
664   }
665
666   /* Decrease reference counter on the java.lang.String object. */
667   (*jvm_env)->DeleteLocalRef (jvm_env, o_type);
668
669   for (size_t i = 0; i < ds->ds_num; i++)
670   {
671     jobject o_datasource;
672
673     o_datasource = ctoj_data_source (jvm_env, ds->ds + i);
674     if (o_datasource == NULL)
675     {
676       ERROR ("java plugin: ctoj_data_set: ctoj_data_source (%s.%s) failed",
677           ds->type, ds->ds[i].name);
678       (*jvm_env)->DeleteLocalRef (jvm_env, o_dataset);
679       return (NULL);
680     }
681
682     (*jvm_env)->CallVoidMethod (jvm_env, o_dataset, m_add, o_datasource);
683
684     (*jvm_env)->DeleteLocalRef (jvm_env, o_datasource);
685   } /* for (i = 0; i < ds->ds_num; i++) */
686
687   return (o_dataset);
688 } /* }}} jobject ctoj_data_set */
689
690 static int ctoj_value_list_add_value (JNIEnv *jvm_env, /* {{{ */
691     value_t value, int ds_type,
692     jclass class_ptr, jobject object_ptr)
693 {
694   jmethodID m_addvalue;
695   jobject o_number;
696
697   m_addvalue = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
698       "addValue", "(Ljava/lang/Number;)V");
699   if (m_addvalue == NULL)
700   {
701     ERROR ("java plugin: ctoj_value_list_add_value: "
702         "Cannot find method `void addValue (Number)'.");
703     return (-1);
704   }
705
706   o_number = ctoj_value_to_number (jvm_env, value, ds_type);
707   if (o_number == NULL)
708   {
709     ERROR ("java plugin: ctoj_value_list_add_value: "
710         "ctoj_value_to_number failed.");
711     return (-1);
712   }
713
714   (*jvm_env)->CallVoidMethod (jvm_env, object_ptr, m_addvalue, o_number);
715
716   (*jvm_env)->DeleteLocalRef (jvm_env, o_number);
717
718   return (0);
719 } /* }}} int ctoj_value_list_add_value */
720
721 static int ctoj_value_list_add_data_set (JNIEnv *jvm_env, /* {{{ */
722     jclass c_valuelist, jobject o_valuelist, const data_set_t *ds)
723 {
724   jmethodID m_setdataset;
725   jobject o_dataset;
726
727   /* Look for the `void setDataSource (List<DataSource> ds)' method. */
728   m_setdataset = (*jvm_env)->GetMethodID (jvm_env, c_valuelist,
729       "setDataSet", "(Lorg/collectd/api/DataSet;)V");
730   if (m_setdataset == NULL)
731   {
732     ERROR ("java plugin: ctoj_value_list_add_data_set: "
733         "Cannot find the `void setDataSet (DataSet)' method.");
734     return (-1);
735   }
736
737   /* Create a DataSet object. */
738   o_dataset = ctoj_data_set (jvm_env, ds);
739   if (o_dataset == NULL)
740   {
741     ERROR ("java plugin: ctoj_value_list_add_data_set: "
742         "ctoj_data_set (%s) failed.", ds->type);
743     return (-1);
744   }
745
746   /* Actually call the method. */
747   (*jvm_env)->CallVoidMethod (jvm_env,
748       o_valuelist, m_setdataset, o_dataset);
749
750   /* Decrease reference counter on the List<DataSource> object. */
751   (*jvm_env)->DeleteLocalRef (jvm_env, o_dataset);
752
753   return (0);
754 } /* }}} int ctoj_value_list_add_data_set */
755
756 /* Convert a value_list_t (and data_set_t) to a org/collectd/api/ValueList */
757 static jobject ctoj_value_list (JNIEnv *jvm_env, /* {{{ */
758     const data_set_t *ds, const value_list_t *vl)
759 {
760   jclass c_valuelist;
761   jmethodID m_valuelist_constructor;
762   jobject o_valuelist;
763   int status;
764
765   /* First, create a new ValueList instance..
766    * Look up the class.. */
767   c_valuelist = (*jvm_env)->FindClass (jvm_env,
768       "org/collectd/api/ValueList");
769   if (c_valuelist == NULL)
770   {
771     ERROR ("java plugin: ctoj_value_list: "
772         "FindClass (org/collectd/api/ValueList) failed.");
773     return (NULL);
774   }
775
776   /* Lookup the `ValueList ()' constructor. */
777   m_valuelist_constructor = (*jvm_env)->GetMethodID (jvm_env, c_valuelist,
778       "<init>", "()V");
779   if (m_valuelist_constructor == NULL)
780   {
781     ERROR ("java plugin: ctoj_value_list: Cannot find the "
782         "`ValueList ()' constructor.");
783     return (NULL);
784   }
785
786   /* Create a new instance. */
787   o_valuelist = (*jvm_env)->NewObject (jvm_env, c_valuelist,
788       m_valuelist_constructor);
789   if (o_valuelist == NULL)
790   {
791     ERROR ("java plugin: ctoj_value_list: Creating a new ValueList instance "
792         "failed.");
793     return (NULL);
794   }
795
796   status = ctoj_value_list_add_data_set (jvm_env,
797       c_valuelist, o_valuelist, ds);
798   if (status != 0)
799   {
800     ERROR ("java plugin: ctoj_value_list: "
801         "ctoj_value_list_add_data_set failed.");
802     (*jvm_env)->DeleteLocalRef (jvm_env, o_valuelist);
803     return (NULL);
804   }
805
806   /* Set the strings.. */
807 #define SET_STRING(str,method_name) do { \
808   status = ctoj_string (jvm_env, str, \
809       c_valuelist, o_valuelist, method_name); \
810   if (status != 0) { \
811     ERROR ("java plugin: ctoj_value_list: ctoj_string (%s) failed.", \
812         method_name); \
813     (*jvm_env)->DeleteLocalRef (jvm_env, o_valuelist); \
814     return (NULL); \
815   } } while (0)
816
817   SET_STRING (vl->host,            "setHost");
818   SET_STRING (vl->plugin,          "setPlugin");
819   SET_STRING (vl->plugin_instance, "setPluginInstance");
820   SET_STRING (vl->type,            "setType");
821   SET_STRING (vl->type_instance,   "setTypeInstance");
822
823 #undef SET_STRING
824
825   /* Set the `time' member. Java stores time in milliseconds. */
826   status = ctoj_long (jvm_env, (jlong) CDTIME_T_TO_MS (vl->time),
827       c_valuelist, o_valuelist, "setTime");
828   if (status != 0)
829   {
830     ERROR ("java plugin: ctoj_value_list: ctoj_long (setTime) failed.");
831     (*jvm_env)->DeleteLocalRef (jvm_env, o_valuelist);
832     return (NULL);
833   }
834
835   /* Set the `interval' member.. */
836   status = ctoj_long (jvm_env,
837       (jlong) CDTIME_T_TO_MS (vl->interval),
838       c_valuelist, o_valuelist, "setInterval");
839   if (status != 0)
840   {
841     ERROR ("java plugin: ctoj_value_list: ctoj_long (setInterval) failed.");
842     (*jvm_env)->DeleteLocalRef (jvm_env, o_valuelist);
843     return (NULL);
844   }
845
846   for (size_t i = 0; i < vl->values_len; i++)
847   {
848     status = ctoj_value_list_add_value (jvm_env, vl->values[i], ds->ds[i].type,
849         c_valuelist, o_valuelist);
850     if (status != 0)
851     {
852       ERROR ("java plugin: ctoj_value_list: "
853           "ctoj_value_list_add_value failed.");
854       (*jvm_env)->DeleteLocalRef (jvm_env, o_valuelist);
855       return (NULL);
856     }
857   }
858
859   return (o_valuelist);
860 } /* }}} jobject ctoj_value_list */
861
862 /* Convert a notification_t to a org/collectd/api/Notification */
863 static jobject ctoj_notification (JNIEnv *jvm_env, /* {{{ */
864     const notification_t *n)
865 {
866   jclass c_notification;
867   jmethodID m_constructor;
868   jobject o_notification;
869   int status;
870
871   /* First, create a new Notification instance..
872    * Look up the class.. */
873   c_notification = (*jvm_env)->FindClass (jvm_env,
874       "org/collectd/api/Notification");
875   if (c_notification == NULL)
876   {
877     ERROR ("java plugin: ctoj_notification: "
878         "FindClass (org/collectd/api/Notification) failed.");
879     return (NULL);
880   }
881
882   /* Lookup the `Notification ()' constructor. */
883   m_constructor = (*jvm_env)->GetMethodID (jvm_env, c_notification,
884       "<init>", "()V");
885   if (m_constructor == NULL)
886   {
887     ERROR ("java plugin: ctoj_notification: Cannot find the "
888         "`Notification ()' constructor.");
889     return (NULL);
890   }
891
892   /* Create a new instance. */
893   o_notification = (*jvm_env)->NewObject (jvm_env, c_notification,
894       m_constructor);
895   if (o_notification == NULL)
896   {
897     ERROR ("java plugin: ctoj_notification: Creating a new Notification "
898         "instance failed.");
899     return (NULL);
900   }
901
902   /* Set the strings.. */
903 #define SET_STRING(str,method_name) do { \
904   status = ctoj_string (jvm_env, str, \
905       c_notification, o_notification, method_name); \
906   if (status != 0) { \
907     ERROR ("java plugin: ctoj_notification: ctoj_string (%s) failed.", \
908         method_name); \
909     (*jvm_env)->DeleteLocalRef (jvm_env, o_notification); \
910     return (NULL); \
911   } } while (0)
912
913   SET_STRING (n->host,            "setHost");
914   SET_STRING (n->plugin,          "setPlugin");
915   SET_STRING (n->plugin_instance, "setPluginInstance");
916   SET_STRING (n->type,            "setType");
917   SET_STRING (n->type_instance,   "setTypeInstance");
918   SET_STRING (n->message,         "setMessage");
919
920 #undef SET_STRING
921
922   /* Set the `time' member. Java stores time in milliseconds. */
923   status = ctoj_long (jvm_env, (jlong) CDTIME_T_TO_MS (n->time),
924       c_notification, o_notification, "setTime");
925   if (status != 0)
926   {
927     ERROR ("java plugin: ctoj_notification: ctoj_long (setTime) failed.");
928     (*jvm_env)->DeleteLocalRef (jvm_env, o_notification);
929     return (NULL);
930   }
931
932   /* Set the `severity' member.. */
933   status = ctoj_int (jvm_env, (jint) n->severity,
934       c_notification, o_notification, "setSeverity");
935   if (status != 0)
936   {
937     ERROR ("java plugin: ctoj_notification: ctoj_int (setSeverity) failed.");
938     (*jvm_env)->DeleteLocalRef (jvm_env, o_notification);
939     return (NULL);
940   }
941
942   return (o_notification);
943 } /* }}} jobject ctoj_notification */
944
945 /*
946  * Java to C conversion functions
947  */
948 /* Call a `String <method> ()' method. */
949 static int jtoc_string (JNIEnv *jvm_env, /* {{{ */
950     char *buffer, size_t buffer_size, int empty_okay,
951     jclass class_ptr, jobject object_ptr, const char *method_name)
952 {
953   jmethodID method_id;
954   jobject string_obj;
955   const char *c_str;
956
957   method_id = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
958       method_name, "()Ljava/lang/String;");
959   if (method_id == NULL)
960   {
961     ERROR ("java plugin: jtoc_string: Cannot find method `String %s ()'.",
962         method_name);
963     return (-1);
964   }
965
966   string_obj = (*jvm_env)->CallObjectMethod (jvm_env, object_ptr, method_id);
967   if ((string_obj == NULL) && (empty_okay == 0))
968   {
969     ERROR ("java plugin: jtoc_string: CallObjectMethod (%s) failed.",
970         method_name);
971     return (-1);
972   }
973   else if ((string_obj == NULL) && (empty_okay != 0))
974   {
975     memset (buffer, 0, buffer_size);
976     return (0);
977   }
978
979   c_str = (*jvm_env)->GetStringUTFChars (jvm_env, string_obj, 0);
980   if (c_str == NULL)
981   {
982     ERROR ("java plugin: jtoc_string: GetStringUTFChars failed.");
983     (*jvm_env)->DeleteLocalRef (jvm_env, string_obj);
984     return (-1);
985   }
986
987   sstrncpy (buffer, c_str, buffer_size);
988
989   (*jvm_env)->ReleaseStringUTFChars (jvm_env, string_obj, c_str);
990   (*jvm_env)->DeleteLocalRef (jvm_env, string_obj);
991
992   return (0);
993 } /* }}} int jtoc_string */
994
995 /* Call an `int <method> ()' method. */
996 static int jtoc_int (JNIEnv *jvm_env, /* {{{ */
997     jint *ret_value,
998     jclass class_ptr, jobject object_ptr, const char *method_name)
999 {
1000   jmethodID method_id;
1001
1002   method_id = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
1003       method_name, "()I");
1004   if (method_id == NULL)
1005   {
1006     ERROR ("java plugin: jtoc_int: Cannot find method `int %s ()'.",
1007         method_name);
1008     return (-1);
1009   }
1010
1011   *ret_value = (*jvm_env)->CallIntMethod (jvm_env, object_ptr, method_id);
1012
1013   return (0);
1014 } /* }}} int jtoc_int */
1015
1016 /* Call a `long <method> ()' method. */
1017 static int jtoc_long (JNIEnv *jvm_env, /* {{{ */
1018     jlong *ret_value,
1019     jclass class_ptr, jobject object_ptr, const char *method_name)
1020 {
1021   jmethodID method_id;
1022
1023   method_id = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
1024       method_name, "()J");
1025   if (method_id == NULL)
1026   {
1027     ERROR ("java plugin: jtoc_long: Cannot find method `long %s ()'.",
1028         method_name);
1029     return (-1);
1030   }
1031
1032   *ret_value = (*jvm_env)->CallLongMethod (jvm_env, object_ptr, method_id);
1033
1034   return (0);
1035 } /* }}} int jtoc_long */
1036
1037 /* Call a `double <method> ()' method. */
1038 static int jtoc_double (JNIEnv *jvm_env, /* {{{ */
1039     jdouble *ret_value,
1040     jclass class_ptr, jobject object_ptr, const char *method_name)
1041 {
1042   jmethodID method_id;
1043
1044   method_id = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
1045       method_name, "()D");
1046   if (method_id == NULL)
1047   {
1048     ERROR ("java plugin: jtoc_double: Cannot find method `double %s ()'.",
1049         method_name);
1050     return (-1);
1051   }
1052
1053   *ret_value = (*jvm_env)->CallDoubleMethod (jvm_env, object_ptr, method_id);
1054
1055   return (0);
1056 } /* }}} int jtoc_double */
1057
1058 static int jtoc_value (JNIEnv *jvm_env, /* {{{ */
1059     value_t *ret_value, int ds_type, jobject object_ptr)
1060 {
1061   jclass class_ptr;
1062   int status;
1063
1064   class_ptr = (*jvm_env)->GetObjectClass (jvm_env, object_ptr);
1065
1066   if (ds_type == DS_TYPE_GAUGE)
1067   {
1068     jdouble tmp_double;
1069
1070     status = jtoc_double (jvm_env, &tmp_double,
1071         class_ptr, object_ptr, "doubleValue");
1072     if (status != 0)
1073     {
1074       ERROR ("java plugin: jtoc_value: "
1075           "jtoc_double failed.");
1076       return (-1);
1077     }
1078     (*ret_value).gauge = (gauge_t) tmp_double;
1079   }
1080   else
1081   {
1082     jlong tmp_long;
1083
1084     status = jtoc_long (jvm_env, &tmp_long,
1085         class_ptr, object_ptr, "longValue");
1086     if (status != 0)
1087     {
1088       ERROR ("java plugin: jtoc_value: "
1089           "jtoc_long failed.");
1090       return (-1);
1091     }
1092
1093     if (ds_type == DS_TYPE_DERIVE)
1094       (*ret_value).derive = (derive_t) tmp_long;
1095     else if (ds_type == DS_TYPE_ABSOLUTE)
1096       (*ret_value).absolute = (absolute_t) tmp_long;
1097     else
1098       (*ret_value).counter = (counter_t) tmp_long;
1099   }
1100
1101   return (0);
1102 } /* }}} int jtoc_value */
1103
1104 /* Read a List<Number>, convert it to `value_t' and add it to the given
1105  * `value_list_t'. */
1106 static int jtoc_values_array (JNIEnv *jvm_env, /* {{{ */
1107     const data_set_t *ds, value_list_t *vl,
1108     jclass class_ptr, jobject object_ptr)
1109 {
1110   jmethodID m_getvalues;
1111   jmethodID m_toarray;
1112   jobject o_list;
1113   jobjectArray o_number_array;
1114
1115   value_t *values;
1116   int values_num;
1117
1118   values_num = ds->ds_num;
1119
1120   values = NULL;
1121   o_number_array = NULL;
1122   o_list = NULL;
1123
1124 #define BAIL_OUT(status) \
1125   free (values); \
1126   if (o_number_array != NULL) \
1127     (*jvm_env)->DeleteLocalRef (jvm_env, o_number_array); \
1128   if (o_list != NULL) \
1129     (*jvm_env)->DeleteLocalRef (jvm_env, o_list); \
1130   return (status);
1131
1132   /* Call: List<Number> ValueList.getValues () */
1133   m_getvalues = (*jvm_env)->GetMethodID (jvm_env, class_ptr,
1134       "getValues", "()Ljava/util/List;");
1135   if (m_getvalues == NULL)
1136   {
1137     ERROR ("java plugin: jtoc_values_array: "
1138         "Cannot find method `List getValues ()'.");
1139     BAIL_OUT (-1);
1140   }
1141
1142   o_list = (*jvm_env)->CallObjectMethod (jvm_env, object_ptr, m_getvalues);
1143   if (o_list == NULL)
1144   {
1145     ERROR ("java plugin: jtoc_values_array: "
1146         "CallObjectMethod (getValues) failed.");
1147     BAIL_OUT (-1);
1148   }
1149
1150   /* Call: Number[] List.toArray () */
1151   m_toarray = (*jvm_env)->GetMethodID (jvm_env,
1152       (*jvm_env)->GetObjectClass (jvm_env, o_list),
1153       "toArray", "()[Ljava/lang/Object;");
1154   if (m_toarray == NULL)
1155   {
1156     ERROR ("java plugin: jtoc_values_array: "
1157         "Cannot find method `Object[] toArray ()'.");
1158     BAIL_OUT (-1);
1159   }
1160
1161   o_number_array = (*jvm_env)->CallObjectMethod (jvm_env, o_list, m_toarray);
1162   if (o_number_array == NULL)
1163   {
1164     ERROR ("java plugin: jtoc_values_array: "
1165         "CallObjectMethod (toArray) failed.");
1166     BAIL_OUT (-1);
1167   }
1168
1169   values = (value_t *) calloc (values_num, sizeof (value_t));
1170   if (values == NULL)
1171   {
1172     ERROR ("java plugin: jtoc_values_array: calloc failed.");
1173     BAIL_OUT (-1);
1174   }
1175
1176   for (int i = 0; i < values_num; i++)
1177   {
1178     jobject o_number;
1179     int status;
1180
1181     o_number = (*jvm_env)->GetObjectArrayElement (jvm_env,
1182         o_number_array, (jsize) i);
1183     if (o_number == NULL)
1184     {
1185       ERROR ("java plugin: jtoc_values_array: "
1186           "GetObjectArrayElement (%i) failed.", i);
1187       BAIL_OUT (-1);
1188     }
1189
1190     status = jtoc_value (jvm_env, values + i, ds->ds[i].type, o_number);
1191     if (status != 0)
1192     {
1193       ERROR ("java plugin: jtoc_values_array: "
1194           "jtoc_value (%i) failed.", i);
1195       BAIL_OUT (-1);
1196     }
1197   } /* for (i = 0; i < values_num; i++) */
1198
1199   vl->values = values;
1200   vl->values_len = values_num;
1201
1202 #undef BAIL_OUT
1203   (*jvm_env)->DeleteLocalRef (jvm_env, o_number_array);
1204   (*jvm_env)->DeleteLocalRef (jvm_env, o_list);
1205   return (0);
1206 } /* }}} int jtoc_values_array */
1207
1208 /* Convert a org/collectd/api/ValueList to a value_list_t. */
1209 static int jtoc_value_list (JNIEnv *jvm_env, value_list_t *vl, /* {{{ */
1210     jobject object_ptr)
1211 {
1212   jclass class_ptr;
1213   int status;
1214   jlong tmp_long;
1215   const data_set_t *ds;
1216
1217   class_ptr = (*jvm_env)->GetObjectClass (jvm_env, object_ptr);
1218   if (class_ptr == NULL)
1219   {
1220     ERROR ("java plugin: jtoc_value_list: GetObjectClass failed.");
1221     return (-1);
1222   }
1223
1224   /* eo == empty okay */
1225 #define SET_STRING(buffer,method, eo) do { \
1226   status = jtoc_string (jvm_env, buffer, sizeof (buffer), eo, \
1227       class_ptr, object_ptr, method); \
1228   if (status != 0) { \
1229     ERROR ("java plugin: jtoc_value_list: jtoc_string (%s) failed.", \
1230         method); \
1231     return (-1); \
1232   } } while (0)
1233
1234   SET_STRING(vl->type, "getType", /* empty = */ 0);
1235
1236   ds = plugin_get_ds (vl->type);
1237   if (ds == NULL)
1238   {
1239     ERROR ("java plugin: jtoc_value_list: Data-set `%s' is not defined. "
1240         "Please consult the types.db(5) manpage for mor information.",
1241         vl->type);
1242     return (-1);
1243   }
1244
1245   SET_STRING(vl->host,            "getHost",           /* empty = */ 0);
1246   SET_STRING(vl->plugin,          "getPlugin",         /* empty = */ 0);
1247   SET_STRING(vl->plugin_instance, "getPluginInstance", /* empty = */ 1);
1248   SET_STRING(vl->type_instance,   "getTypeInstance",   /* empty = */ 1);
1249
1250 #undef SET_STRING
1251
1252   status = jtoc_long (jvm_env, &tmp_long, class_ptr, object_ptr, "getTime");
1253   if (status != 0)
1254   {
1255     ERROR ("java plugin: jtoc_value_list: jtoc_long (getTime) failed.");
1256     return (-1);
1257   }
1258   /* Java measures time in milliseconds. */
1259   vl->time = MS_TO_CDTIME_T (tmp_long);
1260
1261   status = jtoc_long (jvm_env, &tmp_long,
1262       class_ptr, object_ptr, "getInterval");
1263   if (status != 0)
1264   {
1265     ERROR ("java plugin: jtoc_value_list: jtoc_long (getInterval) failed.");
1266     return (-1);
1267   }
1268   vl->interval = MS_TO_CDTIME_T (tmp_long);
1269
1270   status = jtoc_values_array (jvm_env, ds, vl, class_ptr, object_ptr);
1271   if (status != 0)
1272   {
1273     ERROR ("java plugin: jtoc_value_list: jtoc_values_array failed.");
1274     return (-1);
1275   }
1276
1277   return (0);
1278 } /* }}} int jtoc_value_list */
1279
1280 /* Convert a org/collectd/api/Notification to a notification_t. */
1281 static int jtoc_notification (JNIEnv *jvm_env, notification_t *n, /* {{{ */
1282     jobject object_ptr)
1283 {
1284   jclass class_ptr;
1285   int status;
1286   jlong tmp_long;
1287   jint tmp_int;
1288
1289   class_ptr = (*jvm_env)->GetObjectClass (jvm_env, object_ptr);
1290   if (class_ptr == NULL)
1291   {
1292     ERROR ("java plugin: jtoc_notification: GetObjectClass failed.");
1293     return (-1);
1294   }
1295
1296   /* eo == empty okay */
1297 #define SET_STRING(buffer,method, eo) do { \
1298   status = jtoc_string (jvm_env, buffer, sizeof (buffer), eo, \
1299       class_ptr, object_ptr, method); \
1300   if (status != 0) { \
1301     ERROR ("java plugin: jtoc_notification: jtoc_string (%s) failed.", \
1302         method); \
1303     return (-1); \
1304   } } while (0)
1305
1306   SET_STRING (n->host,            "getHost",           /* empty = */ 1);
1307   SET_STRING (n->plugin,          "getPlugin",         /* empty = */ 1);
1308   SET_STRING (n->plugin_instance, "getPluginInstance", /* empty = */ 1);
1309   SET_STRING (n->type,            "getType",           /* empty = */ 1);
1310   SET_STRING (n->type_instance,   "getTypeInstance",   /* empty = */ 1);
1311   SET_STRING (n->message,         "getMessage",        /* empty = */ 0);
1312
1313 #undef SET_STRING
1314
1315   status = jtoc_long (jvm_env, &tmp_long, class_ptr, object_ptr, "getTime");
1316   if (status != 0)
1317   {
1318     ERROR ("java plugin: jtoc_notification: jtoc_long (getTime) failed.");
1319     return (-1);
1320   }
1321   /* Java measures time in milliseconds. */
1322   n->time = MS_TO_CDTIME_T(tmp_long);
1323
1324   status = jtoc_int (jvm_env, &tmp_int,
1325       class_ptr, object_ptr, "getSeverity");
1326   if (status != 0)
1327   {
1328     ERROR ("java plugin: jtoc_notification: jtoc_int (getSeverity) failed.");
1329     return (-1);
1330   }
1331   n->severity = (int) tmp_int;
1332
1333   return (0);
1334 } /* }}} int jtoc_notification */
1335 /*
1336  * Functions accessible from Java
1337  */
1338 static jint JNICALL cjni_api_dispatch_values (JNIEnv *jvm_env, /* {{{ */
1339     jobject this, jobject java_vl)
1340 {
1341   value_list_t vl = VALUE_LIST_INIT;
1342   int status;
1343
1344   DEBUG ("cjni_api_dispatch_values: java_vl = %p;", (void *) java_vl);
1345
1346   status = jtoc_value_list (jvm_env, &vl, java_vl);
1347   if (status != 0)
1348   {
1349     ERROR ("java plugin: cjni_api_dispatch_values: jtoc_value_list failed.");
1350     return (-1);
1351   }
1352
1353   status = plugin_dispatch_values (&vl);
1354
1355   sfree (vl.values);
1356
1357   return (status);
1358 } /* }}} jint cjni_api_dispatch_values */
1359
1360 static jint JNICALL cjni_api_dispatch_notification (JNIEnv *jvm_env, /* {{{ */
1361     jobject this, jobject o_notification)
1362 {
1363   notification_t n = { 0 };
1364   int status;
1365
1366   status = jtoc_notification (jvm_env, &n, o_notification);
1367   if (status != 0)
1368   {
1369     ERROR ("java plugin: cjni_api_dispatch_notification: jtoc_notification failed.");
1370     return (-1);
1371   }
1372
1373   status = plugin_dispatch_notification (&n);
1374
1375   return (status);
1376 } /* }}} jint cjni_api_dispatch_notification */
1377
1378 static jobject JNICALL cjni_api_get_ds (JNIEnv *jvm_env, /* {{{ */
1379     jobject this, jobject o_string_type)
1380 {
1381   const char *ds_name;
1382   const data_set_t *ds;
1383   jobject o_dataset;
1384
1385   ds_name = (*jvm_env)->GetStringUTFChars (jvm_env, o_string_type, 0);
1386   if (ds_name == NULL)
1387   {
1388     ERROR ("java plugin: cjni_api_get_ds: GetStringUTFChars failed.");
1389     return (NULL);
1390   }
1391
1392   ds = plugin_get_ds (ds_name);
1393   DEBUG ("java plugin: cjni_api_get_ds: "
1394       "plugin_get_ds (%s) = %p;", ds_name, (void *) ds);
1395
1396   (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_string_type, ds_name);
1397
1398   if (ds == NULL)
1399     return (NULL);
1400
1401   o_dataset = ctoj_data_set (jvm_env, ds);
1402   return (o_dataset);
1403 } /* }}} jint cjni_api_get_ds */
1404
1405 static jint JNICALL cjni_api_register_config (JNIEnv *jvm_env, /* {{{ */
1406     jobject this, jobject o_name, jobject o_config)
1407 {
1408   return (cjni_callback_register (jvm_env, o_name, o_config, CB_TYPE_CONFIG));
1409 } /* }}} jint cjni_api_register_config */
1410
1411 static jint JNICALL cjni_api_register_init (JNIEnv *jvm_env, /* {{{ */
1412     jobject this, jobject o_name, jobject o_config)
1413 {
1414   return (cjni_callback_register (jvm_env, o_name, o_config, CB_TYPE_INIT));
1415 } /* }}} jint cjni_api_register_init */
1416
1417 static jint JNICALL cjni_api_register_read (JNIEnv *jvm_env, /* {{{ */
1418     jobject this, jobject o_name, jobject o_read)
1419 {
1420   cjni_callback_info_t *cbi;
1421
1422   cbi = cjni_callback_info_create (jvm_env, o_name, o_read, CB_TYPE_READ);
1423   if (cbi == NULL)
1424     return (-1);
1425
1426   DEBUG ("java plugin: Registering new read callback: %s", cbi->name);
1427
1428   plugin_register_complex_read (/* group = */ NULL, cbi->name, cjni_read,
1429       /* interval = */ 0, &(user_data_t) {
1430         .data = cbi,
1431         .free_func = cjni_callback_info_destroy,
1432       });
1433
1434   (*jvm_env)->DeleteLocalRef (jvm_env, o_read);
1435
1436   return (0);
1437 } /* }}} jint cjni_api_register_read */
1438
1439 static jint JNICALL cjni_api_register_write (JNIEnv *jvm_env, /* {{{ */
1440     jobject this, jobject o_name, jobject o_write)
1441 {
1442   cjni_callback_info_t *cbi;
1443
1444   cbi = cjni_callback_info_create (jvm_env, o_name, o_write, CB_TYPE_WRITE);
1445   if (cbi == NULL)
1446     return (-1);
1447
1448   DEBUG ("java plugin: Registering new write callback: %s", cbi->name);
1449
1450   plugin_register_write (cbi->name, cjni_write, &(user_data_t) {
1451         .data = cbi,
1452         .free_func = cjni_callback_info_destroy,
1453       });
1454
1455   (*jvm_env)->DeleteLocalRef (jvm_env, o_write);
1456
1457   return (0);
1458 } /* }}} jint cjni_api_register_write */
1459
1460 static jint JNICALL cjni_api_register_flush (JNIEnv *jvm_env, /* {{{ */
1461     jobject this, jobject o_name, jobject o_flush)
1462 {
1463   cjni_callback_info_t *cbi;
1464
1465   cbi = cjni_callback_info_create (jvm_env, o_name, o_flush, CB_TYPE_FLUSH);
1466   if (cbi == NULL)
1467     return (-1);
1468
1469   DEBUG ("java plugin: Registering new flush callback: %s", cbi->name);
1470
1471   plugin_register_flush (cbi->name, cjni_flush, &(user_data_t) {
1472         .data = cbi,
1473         .free_func = cjni_callback_info_destroy,
1474       });
1475
1476   (*jvm_env)->DeleteLocalRef (jvm_env, o_flush);
1477
1478   return (0);
1479 } /* }}} jint cjni_api_register_flush */
1480
1481 static jint JNICALL cjni_api_register_shutdown (JNIEnv *jvm_env, /* {{{ */
1482     jobject this, jobject o_name, jobject o_shutdown)
1483 {
1484   return (cjni_callback_register (jvm_env, o_name, o_shutdown,
1485         CB_TYPE_SHUTDOWN));
1486 } /* }}} jint cjni_api_register_shutdown */
1487
1488 static jint JNICALL cjni_api_register_log (JNIEnv *jvm_env, /* {{{ */
1489     jobject this, jobject o_name, jobject o_log)
1490 {
1491   cjni_callback_info_t *cbi;
1492
1493   cbi = cjni_callback_info_create (jvm_env, o_name, o_log, CB_TYPE_LOG);
1494   if (cbi == NULL)
1495     return (-1);
1496
1497   DEBUG ("java plugin: Registering new log callback: %s", cbi->name);
1498
1499   plugin_register_log (cbi->name, cjni_log, &(user_data_t) {
1500         .data = cbi,
1501         .free_func = cjni_callback_info_destroy,
1502       });
1503
1504   (*jvm_env)->DeleteLocalRef (jvm_env, o_log);
1505
1506   return (0);
1507 } /* }}} jint cjni_api_register_log */
1508
1509 static jint JNICALL cjni_api_register_notification (JNIEnv *jvm_env, /* {{{ */
1510     jobject this, jobject o_name, jobject o_notification)
1511 {
1512   cjni_callback_info_t *cbi;
1513
1514   cbi = cjni_callback_info_create (jvm_env, o_name, o_notification,
1515       CB_TYPE_NOTIFICATION);
1516   if (cbi == NULL)
1517     return (-1);
1518
1519   DEBUG ("java plugin: Registering new notification callback: %s", cbi->name);
1520
1521   plugin_register_notification (cbi->name, cjni_notification, &(user_data_t) {
1522         .data = cbi,
1523         .free_func = cjni_callback_info_destroy,
1524       });
1525
1526   (*jvm_env)->DeleteLocalRef (jvm_env, o_notification);
1527
1528   return (0);
1529 } /* }}} jint cjni_api_register_notification */
1530
1531 static jint JNICALL cjni_api_register_match_target (JNIEnv *jvm_env, /* {{{ */
1532     jobject this, jobject o_name, jobject o_match, int type)
1533 {
1534   int status;
1535   const char *c_name;
1536
1537   c_name = (*jvm_env)->GetStringUTFChars (jvm_env, o_name, 0);
1538   if (c_name == NULL)
1539   {
1540     ERROR ("java plugin: cjni_api_register_match_target: "
1541         "GetStringUTFChars failed.");
1542     return (-1);
1543   }
1544
1545   status = cjni_callback_register (jvm_env, o_name, o_match, type);
1546   if (status != 0)
1547   {
1548     (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1549     return (-1);
1550   }
1551
1552   if (type == CB_TYPE_MATCH)
1553   {
1554     match_proc_t m_proc = { 0 };
1555
1556     m_proc.create  = cjni_match_target_create;
1557     m_proc.destroy = cjni_match_target_destroy;
1558     m_proc.match   = (void *) cjni_match_target_invoke;
1559
1560     status = fc_register_match (c_name, m_proc);
1561   }
1562   else if (type == CB_TYPE_TARGET)
1563   {
1564     target_proc_t t_proc = { 0 };
1565
1566     t_proc.create  = cjni_match_target_create;
1567     t_proc.destroy = cjni_match_target_destroy;
1568     t_proc.invoke  = cjni_match_target_invoke;
1569
1570     status = fc_register_target (c_name, t_proc);
1571   }
1572   else
1573   {
1574     ERROR ("java plugin: cjni_api_register_match_target: "
1575         "Don't know whether to create a match or a target.");
1576     (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1577     return (-1);
1578   }
1579
1580   if (status != 0)
1581   {
1582     ERROR ("java plugin: cjni_api_register_match_target: "
1583         "%s failed.",
1584         (type == CB_TYPE_MATCH) ? "fc_register_match" : "fc_register_target");
1585     (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1586     return (-1);
1587   }
1588
1589   (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1590
1591   return (0);
1592 } /* }}} jint cjni_api_register_match_target */
1593
1594 static jint JNICALL cjni_api_register_match (JNIEnv *jvm_env, /* {{{ */
1595     jobject this, jobject o_name, jobject o_match)
1596 {
1597   return (cjni_api_register_match_target (jvm_env, this, o_name, o_match,
1598         CB_TYPE_MATCH));
1599 } /* }}} jint cjni_api_register_match */
1600
1601 static jint JNICALL cjni_api_register_target (JNIEnv *jvm_env, /* {{{ */
1602     jobject this, jobject o_name, jobject o_target)
1603 {
1604   return (cjni_api_register_match_target (jvm_env, this, o_name, o_target,
1605         CB_TYPE_TARGET));
1606 } /* }}} jint cjni_api_register_target */
1607
1608 static void JNICALL cjni_api_log (JNIEnv *jvm_env, /* {{{ */
1609     jobject this, jint severity, jobject o_message)
1610 {
1611   const char *c_str;
1612
1613   c_str = (*jvm_env)->GetStringUTFChars (jvm_env, o_message, 0);
1614   if (c_str == NULL)
1615   {
1616     ERROR ("java plugin: cjni_api_log: GetStringUTFChars failed.");
1617     return;
1618   }
1619
1620   if (severity < LOG_ERR)
1621     severity = LOG_ERR;
1622   if (severity > LOG_DEBUG)
1623     severity = LOG_DEBUG;
1624
1625   plugin_log (severity, "%s", c_str);
1626
1627   (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_message, c_str);
1628 } /* }}} void cjni_api_log */
1629
1630 static jstring JNICALL cjni_api_get_hostname (JNIEnv *jvm_env, jobject this)
1631 {
1632     return ctoj_output_string(jvm_env, hostname_g);
1633 }
1634
1635 /* List of ``native'' functions, i. e. C-functions that can be called from
1636  * Java. */
1637 static JNINativeMethod jni_api_functions[] = /* {{{ */
1638 {
1639   { "dispatchValues",
1640     "(Lorg/collectd/api/ValueList;)I",
1641     cjni_api_dispatch_values },
1642
1643   { "dispatchNotification",
1644     "(Lorg/collectd/api/Notification;)I",
1645     cjni_api_dispatch_notification },
1646
1647   { "getDS",
1648     "(Ljava/lang/String;)Lorg/collectd/api/DataSet;",
1649     cjni_api_get_ds },
1650
1651   { "registerConfig",
1652     "(Ljava/lang/String;Lorg/collectd/api/CollectdConfigInterface;)I",
1653     cjni_api_register_config },
1654
1655   { "registerInit",
1656     "(Ljava/lang/String;Lorg/collectd/api/CollectdInitInterface;)I",
1657     cjni_api_register_init },
1658
1659   { "registerRead",
1660     "(Ljava/lang/String;Lorg/collectd/api/CollectdReadInterface;)I",
1661     cjni_api_register_read },
1662
1663   { "registerWrite",
1664     "(Ljava/lang/String;Lorg/collectd/api/CollectdWriteInterface;)I",
1665     cjni_api_register_write },
1666
1667   { "registerFlush",
1668     "(Ljava/lang/String;Lorg/collectd/api/CollectdFlushInterface;)I",
1669     cjni_api_register_flush },
1670
1671   { "registerShutdown",
1672     "(Ljava/lang/String;Lorg/collectd/api/CollectdShutdownInterface;)I",
1673     cjni_api_register_shutdown },
1674
1675   { "registerLog",
1676     "(Ljava/lang/String;Lorg/collectd/api/CollectdLogInterface;)I",
1677     cjni_api_register_log },
1678
1679   { "registerNotification",
1680     "(Ljava/lang/String;Lorg/collectd/api/CollectdNotificationInterface;)I",
1681     cjni_api_register_notification },
1682
1683   { "registerMatch",
1684     "(Ljava/lang/String;Lorg/collectd/api/CollectdMatchFactoryInterface;)I",
1685     cjni_api_register_match },
1686
1687   { "registerTarget",
1688     "(Ljava/lang/String;Lorg/collectd/api/CollectdTargetFactoryInterface;)I",
1689     cjni_api_register_target },
1690
1691   { "log",
1692     "(ILjava/lang/String;)V",
1693     cjni_api_log },
1694
1695   { "getHostname",
1696     "()Ljava/lang/String;",
1697     cjni_api_get_hostname },
1698
1699 };
1700 static size_t jni_api_functions_num = sizeof (jni_api_functions)
1701   / sizeof (jni_api_functions[0]);
1702 /* }}} */
1703
1704 /*
1705  * Functions
1706  */
1707 /* Allocate a `cjni_callback_info_t' given the type and objects necessary for
1708  * all registration functions. */
1709 static cjni_callback_info_t *cjni_callback_info_create (JNIEnv *jvm_env, /* {{{ */
1710     jobject o_name, jobject o_callback, int type)
1711 {
1712   const char *c_name;
1713   cjni_callback_info_t *cbi;
1714   const char *method_name;
1715   const char *method_signature;
1716
1717   switch (type)
1718   {
1719     case CB_TYPE_CONFIG:
1720       method_name = "config";
1721       method_signature = "(Lorg/collectd/api/OConfigItem;)I";
1722       break;
1723
1724     case CB_TYPE_INIT:
1725       method_name = "init";
1726       method_signature = "()I";
1727       break;
1728
1729     case CB_TYPE_READ:
1730       method_name = "read";
1731       method_signature = "()I";
1732       break;
1733
1734     case CB_TYPE_WRITE:
1735       method_name = "write";
1736       method_signature = "(Lorg/collectd/api/ValueList;)I";
1737       break;
1738
1739     case CB_TYPE_FLUSH:
1740       method_name = "flush";
1741       method_signature = "(Ljava/lang/Number;Ljava/lang/String;)I";
1742       break;
1743
1744     case CB_TYPE_SHUTDOWN:
1745       method_name = "shutdown";
1746       method_signature = "()I";
1747       break;
1748
1749     case CB_TYPE_LOG:
1750       method_name = "log";
1751       method_signature = "(ILjava/lang/String;)V";
1752       break;
1753
1754     case CB_TYPE_NOTIFICATION:
1755       method_name = "notification";
1756       method_signature = "(Lorg/collectd/api/Notification;)I";
1757       break;
1758
1759     case CB_TYPE_MATCH:
1760       method_name = "createMatch";
1761       method_signature = "(Lorg/collectd/api/OConfigItem;)"
1762         "Lorg/collectd/api/CollectdMatchInterface;";
1763       break;
1764
1765     case CB_TYPE_TARGET:
1766       method_name = "createTarget";
1767       method_signature = "(Lorg/collectd/api/OConfigItem;)"
1768         "Lorg/collectd/api/CollectdTargetInterface;";
1769       break;
1770
1771     default:
1772       ERROR ("java plugin: cjni_callback_info_create: Unknown type: %#x",
1773           type);
1774       return (NULL);
1775   }
1776
1777   c_name = (*jvm_env)->GetStringUTFChars (jvm_env, o_name, 0);
1778   if (c_name == NULL)
1779   {
1780     ERROR ("java plugin: cjni_callback_info_create: "
1781         "GetStringUTFChars failed.");
1782     return (NULL);
1783   }
1784
1785   cbi = calloc (1, sizeof (*cbi));
1786   if (cbi == NULL)
1787   {
1788     ERROR ("java plugin: cjni_callback_info_create: calloc failed.");
1789     (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1790     return (NULL);
1791   }
1792   cbi->type = type;
1793
1794   cbi->name = strdup (c_name);
1795   if (cbi->name == NULL)
1796   {
1797     pthread_mutex_unlock (&java_callbacks_lock);
1798     ERROR ("java plugin: cjni_callback_info_create: strdup failed.");
1799     (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1800     sfree (cbi);
1801     return (NULL);
1802   }
1803
1804   (*jvm_env)->ReleaseStringUTFChars (jvm_env, o_name, c_name);
1805
1806   cbi->object = (*jvm_env)->NewGlobalRef (jvm_env, o_callback);
1807   if (cbi->object == NULL)
1808   {
1809     ERROR ("java plugin: cjni_callback_info_create: NewGlobalRef failed.");
1810     sfree (cbi->name);
1811     sfree (cbi);
1812     return (NULL);
1813   }
1814
1815   cbi->class  = (*jvm_env)->GetObjectClass (jvm_env, cbi->object);
1816   if (cbi->class == NULL)
1817   {
1818     ERROR ("java plugin: cjni_callback_info_create: GetObjectClass failed.");
1819     (*jvm_env)->DeleteGlobalRef (jvm_env, cbi->object);
1820     sfree (cbi->name);
1821     sfree (cbi);
1822     return (NULL);
1823   }
1824
1825   cbi->method = (*jvm_env)->GetMethodID (jvm_env, cbi->class,
1826       method_name, method_signature);
1827   if (cbi->method == NULL)
1828   {
1829     ERROR ("java plugin: cjni_callback_info_create: "
1830         "Cannot find the `%s' method with signature `%s'.",
1831         method_name, method_signature);
1832     (*jvm_env)->DeleteGlobalRef (jvm_env, cbi->object);
1833     sfree (cbi->name);
1834     sfree (cbi);
1835     return (NULL);
1836   }
1837
1838   return (cbi);
1839 } /* }}} cjni_callback_info_t cjni_callback_info_create */
1840
1841 /* Allocate a `cjni_callback_info_t' via `cjni_callback_info_create' and add it
1842  * to the global `java_callbacks' variable. This is used for `config', `init',
1843  * and `shutdown' callbacks. */
1844 static int cjni_callback_register (JNIEnv *jvm_env, /* {{{ */
1845     jobject o_name, jobject o_callback, int type)
1846 {
1847   cjni_callback_info_t *cbi;
1848   cjni_callback_info_t *tmp;
1849 #if COLLECT_DEBUG
1850   const char *type_str;
1851 #endif
1852
1853   cbi = cjni_callback_info_create (jvm_env, o_name, o_callback, type);
1854   if (cbi == NULL)
1855     return (-1);
1856
1857 #if COLLECT_DEBUG
1858   switch (type)
1859   {
1860     case CB_TYPE_CONFIG:
1861       type_str = "config";
1862       break;
1863
1864     case CB_TYPE_INIT:
1865       type_str = "init";
1866       break;
1867
1868     case CB_TYPE_SHUTDOWN:
1869       type_str = "shutdown";
1870       break;
1871
1872     case CB_TYPE_MATCH:
1873       type_str = "match";
1874       break;
1875
1876     case CB_TYPE_TARGET:
1877       type_str = "target";
1878       break;
1879
1880     default:
1881       type_str = "<unknown>";
1882   }
1883   DEBUG ("java plugin: Registering new %s callback: %s",
1884       type_str, cbi->name);
1885 #endif
1886
1887   pthread_mutex_lock (&java_callbacks_lock);
1888
1889   tmp = realloc (java_callbacks,
1890       (java_callbacks_num + 1) * sizeof (*java_callbacks));
1891   if (tmp == NULL)
1892   {
1893     pthread_mutex_unlock (&java_callbacks_lock);
1894     ERROR ("java plugin: cjni_callback_register: realloc failed.");
1895
1896     (*jvm_env)->DeleteGlobalRef (jvm_env, cbi->object);
1897     free (cbi);
1898
1899     return (-1);
1900   }
1901   java_callbacks = tmp;
1902   java_callbacks[java_callbacks_num] = *cbi;
1903   java_callbacks_num++;
1904
1905   pthread_mutex_unlock (&java_callbacks_lock);
1906
1907   free (cbi);
1908   return (0);
1909 } /* }}} int cjni_callback_register */
1910
1911 /* Callback for `pthread_key_create'. It frees the data contained in
1912  * `jvm_env_key' and prints a warning if the reference counter is not zero. */
1913 static void cjni_jvm_env_destroy (void *args) /* {{{ */
1914 {
1915   cjni_jvm_env_t *cjni_env;
1916
1917   if (args == NULL)
1918     return;
1919
1920   cjni_env = (cjni_jvm_env_t *) args;
1921
1922   if (cjni_env->reference_counter > 0)
1923   {
1924     ERROR ("java plugin: cjni_jvm_env_destroy: "
1925         "cjni_env->reference_counter = %i;", cjni_env->reference_counter);
1926   }
1927
1928   if (cjni_env->jvm_env != NULL)
1929   {
1930     ERROR ("java plugin: cjni_jvm_env_destroy: cjni_env->jvm_env = %p;",
1931         (void *) cjni_env->jvm_env);
1932   }
1933
1934   /* The pointer is allocated in `cjni_thread_attach' */
1935   free (cjni_env);
1936 } /* }}} void cjni_jvm_env_destroy */
1937
1938 /* Register ``native'' functions with the JVM. Native functions are C-functions
1939  * that can be called by Java code. */
1940 static int cjni_init_native (JNIEnv *jvm_env) /* {{{ */
1941 {
1942   jclass api_class_ptr;
1943   int status;
1944
1945   api_class_ptr = (*jvm_env)->FindClass (jvm_env, "org/collectd/api/Collectd");
1946   if (api_class_ptr == NULL)
1947   {
1948     ERROR ("cjni_init_native: Cannot find the API class \"org.collectd.api"
1949         ".Collectd\". Please set the correct class path "
1950         "using 'JVMArg \"-Djava.class.path=...\"'.");
1951     return (-1);
1952   }
1953
1954   status = (*jvm_env)->RegisterNatives (jvm_env, api_class_ptr,
1955       jni_api_functions, (jint) jni_api_functions_num);
1956   if (status != 0)
1957   {
1958     ERROR ("cjni_init_native: RegisterNatives failed with status %i.", status);
1959     return (-1);
1960   }
1961
1962   return (0);
1963 } /* }}} int cjni_init_native */
1964
1965 /* Create the JVM. This is called when the first thread tries to access the JVM
1966  * via cjni_thread_attach. */
1967 static int cjni_create_jvm (void) /* {{{ */
1968 {
1969   JNIEnv *jvm_env;
1970   JavaVMInitArgs vm_args = { 0 };
1971   JavaVMOption vm_options[jvm_argc];
1972
1973   int status;
1974
1975   if (jvm != NULL)
1976     return (0);
1977
1978   status = pthread_key_create (&jvm_env_key, cjni_jvm_env_destroy);
1979   if (status != 0)
1980   {
1981     ERROR ("java plugin: cjni_create_jvm: pthread_key_create failed "
1982         "with status %i.", status);
1983     return (-1);
1984   }
1985
1986   jvm_env = NULL;
1987
1988   vm_args.version = JNI_VERSION_1_2;
1989   vm_args.options = vm_options;
1990   vm_args.nOptions = (jint) jvm_argc;
1991
1992   for (size_t i = 0; i < jvm_argc; i++)
1993   {
1994     DEBUG ("java plugin: cjni_create_jvm: jvm_argv[%zu] = %s",
1995         i, jvm_argv[i]);
1996     vm_args.options[i].optionString = jvm_argv[i];
1997   }
1998
1999   status = JNI_CreateJavaVM (&jvm, (void *) &jvm_env, (void *) &vm_args);
2000   if (status != 0)
2001   {
2002     ERROR ("java plugin: cjni_create_jvm: "
2003         "JNI_CreateJavaVM failed with status %i.",
2004         status);
2005     return (-1);
2006   }
2007   assert (jvm != NULL);
2008   assert (jvm_env != NULL);
2009
2010   /* Call RegisterNatives */
2011   status = cjni_init_native (jvm_env);
2012   if (status != 0)
2013   {
2014     ERROR ("java plugin: cjni_create_jvm: cjni_init_native failed.");
2015     return (-1);
2016   }
2017
2018   DEBUG ("java plugin: The JVM has been created.");
2019   return (0);
2020 } /* }}} int cjni_create_jvm */
2021
2022 /* Increase the reference counter to the JVM for this thread. If it was zero,
2023  * attach the JVM first. */
2024 static JNIEnv *cjni_thread_attach (void) /* {{{ */
2025 {
2026   cjni_jvm_env_t *cjni_env;
2027   JNIEnv *jvm_env;
2028
2029   /* If we're the first thread to access the JVM, we'll have to create it
2030    * first.. */
2031   if (jvm == NULL)
2032   {
2033     int status;
2034
2035     status = cjni_create_jvm ();
2036     if (status != 0)
2037     {
2038       ERROR ("java plugin: cjni_thread_attach: cjni_create_jvm failed.");
2039       return (NULL);
2040     }
2041   }
2042   assert (jvm != NULL);
2043
2044   cjni_env = pthread_getspecific (jvm_env_key);
2045   if (cjni_env == NULL)
2046   {
2047     /* This pointer is free'd in `cjni_jvm_env_destroy'. */
2048     cjni_env = calloc (1, sizeof (*cjni_env));
2049     if (cjni_env == NULL)
2050     {
2051       ERROR ("java plugin: cjni_thread_attach: calloc failed.");
2052       return (NULL);
2053     }
2054     cjni_env->reference_counter = 0;
2055     cjni_env->jvm_env = NULL;
2056
2057     pthread_setspecific (jvm_env_key, cjni_env);
2058   }
2059
2060   if (cjni_env->reference_counter > 0)
2061   {
2062     cjni_env->reference_counter++;
2063     jvm_env = cjni_env->jvm_env;
2064   }
2065   else
2066   {
2067     int status;
2068     JavaVMAttachArgs args = { 0 };
2069
2070     assert (cjni_env->jvm_env == NULL);
2071
2072     args.version = JNI_VERSION_1_2;
2073
2074     status = (*jvm)->AttachCurrentThread (jvm, (void *) &jvm_env, (void *) &args);
2075     if (status != 0)
2076     {
2077       ERROR ("java plugin: cjni_thread_attach: AttachCurrentThread failed "
2078           "with status %i.", status);
2079       return (NULL);
2080     }
2081
2082     cjni_env->reference_counter = 1;
2083     cjni_env->jvm_env = jvm_env;
2084   }
2085
2086   DEBUG ("java plugin: cjni_thread_attach: cjni_env->reference_counter = %i",
2087       cjni_env->reference_counter);
2088   assert (jvm_env != NULL);
2089   return (jvm_env);
2090 } /* }}} JNIEnv *cjni_thread_attach */
2091
2092 /* Decrease the reference counter of this thread. If it reaches zero, detach
2093  * from the JVM. */
2094 static int cjni_thread_detach (void) /* {{{ */
2095 {
2096   cjni_jvm_env_t *cjni_env;
2097   int status;
2098
2099   cjni_env = pthread_getspecific (jvm_env_key);
2100   if (cjni_env == NULL)
2101   {
2102     ERROR ("java plugin: cjni_thread_detach: pthread_getspecific failed.");
2103     return (-1);
2104   }
2105
2106   assert (cjni_env->reference_counter > 0);
2107   assert (cjni_env->jvm_env != NULL);
2108
2109   cjni_env->reference_counter--;
2110   DEBUG ("java plugin: cjni_thread_detach: cjni_env->reference_counter = %i",
2111       cjni_env->reference_counter);
2112
2113   if (cjni_env->reference_counter > 0)
2114     return (0);
2115
2116   status = (*jvm)->DetachCurrentThread (jvm);
2117   if (status != 0)
2118   {
2119     ERROR ("java plugin: cjni_thread_detach: DetachCurrentThread failed "
2120         "with status %i.", status);
2121   }
2122
2123   cjni_env->reference_counter = 0;
2124   cjni_env->jvm_env = NULL;
2125
2126   return (0);
2127 } /* }}} int cjni_thread_detach */
2128
2129 static int cjni_config_add_jvm_arg (oconfig_item_t *ci) /* {{{ */
2130 {
2131   char **tmp;
2132
2133   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
2134   {
2135     WARNING ("java plugin: `JVMArg' needs exactly one string argument.");
2136     return (-1);
2137   }
2138
2139   if (jvm != NULL)
2140   {
2141     ERROR ("java plugin: All `JVMArg' options MUST appear before all "
2142         "`LoadPlugin' options! The JVM is already started and I have to "
2143         "ignore this argument: %s",
2144         ci->values[0].value.string);
2145     return (-1);
2146   }
2147
2148   tmp = realloc (jvm_argv, sizeof (char *) * (jvm_argc + 1));
2149   if (tmp == NULL)
2150   {
2151     ERROR ("java plugin: realloc failed.");
2152     return (-1);
2153   }
2154   jvm_argv = tmp;
2155
2156   jvm_argv[jvm_argc] = strdup (ci->values[0].value.string);
2157   if (jvm_argv[jvm_argc] == NULL)
2158   {
2159     ERROR ("java plugin: strdup failed.");
2160     return (-1);
2161   }
2162   jvm_argc++;
2163
2164   return (0);
2165 } /* }}} int cjni_config_add_jvm_arg */
2166
2167 static int cjni_config_load_plugin (oconfig_item_t *ci) /* {{{ */
2168 {
2169   JNIEnv *jvm_env;
2170   java_plugin_class_t *class;
2171   jmethodID constructor_id;
2172   jobject tmp_object;
2173
2174   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
2175   {
2176     WARNING ("java plugin: `LoadPlugin' needs exactly one string argument.");
2177     return (-1);
2178   }
2179
2180   jvm_env = cjni_thread_attach ();
2181   if (jvm_env == NULL)
2182     return (-1);
2183
2184   class = realloc (java_classes_list,
2185       (java_classes_list_len + 1) * sizeof (*java_classes_list));
2186   if (class == NULL)
2187   {
2188     ERROR ("java plugin: realloc failed.");
2189     cjni_thread_detach ();
2190     return (-1);
2191   }
2192   java_classes_list = class;
2193   class = java_classes_list + java_classes_list_len;
2194
2195   memset (class, 0, sizeof (*class));
2196   class->name = strdup (ci->values[0].value.string);
2197   if (class->name == NULL)
2198   {
2199     ERROR ("java plugin: strdup failed.");
2200     cjni_thread_detach ();
2201     return (-1);
2202   }
2203   class->class = NULL;
2204   class->object = NULL;
2205
2206   { /* Replace all dots ('.') with slashes ('/'). Dots are usually used
2207        thorough the Java community, but (Sun's) `FindClass' and friends need
2208        slashes. */
2209     for (size_t i = 0; class->name[i] != 0; i++)
2210       if (class->name[i] == '.')
2211         class->name[i] = '/';
2212   }
2213
2214   DEBUG ("java plugin: Loading class %s", class->name);
2215
2216   class->class = (*jvm_env)->FindClass (jvm_env, class->name);
2217   if (class->class == NULL)
2218   {
2219     ERROR ("java plugin: cjni_config_load_plugin: FindClass (%s) failed.",
2220         class->name);
2221     cjni_thread_detach ();
2222     free (class->name);
2223     return (-1);
2224   }
2225
2226   constructor_id = (*jvm_env)->GetMethodID (jvm_env, class->class,
2227       "<init>", "()V");
2228   if (constructor_id == NULL)
2229   {
2230     ERROR ("java plugin: cjni_config_load_plugin: "
2231         "Could not find the constructor for `%s'.",
2232         class->name);
2233     cjni_thread_detach ();
2234     free (class->name);
2235     return (-1);
2236   }
2237
2238   tmp_object = (*jvm_env)->NewObject (jvm_env, class->class,
2239       constructor_id);
2240   if (tmp_object != NULL)
2241     class->object = (*jvm_env)->NewGlobalRef (jvm_env, tmp_object);
2242   else
2243     class->object = NULL;
2244   if (class->object == NULL)
2245   {
2246     ERROR ("java plugin: cjni_config_load_plugin: "
2247         "Could create a new `%s' object.",
2248         class->name);
2249     cjni_thread_detach ();
2250     free (class->name);
2251     return (-1);
2252   }
2253
2254   cjni_thread_detach ();
2255
2256   java_classes_list_len++;
2257
2258   return (0);
2259 } /* }}} int cjni_config_load_plugin */
2260
2261 static int cjni_config_plugin_block (oconfig_item_t *ci) /* {{{ */
2262 {
2263   JNIEnv *jvm_env;
2264   cjni_callback_info_t *cbi;
2265   jobject o_ocitem;
2266   const char *name;
2267
2268   jclass class;
2269   jmethodID method;
2270
2271   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
2272   {
2273     WARNING ("java plugin: `Plugin' blocks "
2274         "need exactly one string argument.");
2275     return (-1);
2276   }
2277
2278   name = ci->values[0].value.string;
2279
2280   cbi = NULL;
2281   for (size_t i = 0; i < java_callbacks_num; i++)
2282   {
2283     if (java_callbacks[i].type != CB_TYPE_CONFIG)
2284       continue;
2285
2286     if (strcmp (name, java_callbacks[i].name) != 0)
2287       continue;
2288
2289     cbi = java_callbacks + i;
2290     break;
2291   }
2292
2293   if (cbi == NULL)
2294   {
2295     NOTICE ("java plugin: Configuration block for `%s' found, but no such "
2296         "configuration callback has been registered. Please make sure, the "
2297         "`LoadPlugin' lines precede the `Plugin' blocks.",
2298         name);
2299     return (0);
2300   }
2301
2302   DEBUG ("java plugin: Configuring %s", name);
2303
2304   jvm_env = cjni_thread_attach ();
2305   if (jvm_env == NULL)
2306     return (-1);
2307
2308   o_ocitem = ctoj_oconfig_item (jvm_env, ci);
2309   if (o_ocitem == NULL)
2310   {
2311     ERROR ("java plugin: cjni_config_plugin_block: ctoj_oconfig_item failed.");
2312     cjni_thread_detach ();
2313     return (-1);
2314   }
2315
2316   class = (*jvm_env)->GetObjectClass (jvm_env, cbi->object);
2317   method = (*jvm_env)->GetMethodID (jvm_env, class,
2318       "config", "(Lorg/collectd/api/OConfigItem;)I");
2319
2320   (*jvm_env)->CallIntMethod (jvm_env,
2321       cbi->object, method, o_ocitem);
2322
2323   (*jvm_env)->DeleteLocalRef (jvm_env, o_ocitem);
2324   cjni_thread_detach ();
2325   return (0);
2326 } /* }}} int cjni_config_plugin_block */
2327
2328 static int cjni_config_perform (oconfig_item_t *ci) /* {{{ */
2329 {
2330   int success;
2331   int errors;
2332   int status;
2333
2334   success = 0;
2335   errors = 0;
2336
2337   for (int i = 0; i < ci->children_num; i++)
2338   {
2339     oconfig_item_t *child = ci->children + i;
2340
2341     if (strcasecmp ("JVMArg", child->key) == 0)
2342     {
2343       status = cjni_config_add_jvm_arg (child);
2344       if (status == 0)
2345         success++;
2346       else
2347         errors++;
2348     }
2349     else if (strcasecmp ("LoadPlugin", child->key) == 0)
2350     {
2351       status = cjni_config_load_plugin (child);
2352       if (status == 0)
2353         success++;
2354       else
2355         errors++;
2356     }
2357     else if (strcasecmp ("Plugin", child->key) == 0)
2358     {
2359       status = cjni_config_plugin_block (child);
2360       if (status == 0)
2361         success++;
2362       else
2363         errors++;
2364     }
2365     else
2366     {
2367       WARNING ("java plugin: Option `%s' not allowed here.", child->key);
2368       errors++;
2369     }
2370   }
2371
2372   DEBUG ("java plugin: jvm_argc = %zu;", jvm_argc);
2373   DEBUG ("java plugin: java_classes_list_len = %zu;", java_classes_list_len);
2374
2375   if ((success == 0) && (errors > 0))
2376   {
2377     ERROR ("java plugin: All statements failed.");
2378     return (-1);
2379   }
2380
2381   return (0);
2382 } /* }}} int cjni_config_perform */
2383
2384 /* Copy the children of `ci' to the global `config_block' variable. */
2385 static int cjni_config_callback (oconfig_item_t *ci) /* {{{ */
2386 {
2387   oconfig_item_t *ci_copy;
2388   oconfig_item_t *tmp;
2389
2390   assert (ci != NULL);
2391   if (ci->children_num == 0)
2392     return (0); /* nothing to do */
2393
2394   ci_copy = oconfig_clone (ci);
2395   if (ci_copy == NULL)
2396   {
2397     ERROR ("java plugin: oconfig_clone failed.");
2398     return (-1);
2399   }
2400
2401   if (config_block == NULL)
2402   {
2403     config_block = ci_copy;
2404     return (0);
2405   }
2406
2407   tmp = realloc (config_block->children,
2408       (config_block->children_num + ci_copy->children_num) * sizeof (*tmp));
2409   if (tmp == NULL)
2410   {
2411     ERROR ("java plugin: realloc failed.");
2412     oconfig_free (ci_copy);
2413     return (-1);
2414   }
2415   config_block->children = tmp;
2416
2417   /* Copy the pointers */
2418   memcpy (config_block->children + config_block->children_num,
2419       ci_copy->children,
2420       ci_copy->children_num * sizeof (*ci_copy->children));
2421   config_block->children_num += ci_copy->children_num;
2422
2423   /* Delete the pointers from the copy, so `oconfig_free' can't free them. */
2424   memset (ci_copy->children, 0,
2425       ci_copy->children_num * sizeof (*ci_copy->children));
2426   ci_copy->children_num = 0;
2427
2428   oconfig_free (ci_copy);
2429
2430   return (0);
2431 } /* }}} int cjni_config_callback */
2432
2433 /* Free the data contained in the `user_data_t' pointer passed to `cjni_read'
2434  * and `cjni_write'. In particular, delete the global reference to the Java
2435  * object. */
2436 static void cjni_callback_info_destroy (void *arg) /* {{{ */
2437 {
2438   JNIEnv *jvm_env;
2439   cjni_callback_info_t *cbi;
2440
2441   DEBUG ("java plugin: cjni_callback_info_destroy (arg = %p);", arg);
2442
2443   cbi = (cjni_callback_info_t *) arg;
2444
2445   /* This condition can occur when shutting down. */
2446   if (jvm == NULL)
2447   {
2448     sfree (cbi);
2449     return;
2450   }
2451
2452   if (arg == NULL)
2453     return;
2454
2455   jvm_env = cjni_thread_attach ();
2456   if (jvm_env == NULL)
2457   {
2458     ERROR ("java plugin: cjni_callback_info_destroy: cjni_thread_attach failed.");
2459     return;
2460   }
2461
2462   (*jvm_env)->DeleteGlobalRef (jvm_env, cbi->object);
2463
2464   cbi->method = NULL;
2465   cbi->object = NULL;
2466   cbi->class  = NULL;
2467   free (cbi);
2468
2469   cjni_thread_detach ();
2470 } /* }}} void cjni_callback_info_destroy */
2471
2472 /* Call the CB_TYPE_READ callback pointed to by the `user_data_t' pointer. */
2473 static int cjni_read (user_data_t *ud) /* {{{ */
2474 {
2475   JNIEnv *jvm_env;
2476   cjni_callback_info_t *cbi;
2477   int ret_status;
2478
2479   if (jvm == NULL)
2480   {
2481     ERROR ("java plugin: cjni_read: jvm == NULL");
2482     return (-1);
2483   }
2484
2485   if ((ud == NULL) || (ud->data == NULL))
2486   {
2487     ERROR ("java plugin: cjni_read: Invalid user data.");
2488     return (-1);
2489   }
2490
2491   jvm_env = cjni_thread_attach ();
2492   if (jvm_env == NULL)
2493     return (-1);
2494
2495   cbi = (cjni_callback_info_t *) ud->data;
2496
2497   ret_status = (*jvm_env)->CallIntMethod (jvm_env, cbi->object,
2498       cbi->method);
2499
2500   cjni_thread_detach ();
2501   return (ret_status);
2502 } /* }}} int cjni_read */
2503
2504 /* Call the CB_TYPE_WRITE callback pointed to by the `user_data_t' pointer. */
2505 static int cjni_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
2506     user_data_t *ud)
2507 {
2508   JNIEnv *jvm_env;
2509   cjni_callback_info_t *cbi;
2510   jobject vl_java;
2511   int ret_status;
2512
2513   if (jvm == NULL)
2514   {
2515     ERROR ("java plugin: cjni_write: jvm == NULL");
2516     return (-1);
2517   }
2518
2519   if ((ud == NULL) || (ud->data == NULL))
2520   {
2521     ERROR ("java plugin: cjni_write: Invalid user data.");
2522     return (-1);
2523   }
2524
2525   jvm_env = cjni_thread_attach ();
2526   if (jvm_env == NULL)
2527     return (-1);
2528
2529   cbi = (cjni_callback_info_t *) ud->data;
2530
2531   vl_java = ctoj_value_list (jvm_env, ds, vl);
2532   if (vl_java == NULL)
2533   {
2534     ERROR ("java plugin: cjni_write: ctoj_value_list failed.");
2535     cjni_thread_detach ();
2536     return (-1);
2537   }
2538
2539   ret_status = (*jvm_env)->CallIntMethod (jvm_env,
2540       cbi->object, cbi->method, vl_java);
2541
2542   (*jvm_env)->DeleteLocalRef (jvm_env, vl_java);
2543
2544   cjni_thread_detach ();
2545   return (ret_status);
2546 } /* }}} int cjni_write */
2547
2548 /* Call the CB_TYPE_FLUSH callback pointed to by the `user_data_t' pointer. */
2549 static int cjni_flush (cdtime_t timeout, const char *identifier, /* {{{ */
2550     user_data_t *ud)
2551 {
2552   JNIEnv *jvm_env;
2553   cjni_callback_info_t *cbi;
2554   jobject o_timeout;
2555   jobject o_identifier;
2556   int ret_status;
2557
2558   if (jvm == NULL)
2559   {
2560     ERROR ("java plugin: cjni_flush: jvm == NULL");
2561     return (-1);
2562   }
2563
2564   if ((ud == NULL) || (ud->data == NULL))
2565   {
2566     ERROR ("java plugin: cjni_flush: Invalid user data.");
2567     return (-1);
2568   }
2569
2570   jvm_env = cjni_thread_attach ();
2571   if (jvm_env == NULL)
2572     return (-1);
2573
2574   cbi = (cjni_callback_info_t *) ud->data;
2575
2576   o_timeout = ctoj_jdouble_to_number (jvm_env,
2577       (jdouble) CDTIME_T_TO_DOUBLE (timeout));
2578   if (o_timeout == NULL)
2579   {
2580     ERROR ("java plugin: cjni_flush: Converting double "
2581         "to Number object failed.");
2582     cjni_thread_detach ();
2583     return (-1);
2584   }
2585
2586   o_identifier = NULL;
2587   if (identifier != NULL)
2588   {
2589     o_identifier = (*jvm_env)->NewStringUTF (jvm_env, identifier);
2590     if (o_identifier == NULL)
2591     {
2592       (*jvm_env)->DeleteLocalRef (jvm_env, o_timeout);
2593       ERROR ("java plugin: cjni_flush: NewStringUTF failed.");
2594       cjni_thread_detach ();
2595       return (-1);
2596     }
2597   }
2598
2599   ret_status = (*jvm_env)->CallIntMethod (jvm_env,
2600       cbi->object, cbi->method, o_timeout, o_identifier);
2601
2602   (*jvm_env)->DeleteLocalRef (jvm_env, o_identifier);
2603   (*jvm_env)->DeleteLocalRef (jvm_env, o_timeout);
2604
2605   cjni_thread_detach ();
2606   return (ret_status);
2607 } /* }}} int cjni_flush */
2608
2609 /* Call the CB_TYPE_LOG callback pointed to by the `user_data_t' pointer. */
2610 static void cjni_log (int severity, const char *message, /* {{{ */
2611     user_data_t *ud)
2612 {
2613   JNIEnv *jvm_env;
2614   cjni_callback_info_t *cbi;
2615   jobject o_message;
2616
2617   if (jvm == NULL)
2618     return;
2619
2620   if ((ud == NULL) || (ud->data == NULL))
2621     return;
2622
2623   jvm_env = cjni_thread_attach ();
2624   if (jvm_env == NULL)
2625     return;
2626
2627   cbi = (cjni_callback_info_t *) ud->data;
2628
2629   o_message = (*jvm_env)->NewStringUTF (jvm_env, message);
2630   if (o_message == NULL)
2631   {
2632     cjni_thread_detach ();
2633     return;
2634   }
2635
2636   (*jvm_env)->CallVoidMethod (jvm_env,
2637       cbi->object, cbi->method, (jint) severity, o_message);
2638
2639   (*jvm_env)->DeleteLocalRef (jvm_env, o_message);
2640
2641   cjni_thread_detach ();
2642 } /* }}} void cjni_log */
2643
2644 /* Call the CB_TYPE_NOTIFICATION callback pointed to by the `user_data_t'
2645  * pointer. */
2646 static int cjni_notification (const notification_t *n, /* {{{ */
2647     user_data_t *ud)
2648 {
2649   JNIEnv *jvm_env;
2650   cjni_callback_info_t *cbi;
2651   jobject o_notification;
2652   int ret_status;
2653
2654   if (jvm == NULL)
2655   {
2656     ERROR ("java plugin: cjni_read: jvm == NULL");
2657     return (-1);
2658   }
2659
2660   if ((ud == NULL) || (ud->data == NULL))
2661   {
2662     ERROR ("java plugin: cjni_read: Invalid user data.");
2663     return (-1);
2664   }
2665
2666   jvm_env = cjni_thread_attach ();
2667   if (jvm_env == NULL)
2668     return (-1);
2669
2670   cbi = (cjni_callback_info_t *) ud->data;
2671
2672   o_notification = ctoj_notification (jvm_env, n);
2673   if (o_notification == NULL)
2674   {
2675     ERROR ("java plugin: cjni_notification: ctoj_notification failed.");
2676     cjni_thread_detach ();
2677     return (-1);
2678   }
2679
2680   ret_status = (*jvm_env)->CallIntMethod (jvm_env,
2681       cbi->object, cbi->method, o_notification);
2682
2683   (*jvm_env)->DeleteLocalRef (jvm_env, o_notification);
2684
2685   cjni_thread_detach ();
2686   return (ret_status);
2687 } /* }}} int cjni_notification */
2688
2689 /* Callbacks for matches implemented in Java */
2690 static int cjni_match_target_create (const oconfig_item_t *ci, /* {{{ */
2691     void **user_data)
2692 {
2693   JNIEnv *jvm_env;
2694   cjni_callback_info_t *cbi_ret;
2695   cjni_callback_info_t *cbi_factory;
2696   const char *name;
2697   jobject o_ci;
2698   jobject o_tmp;
2699   int type;
2700
2701   cbi_ret = NULL;
2702   o_ci = NULL;
2703   jvm_env = NULL;
2704
2705 #define BAIL_OUT(status) \
2706   if (cbi_ret != NULL) { \
2707     free (cbi_ret->name); \
2708     if ((jvm_env != NULL) && (cbi_ret->object != NULL)) \
2709       (*jvm_env)->DeleteLocalRef (jvm_env, cbi_ret->object); \
2710   } \
2711   free (cbi_ret); \
2712   if (o_ci != NULL) \
2713     (*jvm_env)->DeleteLocalRef (jvm_env, o_ci); \
2714   cjni_thread_detach (); \
2715   return (status)
2716
2717   if (jvm == NULL)
2718   {
2719     ERROR ("java plugin: cjni_read: jvm == NULL");
2720     return (-1);
2721   }
2722
2723   jvm_env = cjni_thread_attach ();
2724   if (jvm_env == NULL)
2725     return (-1);
2726
2727   /* Find out whether to create a match or a target. */
2728   if (strcasecmp ("Match", ci->key) == 0)
2729     type = CB_TYPE_MATCH;
2730   else if (strcasecmp ("Target", ci->key) == 0)
2731     type = CB_TYPE_TARGET;
2732   else
2733   {
2734     ERROR ("java plugin: cjni_match_target_create: Can't figure out whether "
2735         "to create a match or a target.");
2736     BAIL_OUT (-1);
2737   }
2738
2739   /* This is the name of the match we should create. */
2740   name = ci->values[0].value.string;
2741
2742   /* Lets see if we have a matching factory here.. */
2743   cbi_factory = NULL;
2744   for (size_t i = 0; i < java_callbacks_num; i++)
2745   {
2746     if (java_callbacks[i].type != type)
2747       continue;
2748
2749     if (strcmp (name, java_callbacks[i].name) != 0)
2750       continue;
2751
2752     cbi_factory = java_callbacks + i;
2753     break;
2754   }
2755
2756   /* Nope, no factory for that name.. */
2757   if (cbi_factory == NULL)
2758   {
2759     ERROR ("java plugin: cjni_match_target_create: "
2760         "No such match factory registered: %s",
2761         name);
2762     BAIL_OUT (-1);
2763   }
2764
2765   /* We convert `ci' to its Java equivalent.. */
2766   o_ci = ctoj_oconfig_item (jvm_env, ci);
2767   if (o_ci == NULL)
2768   {
2769     ERROR ("java plugin: cjni_match_target_create: "
2770         "ctoj_oconfig_item failed.");
2771     BAIL_OUT (-1);
2772   }
2773
2774   /* Allocate a new callback info structure. This is going to be our user_data
2775    * pointer. */
2776   cbi_ret = calloc (1, sizeof (*cbi_ret));
2777   if (cbi_ret == NULL)
2778   {
2779     ERROR ("java plugin: cjni_match_target_create: calloc failed.");
2780     BAIL_OUT (-1);
2781   }
2782
2783   cbi_ret->object = NULL;
2784   cbi_ret->type = type;
2785
2786   /* Lets fill the callback info structure.. First, the name: */
2787   cbi_ret->name = strdup (name);
2788   if (cbi_ret->name == NULL)
2789   {
2790     ERROR ("java plugin: cjni_match_target_create: strdup failed.");
2791     BAIL_OUT (-1);
2792   }
2793
2794   /* Then call the factory method so it creates a new object for us. */
2795   o_tmp = (*jvm_env)->CallObjectMethod (jvm_env,
2796       cbi_factory->object, cbi_factory->method, o_ci);
2797   if (o_tmp == NULL)
2798   {
2799     ERROR ("java plugin: cjni_match_target_create: CallObjectMethod failed.");
2800     BAIL_OUT (-1);
2801   }
2802
2803   cbi_ret->object = (*jvm_env)->NewGlobalRef (jvm_env, o_tmp);
2804   if (o_tmp == NULL)
2805   {
2806     ERROR ("java plugin: cjni_match_target_create: NewGlobalRef failed.");
2807     BAIL_OUT (-1);
2808   }
2809
2810   /* This is the class of the match. It is possibly different from the class of
2811    * the match-factory! */
2812   cbi_ret->class = (*jvm_env)->GetObjectClass (jvm_env, cbi_ret->object);
2813   if (cbi_ret->class == NULL)
2814   {
2815     ERROR ("java plugin: cjni_match_target_create: GetObjectClass failed.");
2816     BAIL_OUT (-1);
2817   }
2818
2819   /* Lookup the `int match (DataSet, ValueList)' method. */
2820   cbi_ret->method = (*jvm_env)->GetMethodID (jvm_env, cbi_ret->class,
2821       /* method name = */ (type == CB_TYPE_MATCH) ? "match" : "invoke",
2822       "(Lorg/collectd/api/DataSet;Lorg/collectd/api/ValueList;)I");
2823   if (cbi_ret->method == NULL)
2824   {
2825     ERROR ("java plugin: cjni_match_target_create: GetMethodID failed.");
2826     BAIL_OUT (-1);
2827   }
2828
2829   /* Return the newly created match via the user_data pointer. */
2830   *user_data = (void *) cbi_ret;
2831
2832   cjni_thread_detach ();
2833
2834   DEBUG ("java plugin: cjni_match_target_create: "
2835       "Successfully created a `%s' %s.",
2836       cbi_ret->name, (type == CB_TYPE_MATCH) ? "match" : "target");
2837
2838   /* Success! */
2839   return (0);
2840 #undef BAIL_OUT
2841 } /* }}} int cjni_match_target_create */
2842
2843 static int cjni_match_target_destroy (void **user_data) /* {{{ */
2844 {
2845   cjni_callback_info_destroy (*user_data);
2846   *user_data = NULL;
2847
2848   return (0);
2849 } /* }}} int cjni_match_target_destroy */
2850
2851 static int cjni_match_target_invoke (const data_set_t *ds, /* {{{ */
2852     value_list_t *vl, notification_meta_t **meta, void **user_data)
2853 {
2854   JNIEnv *jvm_env;
2855   cjni_callback_info_t *cbi;
2856   jobject o_vl;
2857   jobject o_ds;
2858   int ret_status;
2859   int status;
2860
2861   if (jvm == NULL)
2862   {
2863     ERROR ("java plugin: cjni_match_target_invoke: jvm == NULL");
2864     return (-1);
2865   }
2866
2867   jvm_env = cjni_thread_attach ();
2868   if (jvm_env == NULL)
2869     return (-1);
2870
2871   cbi = (cjni_callback_info_t *) *user_data;
2872
2873   o_vl = ctoj_value_list (jvm_env, ds, vl);
2874   if (o_vl == NULL)
2875   {
2876     ERROR ("java plugin: cjni_match_target_invoke: ctoj_value_list failed.");
2877     cjni_thread_detach ();
2878     return (-1);
2879   }
2880
2881   o_ds = ctoj_data_set (jvm_env, ds);
2882   if (o_ds == NULL)
2883   {
2884     ERROR ("java plugin: cjni_match_target_invoke: ctoj_value_list failed.");
2885     cjni_thread_detach ();
2886     return (-1);
2887   }
2888
2889   ret_status = (*jvm_env)->CallIntMethod (jvm_env, cbi->object, cbi->method,
2890       o_ds, o_vl);
2891
2892   DEBUG ("java plugin: cjni_match_target_invoke: Method returned %i.", ret_status);
2893
2894   /* If we're executing a target, copy the `ValueList' back to our
2895    * `value_list_t'. */
2896   if (cbi->type == CB_TYPE_TARGET)
2897   {
2898     value_list_t new_vl = { 0 };
2899
2900     status = jtoc_value_list (jvm_env, &new_vl, o_vl);
2901     if (status != 0)
2902     {
2903       ERROR ("java plugin: cjni_match_target_invoke: "
2904           "jtoc_value_list failed.");
2905     }
2906     else /* if (status == 0) */
2907     {
2908       /* plugin_dispatch_values assures that this is dynamically allocated
2909        * memory. */
2910       sfree (vl->values);
2911
2912       /* This will replace the vl->values pointer to a new, dynamically
2913        * allocated piece of memory. */
2914       memcpy (vl, &new_vl, sizeof (*vl));
2915     }
2916   } /* if (cbi->type == CB_TYPE_TARGET) */
2917
2918   cjni_thread_detach ();
2919   return (ret_status);
2920 } /* }}} int cjni_match_target_invoke */
2921
2922 /* Iterate over `java_callbacks' and call all CB_TYPE_INIT callbacks. */
2923 static int cjni_init_plugins (JNIEnv *jvm_env) /* {{{ */
2924 {
2925   int status;
2926
2927   for (size_t i = 0; i < java_callbacks_num; i++)
2928   {
2929     if (java_callbacks[i].type != CB_TYPE_INIT)
2930       continue;
2931
2932     DEBUG ("java plugin: Initializing %s", java_callbacks[i].name);
2933
2934     status = (*jvm_env)->CallIntMethod (jvm_env,
2935         java_callbacks[i].object, java_callbacks[i].method);
2936     if (status != 0)
2937     {
2938       ERROR ("java plugin: Initializing `%s' failed with status %i. "
2939           "Removing read function.",
2940           java_callbacks[i].name, status);
2941       plugin_unregister_read (java_callbacks[i].name);
2942     }
2943   }
2944
2945   return (0);
2946 } /* }}} int cjni_init_plugins */
2947
2948 /* Iterate over `java_callbacks' and call all CB_TYPE_SHUTDOWN callbacks. */
2949 static int cjni_shutdown_plugins (JNIEnv *jvm_env) /* {{{ */
2950 {
2951   int status;
2952
2953   for (size_t i = 0; i < java_callbacks_num; i++)
2954   {
2955     if (java_callbacks[i].type != CB_TYPE_SHUTDOWN)
2956       continue;
2957
2958     DEBUG ("java plugin: Shutting down %s", java_callbacks[i].name);
2959
2960     status = (*jvm_env)->CallIntMethod (jvm_env,
2961         java_callbacks[i].object, java_callbacks[i].method);
2962     if (status != 0)
2963     {
2964       ERROR ("java plugin: Shutting down `%s' failed with status %i. ",
2965           java_callbacks[i].name, status);
2966     }
2967   }
2968
2969   return (0);
2970 } /* }}} int cjni_shutdown_plugins */
2971
2972
2973 static int cjni_shutdown (void) /* {{{ */
2974 {
2975   JNIEnv *jvm_env;
2976   JavaVMAttachArgs args = { 0 };
2977   int status;
2978
2979   if (jvm == NULL)
2980     return (0);
2981
2982   jvm_env = NULL;
2983   args.version = JNI_VERSION_1_2;
2984
2985   status = (*jvm)->AttachCurrentThread (jvm, (void *) &jvm_env, &args);
2986   if (status != 0)
2987   {
2988     ERROR ("java plugin: cjni_shutdown: AttachCurrentThread failed with status %i.",
2989         status);
2990     return (-1);
2991   }
2992
2993   /* Execute all the shutdown functions registered by plugins. */
2994   cjni_shutdown_plugins (jvm_env);
2995
2996   /* Release all the global references to callback functions */
2997   for (size_t i = 0; i < java_callbacks_num; i++)
2998   {
2999     if (java_callbacks[i].object != NULL)
3000     {
3001       (*jvm_env)->DeleteGlobalRef (jvm_env, java_callbacks[i].object);
3002       java_callbacks[i].object = NULL;
3003     }
3004     sfree (java_callbacks[i].name);
3005   }
3006   java_callbacks_num = 0;
3007   sfree (java_callbacks);
3008
3009   /* Release all the global references to directly loaded classes. */
3010   for (size_t i = 0; i < java_classes_list_len; i++)
3011   {
3012     if (java_classes_list[i].object != NULL)
3013     {
3014       (*jvm_env)->DeleteGlobalRef (jvm_env, java_classes_list[i].object);
3015       java_classes_list[i].object = NULL;
3016     }
3017     sfree (java_classes_list[i].name);
3018   }
3019   java_classes_list_len = 0;
3020   sfree (java_classes_list);
3021
3022   /* Destroy the JVM */
3023   DEBUG ("java plugin: Destroying the JVM.");
3024   (*jvm)->DestroyJavaVM (jvm);
3025   jvm = NULL;
3026   jvm_env = NULL;
3027
3028   pthread_key_delete (jvm_env_key);
3029
3030   /* Free the JVM argument list */
3031   for (size_t i = 0; i < jvm_argc; i++)
3032     sfree (jvm_argv[i]);
3033   jvm_argc = 0;
3034   sfree (jvm_argv);
3035
3036   return (0);
3037 } /* }}} int cjni_shutdown */
3038
3039 /* Initialization: Create a JVM, load all configured classes and call their
3040  * `config' and `init' callback methods. */
3041 static int cjni_init (void) /* {{{ */
3042 {
3043   JNIEnv *jvm_env;
3044
3045   if ((config_block == NULL) && (jvm == NULL))
3046   {
3047     ERROR ("java plugin: cjni_init: No configuration block for "
3048         "the java plugin was found.");
3049     return (-1);
3050   }
3051
3052   if (config_block != NULL)
3053   {
3054     cjni_config_perform (config_block);
3055     oconfig_free (config_block);
3056   }
3057
3058   if (jvm == NULL)
3059   {
3060     ERROR ("java plugin: cjni_init: jvm == NULL");
3061     return (-1);
3062   }
3063
3064   jvm_env = cjni_thread_attach ();
3065   if (jvm_env == NULL)
3066     return (-1);
3067
3068   cjni_init_plugins (jvm_env);
3069
3070   cjni_thread_detach ();
3071   return (0);
3072 } /* }}} int cjni_init */
3073
3074 void module_register (void)
3075 {
3076   plugin_register_complex_config ("java", cjni_config_callback);
3077   plugin_register_init ("java", cjni_init);
3078   plugin_register_shutdown ("java", cjni_shutdown);
3079 } /* void module_register (void) */
3080
3081 /* vim: set sw=2 sts=2 et fdm=marker : */