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