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