forked from elastic/built-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava-codec-plugin.html
717 lines (673 loc) · 41.5 KB
/
java-codec-plugin.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>How to write a Java codec plugin | Logstash Reference [7.0] | Elastic</title>
<meta class="elastic" name="content" content="How to write a Java codec plugin | Logstash Reference [7.0]">
<link rel="home" href="index.html" title="Logstash Reference [7.0]"/>
<link rel="up" href="contributing-java-plugin.html" title="Contributing a Java Plugin"/>
<link rel="prev" href="java-input-plugin.html" title="How to write a Java input plugin"/>
<link rel="next" href="java-filter-plugin.html" title="How to write a Java filter plugin"/>
<meta class="elastic" name="product_version" content="7.0"/>
<meta class="elastic" name="product_name" content="Logstash"/>
<meta class="elastic" name="website_area" content="documentation"/>
<meta name="DC.type" content="Learn/Docs/Logstash/Reference/7.0"/>
<meta name="DC.subject" content="Logstash"/>
<meta name="DC.identifier" content="7.0"/>
<meta name="robots" content="noindex,nofollow"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.optimizely.com/js/18132920325.js"></script>
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<meta name="apple-mobile-web-app-title" content="Elastic">
<meta name="application-name" content="Elastic">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd" />
<meta name="yandex-verification" content="d8a47e95d0972434" />
<meta name="localized" content="true" />
<meta name="st:robots" content="follow,index" />
<meta property="og:image" content="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt280217a63b82a734/6202d3378b1f312528798412/elastic-logo.svg" />
<meta property="og:image:width" content="500" />
<meta property="og:image:height" content="172" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
<link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
<link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
<!-- Give IE8 a fighting chance -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="/guide/static/styles.css" />
</head>
<!--© 2015-2022 Elasticsearch B.V. -->
<!-- All Elastic documentation is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. -->
<!-- http://creativecommons.org/licenses/by-nc-nd/4.0/ -->
<body>
<!-- Google Tag Manager -->
<script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
<!-- End Google Tag Manager -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-12395217-16');
</script>
<!-- Google Tag Manager for GA4 -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-KNJMG2M');</script>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KNJMG2M" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager for GA4-->
<div id='elastic-nav' style="display:none;"></div>
<script src='https://www.elastic.co/elastic-nav.js'></script>
<div class="main-container">
<section id="content" >
<div class="content-wrapper">
<section id="guide" lang="en">
<div class="container-fluid">
<div class="row pb-3">
<div class="col-12 order-2 col-md-4 order-md-1 col-lg-3 h-almost-full-md sticky-top-md" id="left_col">
<!-- The TOC is appended here -->
</div>
<div class="col-12 order-1 col-md-8 order-md-2 col-lg-7 order-lg-2 guide-section" id="middle_col">
<!-- start body -->
<div class="page_header">
<strong>IMPORTANT</strong>: No additional bug fixes or documentation updates
will be released for this version. For the latest information, see the
<a href="../current/index.html">current release documentation</a>.
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="/guide/">Elastic Docs</a></span>
<span class="chevron-right">›</span><span class="breadcrumb-link"><a href="index.html">Logstash Reference [7.0]</a></span>
<span class="chevron-right">›</span><span class="breadcrumb-link"><a href="contributing-java-plugin.html">Contributing a Java Plugin</a></span>
</div>
<div class="navheader">
<span class="prev">
<a href="java-input-plugin.html">« How to write a Java input plugin</a>
</span>
<span class="next">
<a href="java-filter-plugin.html">How to write a Java filter plugin »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title"><a id="java-codec-plugin"></a>How to write a Java codec plugin<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h2>
</div></div></div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>This functionality is in beta and is subject to change. The design and code is less mature than official GA features and is being provided as-is with no warranties. Beta features are not subject to the support SLA of official GA features.</p>
</div>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>Java codecs are currently supported only for Java input and output plugins. They will not work with Ruby
input or output plugins.</p>
</div>
</div>
<p>To develop a new Java codec for Logstash, you write a new Java class that
conforms to the Logstash Java Codecs API, package it, and install it with the
logstash-plugin utility. We’ll go through each of those steps.</p>
<h3><a id="_set_up_your_environment_2"></a>Set up your environment<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h3>
<h4><a id="_copy_the_example_repo_2"></a>Copy the example repo<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>Start by copying the <a href="https://github.com/logstash-plugins/logstash-codec-java_codec_example" class="ulink" target="_top">example codec plugin</a>. The plugin API is currently part of the
Logstash codebase so you must have a local copy of that available. You can
obtain a copy of the Logstash codebase with the following <code class="literal">git</code> command:</p>
<div class="pre_wrapper lang-shell">
<pre class="programlisting prettyprint lang-shell">git clone --branch <branch_name> --single-branch https://github.com/elastic/logstash.git <target_folder></pre>
</div>
<p>The <code class="literal">branch_name</code> should correspond to the version of Logstash containing the
preferred revision of the Java plugin API.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>The beta version of the Java plugin API is available in the <code class="literal">6.7</code>
branch of the Logstash codebase.</p>
</div>
</div>
<p>Specify the <code class="literal">target_folder</code> for your local copy of the Logstash codebase. If you
do not specify <code class="literal">target_folder</code>, it defaults to a new folder called <code class="literal">logstash</code>
under your current folder.</p>
<h4><a id="_generate_the_jar_file_2"></a>Generate the .jar file<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>After you have obtained a copy of the appropriate revision of the Logstash
codebase, you need to compile it to generate the .jar file containing the Java
plugin API. From the root directory of your Logstash codebase ($LS_HOME), you
can compile it with <code class="literal">./gradlew assemble</code> (or <code class="literal">gradlew.bat assemble</code> if you’re
running on Windows). This should produce the
<code class="literal">$LS_HOME/logstash-core/build/libs/logstash-core-x.y.z.jar</code> where <code class="literal">x</code>, <code class="literal">y</code>, and
<code class="literal">z</code> refer to the version of Logstash.</p>
<p>After you have successfully compiled Logstash, you need to tell your Java plugin
where to find the <code class="literal">logstash-core-x.y.z.jar</code> file. Create a new file named
<code class="literal">gradle.properties</code> in the root folder of your plugin project. That file should
have a single line:</p>
<div class="pre_wrapper lang-txt">
<pre class="programlisting prettyprint lang-txt">LOGSTASH_CORE_PATH=<target_folder>/logstash-core</pre>
</div>
<p>where <code class="literal">target_folder</code> is the root folder of your local copy of the Logstash codebase.</p>
<h3><a id="_code_the_plugin_2"></a>Code the plugin<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h3>
<p>The example codec plugin decodes messages separated by a configurable delimiter
and encodes messages by writing their string representation separated by a
delimiter. For example, if the codec were configured with <code class="literal">/</code> as the delimiter,
the input text <code class="literal">event1/event2/</code> would be decoded into two separate events with
<code class="literal">message</code> fields of <code class="literal">event1</code> and <code class="literal">event2</code>, respectively. Note that this is only
an example codec and does not cover all the edge cases that a production-grade
codec should cover.</p>
<p>Let’s look at the main class in that codec filter:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">@LogstashPlugin(name="java_codec_example")
public class JavaCodecExample implements Codec {
public static final PluginConfigSpec<String> DELIMITER_CONFIG =
PluginConfigSpec.stringSetting("delimiter", ",");
private final String id;
private final String delimiter;
private final CharsetEncoder encoder;
private Event currentEncodedEvent;
private CharBuffer currentEncoding;
public JavaCodecExample(final Configuration config, final Context context) {
this(config.get(DELIMITER_CONFIG));
}
private JavaCodecExample(String delimiter) {
this.id = UUID.randomUUID().toString();
this.delimiter = delimiter;
this.encoder = Charset.defaultCharset().newEncoder();
}
@Override
public void decode(ByteBuffer byteBuffer, Consumer<Map<String, Object>> consumer) {
// a not-production-grade delimiter decoder
byte[] byteInput = new byte[byteBuffer.remaining()];
byteBuffer.get(byteInput);
if (byteInput.length > 0) {
String input = new String(byteInput);
String[] split = input.split(delimiter);
for (String s : split) {
Map<String, Object> map = new HashMap<>();
map.put("message", s);
consumer.accept(map);
}
}
}
@Override
public void flush(ByteBuffer byteBuffer, Consumer<Map<String, Object>> consumer) {
// if the codec maintains any internal state such as partially-decoded input, this
// method should flush that state along with any additional input supplied in
// the ByteBuffer
decode(byteBuffer, consumer); // this is a simplistic implementation
}
@Override
public boolean encode(Event event, ByteBuffer buffer) throws EncodeException {
try {
if (currentEncodedEvent != null && event != currentEncodedEvent) {
throw new EncodeException("New event supplied before encoding of previous event was completed");
} else if (currentEncodedEvent == null) {
currentEncoding = CharBuffer.wrap(event.toString() + delimiter);
}
CoderResult result = encoder.encode(currentEncoding, buffer, true);
buffer.flip();
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
currentEncodedEvent = event;
return false;
} else {
currentEncodedEvent = null;
return true;
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public Collection<PluginConfigSpec<?>> configSchema() {
// should return a list of all configuration options for this plugin
return Collections.singletonList(DELIMITER_CONFIG);
}
@Override
public Codec cloneCodec() {
return new JavaCodecExample(this.delimiter);
}
@Override
public String getId() {
return this.id;
}
}</pre>
</div>
<p>Let’s step through and examine each part of that class.</p>
<h4><a id="_class_declaration_6"></a>Class declaration<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">@LogstashPlugin(name="java_codec_example")
public class JavaCodecExample implements Codec {</pre>
</div>
<p>Notes about the class declaration:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<p>All Java plugins must be annotated with the <code class="literal">@LogstashPlugin</code> annotation. Additionally:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
The <code class="literal">name</code> property of the annotation must be supplied and defines the name of the plugin as it will be used
in the Logstash pipeline definition. For example, this codec would be referenced in the codec section of the
an appropriate input or output in the Logstash pipeline defintion as <code class="literal">codec => java_codec_example { }</code>
</li>
<li class="listitem">
The value of the <code class="literal">name</code> property must match the name of the class excluding casing and underscores.
</li>
</ul>
</div>
</li>
<li class="listitem">
The class must implement the <code class="literal">co.elastic.logstash.api.Codec</code> interface.
</li>
</ul>
</div>
<h5><a id="_plugin_settings_2"></a>Plugin settings<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h5>
<p>The snippet below contains both the setting definition and the method referencing it:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">public static final PluginConfigSpec<String> DELIMITER_CONFIG =
PluginConfigSpec.stringSetting("delimiter", ",");
@Override
public Collection<PluginConfigSpec<?>> configSchema() {
return Collections.singletonList(DELIMITER_CONFIG);
}</pre>
</div>
<p>The <code class="literal">PluginConfigSpec</code> class allows developers to specify the settings that a
plugin supports complete with setting name, data type, deprecation status,
required status, and default value. In this example, the <code class="literal">delimiter</code> setting
defines the delimiter on which the codec will split events. It is not a required
setting and if it is not explicitly set, its default value will be <code class="literal">,</code>.</p>
<p>The <code class="literal">configSchema</code> method must return a list of all settings that the plugin
supports. The Logstash execution engine will validate that all required
settings are present and that no unsupported settings are present.</p>
<h5><a id="_constructor_and_initialization_2"></a>Constructor and initialization<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h5>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">private final String id;
private final String delimiter;
private final CharsetEncoder encoder;
public JavaCodecExample(final Configuration config, final Context context) {
this(config.get(DELIMITER_CONFIG));
}
private JavaCodecExample(String delimiter) {
this.id = UUID.randomUUID().toString();
this.delimiter = delimiter;
this.encoder = Charset.defaultCharset().newEncoder();
}</pre>
</div>
<p>All Java codec plugins must have a constructor taking a <code class="literal">Configuration</code> and
<code class="literal">Context</code> argument. This is the constructor that will be used to instantiate
them at runtime. The retrieval and validation of all plugin settings should
occur in this constructor. In this example, the delimiter to be used for
delimiting events is retrieved from its setting and stored in a local variable
so that it can be used later in the <code class="literal">decode</code> and <code class="literal">encode</code> methods. The codec’s
ID is initialized to a random UUID (as should be done for most codecs), and a
local <code class="literal">encoder</code> variable is initialized to encode and decode with a specified
character set.</p>
<p>Any additional initialization may occur in the constructor as well. If there are
any unrecoverable errors encountered in the configuration or initialization of
the codec plugin, a descriptive exception should be thrown. The exception will
be logged and will prevent Logstash from starting.</p>
<h4><a id="_codec_methods"></a>Codec methods<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">@Override
public void decode(ByteBuffer byteBuffer, Consumer<Map<String, Object>> consumer) {
// a not-production-grade delimiter decoder
byte[] byteInput = new byte[byteBuffer.remaining()];
byteBuffer.get(byteInput);
if (byteInput.length > 0) {
String input = new String(byteInput);
String[] split = input.split(delimiter);
for (String s : split) {
Map<String, Object> map = new HashMap<>();
map.put("message", s);
consumer.accept(map);
}
}
}
@Override
public void flush(ByteBuffer byteBuffer, Consumer<Map<String, Object>> consumer) {
decode(byteBuffer, consumer); // this is a simplistic implementation
}
@Override
public boolean encode(Event event, ByteBuffer buffer) throws EncodeException {
try {
if (currentEncodedEvent != null && event != currentEncodedEvent) {
throw new EncodeException("New event supplied before encoding of previous event was completed");
} else if (currentEncodedEvent == null) {
currentEncoding = CharBuffer.wrap(event.toString() + delimiter);
}
CoderResult result = encoder.encode(currentEncoding, buffer, true);
buffer.flip();
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
currentEncodedEvent = event;
return false;
} else {
currentEncodedEvent = null;
return true;
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}</pre>
</div>
<p>The <code class="literal">decode</code>, <code class="literal">flush</code>, and <code class="literal">encode</code> methods provide the core functionality of
the codec. Codecs may be used by inputs to decode a sequence or stream of bytes
into events or by outputs to encode events into a sequence of bytes.</p>
<p>The <code class="literal">decode</code> method decodes events from the specified <code class="literal">ByteBuffer</code> and passes
them to the provided <code class="literal">Consumer</code>. The input must provide a <code class="literal">ByteBuffer</code> that is
ready for reading with <code class="literal">byteBuffer.position()</code> indicating the next position to
read and <code class="literal">byteBuffer.limit()</code> indicating the first byte in the buffer that is
not safe to read. Codecs must ensure that <code class="literal">byteBuffer.position()</code> reflects the
last-read position before returning control to the input. The input is then
responsible for returning the buffer to write mode via either
<code class="literal">byteBuffer.clear()</code> or <code class="literal">byteBuffer.compact()</code> before resuming writes. In the
example above, the <code class="literal">decode</code> method simply splits the incoming byte stream on the
specified delimiter. A production-grade codec such as
<a href="https://github.com/elastic/logstash/blob/6.7/logstash-core/src/main/java/org/logstash/plugins/codecs/Line.java" class="ulink" target="_top"><code class="literal">java-line</code></a>
would not make the simplifying assumption that the end of the supplied byte
stream corresponded with the end of an event.</p>
<p>The <code class="literal">flush</code> method works in coordination with the <code class="literal">decode</code> method to decode all
remaining events from the specified <code class="literal">ByteBuffer</code> along with any internal state
that may remain after previous calls to the <code class="literal">decode</code> method. As an example of
internal state that a codec might maintain, consider an input stream of bytes
<code class="literal">event1/event2/event3</code> with a delimiter of <code class="literal">/</code>. Due to buffering or other
reasons, the input might supply a partial stream of bytes such as <code class="literal">event1/eve</code>
to the codec’s <code class="literal">decode</code> method. In this case, the codec could save the beginning
three characters <code class="literal">eve</code> of the second event rather than assuming that the
supplied byte stream ends on an event boundary. If the next call to <code class="literal">decode</code>
supplied the <code class="literal">nt2/ev</code> bytes, the codec would prepend the saved <code class="literal">eve</code> bytes to
produce the full <code class="literal">event2</code> event and then save the remaining <code class="literal">ev</code> bytes for
decoding when the remainder of the bytes for that event were supplied. A call to
<code class="literal">flush</code> signals the codec that the supplied bytes represent the end of an event
stream and all remaining bytes should be decoded to events. The <code class="literal">flush</code> example
above is a simplistic implementation that does not maintain any state about
partially-supplied byte streams across calls to <code class="literal">decode</code>.</p>
<p>The <code class="literal">encode</code> method encodes an event into a sequence of bytes and writes it into
the specified <code class="literal">ByteBuffer</code>. Under ideal circumstances, the entirety of the
event’s encoding will fit into the supplied buffer. In cases where the buffer
has insufficient space to hold the event’s encoding, the codec must fill the
buffer with as much of the event’s encoding as possible, the <code class="literal">encode</code> must
return <code class="literal">false</code>, and the output must call the <code class="literal">encode</code> method with the same event
and a buffer that has more <code class="literal">buffer.remaining()</code> bytes. The output typically does
that by draining the partial encoding from the supplied buffer. This process
must be repeated until the event’s entire encoding is written to the buffer at
which point the <code class="literal">encode</code> method will return <code class="literal">true</code>. Attempting to call this
method with a new event before the entirety of the previous event’s encoding has
been written to a buffer must result in an <code class="literal">EncodeException</code>. As the coneptual
inverse of the <code class="literal">decode</code> method, the <code class="literal">encode</code> method must return the buffer in a
state from which it can be read, typically by calling <code class="literal">buffer.flip()</code> before
returning. In the example above, the <code class="literal">encode</code> method attempts to write the
event’s encoding to the supplied buffer. If the buffer contains sufficient free
space, the entirety of the event is written and <code class="literal">true</code> is returned. Otherwise,
the method writes as much of the event’s encoding to the buffer as possible,
returns <code class="literal">false</code>, and stores the remainder to be written to the buffer in the
next call to the <code class="literal">encode</code> method.</p>
<h4><a id="_clonecodec_method"></a>cloneCodec method<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">@Override
public Codec cloneCodec() {
return new JavaCodecExample(this.delimiter);
}</pre>
</div>
<p>The <code class="literal">cloneCodec</code> method should return an identical instance of the codec with the exception of its ID. Because codecs
may be stateful across calls to their <code class="literal">decode</code> methods, input plugins that are multi-threaded should use a separate
instance of each codec via the <code class="literal">cloneCodec</code> method for each of their threads. Because a single codec instance is shared
across all pipeline workers in the output stage of the Logstash pipeline, codecs should <em>not</em> retain state across calls
to their <code class="literal">encode</code> methods. In the example above, the codec is cloned with the same delimiter but a different ID.</p>
<h4><a id="_getid_method_2"></a>getId method<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">@Override
public String getId() {
return id;
}</pre>
</div>
<p>For codec plugins, the <code class="literal">getId</code> method should always return the id that was set at instantiation time. This is typically
an UUID.</p>
<h4><a id="_unit_tests_2"></a>Unit tests<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>Lastly, but certainly not least importantly, unit tests are strongly encouraged.
The example codec plugin includes an
<a href="https://github.com/logstash-plugins/logstash-codec-java_codec_example/blob/master/src/test/java/org/logstash/javaapi/JavaCodecExampleTest.java" class="ulink" target="_top">example unit
test</a> that you can use as a template for your own.</p>
<h3><a id="_package_and_deploy_2"></a>Package and deploy<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h3>
<p>Java plugins are packaged as Ruby gems for dependency management and
interoperability with Ruby plugins.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>One of the goals for Java plugin support is to eliminate the need for any
knowledge of Ruby or its toolchain for Java plugin development. Future phases of
the Java plugin project will automate the packaging of Java plugins as Ruby gems
so no direct knowledge of or interaction with Ruby will be required. In the
current phase, Java plugins must still be manually packaged as Ruby gems
and installed with the <code class="literal">logstash-plugin</code> utility.</p>
</div>
</div>
<h4><a id="_compile_to_jar_file_2"></a>Compile to JAR file<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>The Java plugin should be compiled and assembled into a fat jar with the
<code class="literal">vendor</code> task in the Gradle build file. This will package all Java dependencies
into a single jar and write it to the correct folder for later packaging into a
Ruby gem.</p>
<h4><a id="_manually_package_as_ruby_gem_2"></a>Manually package as Ruby gem<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>Several Ruby source files are required to package the jar file as a
Ruby gem. These Ruby files are used only at Logstash startup time to identify
the Java plugin and are not used during runtime event processing.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>These Ruby source files will be automatically generated in a future release.</p>
</div>
</div>
<p><span class="strong strong"><strong><code class="literal">logstash-codec-<codec-name>.gemspec</code></strong></span></p>
<div class="pre_wrapper lang-txt">
<pre class="programlisting prettyprint lang-txt">Gem::Specification.new do |s|
s.name = 'logstash-codec-java_codec_example'
s.version = PLUGIN_VERSION
s.licenses = ['Apache-2.0']
s.summary = "Example codec using Java plugin API"
s.description = ""
s.authors = ['Elasticsearch']
s.email = '[email protected]'
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
s.require_paths = ['lib', 'vendor/jar-dependencies']
# Files
s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"]
# Special flag to let us know this is actually a logstash plugin
s.metadata = { 'logstash_plugin' => 'true', 'logstash_group' => 'codec'}
# Gem dependencies
s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99"
s.add_runtime_dependency 'jar-dependencies'
s.add_development_dependency 'logstash-devutils'
end</pre>
</div>
<p>You can use this file with the following modifications:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<code class="literal">s.name</code> must follow the <code class="literal">logstash-codec-<codec-name></code> pattern
</li>
<li class="listitem">
<code class="literal">s.version</code> must match the <code class="literal">project.version</code> specified in the <code class="literal">build.gradle</code> file.
Both versions should be set to be read from the <code class="literal">VERSION</code> file in this example.
</li>
</ul>
</div>
<p><span class="strong strong"><strong><code class="literal">lib/logstash/codecs/<codec-name>.rb</code></strong></span></p>
<div class="pre_wrapper lang-ruby">
<pre class="programlisting prettyprint lang-ruby"># encoding: utf-8
require "logstash/codecs/base"
require "logstash/namespace"
require "logstash-codec-java_codec_example_jars"
require "java"
class LogStash::Codecs::JavaCodecExample < LogStash::Codecs::Base
config_name "java_codec_example"
def self.javaClass() org.logstash.javaapi.JavaCodecExample.java_class; end
end</pre>
</div>
<p>Modify these items in the file above:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
Change the name to correspond with the codec name.
</li>
<li class="listitem">
Change <code class="literal">require "logstash-codec-java_codec_example_jars"</code> to reference the appropriate "jars" file
as described below.
</li>
<li class="listitem">
Change <code class="literal">class LogStash::Codecs::JavaCodecExample < LogStash::Codecs::Base</code> to provide a unique and
descriptive Ruby class name.
</li>
<li class="listitem">
Change <code class="literal">config_name "java_codec_example"</code> to match the name of the plugin as specified in the <code class="literal">name</code> property of
the <code class="literal">@LogstashPlugin</code> annotation.
</li>
<li class="listitem">
Change <code class="literal">def self.javaClass() org.logstash.javaapi.JavaCodecExample.java_class; end</code> to return the
class of the Java codec.
</li>
</ul>
</div>
<p><span class="strong strong"><strong><code class="literal">lib/logstash-codec-<codec-name>_jars.rb</code></strong></span></p>
<div class="pre_wrapper lang-txt">
<pre class="programlisting prettyprint lang-txt">require 'jar_dependencies'
require_jar('org.logstash.javaapi', 'logstash-codec-java_codec_example', '0.2.0')</pre>
</div>
<p>In the file above:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
Rename the file to correspond to the codec name.
</li>
<li class="listitem">
Change the <code class="literal">require_jar</code> directive to correspond to the <code class="literal">group</code> specified in the
Gradle build file, the name of the codec JAR file, and the version as
specified in both the gemspec and Gradle build file.
</li>
</ul>
</div>
<p>After you have created the previous files and the plugin JAR file, build the gem using the
following command:</p>
<div class="pre_wrapper lang-shell">
<pre class="programlisting prettyprint lang-shell">gem build logstash-codec-<codec-name>.gemspec</pre>
</div>
<h4><a id="_installing_the_java_plugin_in_logstash_2"></a>Installing the Java plugin in Logstash<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h4>
<p>After you have packaged your Java plugin as a Ruby gem, you can install it in
Logstash with this command:</p>
<div class="pre_wrapper lang-shell">
<pre class="programlisting prettyprint lang-shell">bin/logstash-plugin install --no-verify --local /path/to/javaPlugin.gem</pre>
</div>
<p>For Windows platforms: Substitute backslashes for forward slashes as appropriate in the command.</p>
<h3><a id="_run_logstash_with_the_java_codec_plugin"></a>Run Logstash with the Java codec plugin<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h3>
<p>To test the plugin, start Logstash with:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">echo "foo,bar" | bin/logstash --java-execution -e 'input { java_stdin { codec => java_codec_example } } }'</pre>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>The <code class="literal">--java-execution</code> flag to enable the Java execution engine is required as Java plugins are not supported
in the Ruby execution engine.</p>
</div>
</div>
<p>The expected Logstash output (excluding initialization) with the configuration above is:</p>
<div class="pre_wrapper lang-txt">
<pre class="programlisting prettyprint lang-txt">{
"@version" => "1",
"message" => "foo",
"@timestamp" => yyyy-MM-ddThh:mm:ss.SSSZ,
"host" => "<yourHostName>"
}
{
"@version" => "1",
"message" => "bar\n",
"@timestamp" => yyyy-MM-ddThh:mm:ss.SSSZ,
"host" => "<yourHostName>"
}</pre>
</div>
<h3><a id="_feedback_2"></a>Feedback<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/logstash/edit/7.0/docs/static/contributing-java-plugin.asciidoc">edit</a></h3>
<p>If you have any feedback on Java plugin support in Logstash, please comment on our
<a href="https://github.com/elastic/logstash/issues/9215" class="ulink" target="_top">main Github issue</a> or post in the
<a href="https://discuss.elastic.co/c/logstash" class="ulink" target="_top">Logstash forum</a>.</p>
</div>
<div class="navfooter">
<span class="prev">
<a href="java-input-plugin.html">« How to write a Java input plugin</a>
</span>
<span class="next">
<a href="java-filter-plugin.html">How to write a Java filter plugin »</a>
</span>
</div>
</div>
<!-- end body -->
</div>
<div class="col-12 order-3 col-lg-2 order-lg-3 h-almost-full-lg sticky-top-lg" id="right_col">
<div id="sticky_content">
<!-- The OTP is appended here -->
<div class="row">
<div class="col-0 col-md-4 col-lg-0" id="bottom_left_col"></div>
<div class="col-12 col-md-8 col-lg-12">
<div id="rtpcontainer">
<div class="mktg-promo" id="most-popular">
<p class="aside-heading">Most Popular</p>
<div class="pb-2">
<p class="media-type">Video</p>
<a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&elektra=docs&storm=top-video">
<p class="mb-0">Get Started with Elasticsearch</p>
</a>
</div>
<div class="pb-2">
<p class="media-type">Video</p>
<a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&elektra=docs&storm=top-video">
<p class="mb-0">Intro to Kibana</p>
</a>
</div>
<div class="pb-2">
<p class="media-type">Video</p>
<a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&elektra=docs&storm=top-video">
<p class="mb-0">ELK for Logs & Metrics</p>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
<div id='elastic-footer'></div>
<script src='https://www.elastic.co/elastic-footer.js'></script>
<!-- Footer Section end-->
</section>
</div>
<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
window.initial_state = {}</script>
</body>
</html>