<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eli Segev on Medium]]></title>
        <description><![CDATA[Stories by Eli Segev on Medium]]></description>
        <link>https://medium.com/@elisegev?source=rss-f92aeadd0c29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aO1zEGX_-OfHeYafY61Usw.jpeg</url>
            <title>Stories by Eli Segev on Medium</title>
            <link>https://medium.com/@elisegev?source=rss-f92aeadd0c29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:55:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elisegev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Get a file extension from a URL in Golang]]></title>
            <link>https://elisegev.medium.com/get-a-file-extension-from-a-url-in-golang-5061d4a298a?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/5061d4a298a</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 16:40:53 GMT</pubDate>
            <atom:updated>2022-04-28T16:40:53.236Z</atom:updated>
            <content:encoded><![CDATA[<p>I am presenting a quick code snippet in case anyone else needs a safe way to get the file extension from a URL using Go (Golang). The issue with URLs is that they have many “parts” that using a regular expression might not be the best possible (and readable) way to solve this with. Instead, I am using the standard Go url library to isolate the path (without the host or the query-string), and extract the extension from it.</p><pre>func GetFileExtensionFromUrl(rawUrl string) (string, error) {<br>   u, err := url.Parse(rawUrl)<br>   if err != nil {<br>      return &quot;&quot;, err<br>   }<br>   pos := strings.LastIndex(u.Path, &quot;.&quot;)<br>   if pos == -1 {<br>      return &quot;&quot;, errors.New(&quot;couldn&#39;t find a period to indicate a file extension&quot;)<br>   }<br>   return u.Path[pos+1 : len(u.Path)], nil<br>}</pre><p>Tests:</p><pre>func TestGetFileExtensionFromUrl(t *testing.T) {<br>   tests := []struct{<br>      fullUrl, want string<br>      wantErr bool<br>   }{<br>      {<br>         fullUrl: &quot;https://assets.somedomain.com/assets/files/mypicture.jpg?width=1000&amp;height=600&quot;,<br>         want: &quot;jpg&quot;,<br>         wantErr: false,<br>      }, {<br>         fullUrl: &quot;https://google.com&quot;,<br>         wantErr: true,<br>      },<br>   }<br><br>   for _, tt := range tests {<br>      t.Run(tt.fullUrl, func(t *testing.T) {<br>         ext, err := utils.GetFileExtensionFromUrl(tt.fullUrl)<br>         if tt.wantErr {<br>            assert.NotNil(t, err)<br>         } else {<br>            assert.Nil(t, err)<br>            assert.Equal(t, ext, tt.want)<br>         }<br>      })<br>   }<br>}</pre><p>Tip: if you need the period ( . ) along the returned extension, just change u.Path[pos+1 : len(u.Path)] to u.Path[pos : len(u.Path)]</p><p>This is inspired by <a href="https://stackoverflow.com/a/44570361">https://stackoverflow.com/a/44570361</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5061d4a298a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Druid complex Lookup using other dimensions, with native query or Golang]]></title>
            <link>https://elisegev.medium.com/druid-complex-lookup-using-other-dimensions-with-native-query-or-golang-b421a59154f3?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b421a59154f3</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[druid]]></category>
            <category><![CDATA[lookup-table]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 15:07:46 GMT</pubDate>
            <atom:updated>2022-04-19T10:55:32.723Z</atom:updated>
            <content:encoded><![CDATA[<p>Lookups in Apache Druid are a way to replace values by keys in datasources, without needing to actually change anything in the datasources. This is extremely useful for repeatable data. Common examples are replacing a country-code with the country name, language-code with the language name, and so on.</p><p>For me, a real world example was the need to replace meta-data that a customer might change on distant occasions, without having to update all the respective records in the datasource (because there might be a great amount of them, and it is not efficient to do it every customer update).</p><p>For the ability to update the meta-data on customer demand, it was convenient to create a lookup name for each customer. Then, in the lookup, it was convenient that the keys would be a combination of an ID (which is a dimension of its own) and the meta-data-key.<br>Example:</p><pre>Datasource: items<br>-----------------<br>guid   | customer_id | name  | view_count<br>-------------------------------------<br>guid1  | custA       | page1 | 12<br>guid2  | custA       | page2 | 8<br>guid3  | custB       | page1 | 15<br></pre><pre>Lookup 1: custA_metadata<br>------------------------<br>key              | value<br>------------------------<br>guid1_background | dark<br>guid1_language   | en-US<br>guid2_background | light<br>guid2_language   | he-IL<br></pre><pre>Lookup 2: custB_metadata<br>------------------------<br>key              | value<br>------------------------<br>guid3_background | dark<br>...</pre><p>This guide will demonstrate how to create and fetch this structure in native Druid queries and also with Go (Golang).</p><h3>Creating the lookups</h3><p>To create the lookups, send the following POST request:</p><pre>{<br>  &quot;__default&quot;: {<br>    &quot;custA_metadata&quot;: {<br>      &quot;version&quot;: &quot;1&quot;,<br>      &quot;lookupExtractorFactory&quot;: {<br>        &quot;type&quot;: &quot;map&quot;,<br>        &quot;map&quot;: {<br>          &quot;guid1_background&quot;: &quot;dark&quot;,<br>          &quot;guid1_language&quot;: &quot;en-US&quot;,<br>          &quot;guid2_background&quot;: &quot;light&quot;,<br>          &quot;guid2_language&quot;: &quot;he-IL&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Notice the first json node is__default , which is the default tier (a group of lookups across Druid servers).<br>If you decide to name the tier differently, you will need to update your Druid druid.lookup.lookupTier configuration to that alternate name (<a href="https://druid.apache.org/docs/latest/querying/lookups.html#configuration">read more</a>).</p><p>Now you have a lookup in place. You can repeat this for the other lookup names.</p><h3>Verify that the lookup was successfully created</h3><p>It takes a little time for lookups to propagate across Druid servers. One might need to retry the verification before it returns a successful response.</p><p>Use the following to verify that the lookup update was successful:</p><pre>GET http://localhost:8888/druid/coordinator/v1/lookups/config</pre><p>Use the following to verify that the lookup was propagated successfully:</p><pre>GET http://localhost:8082/druid/listen/v1/lookups</pre><p>Notice the ports are different, intentionally.</p><h3>GroupBy aggregation native query</h3><p>Because the keys in our lookup rely on another dimension (the guid), we can’t use a simple lookup-dimension. Before that, we need to “extract” the guid, and then apply “variations” to it. For this we can utilize the Cascade extraction and apply the lookup extraction-function to it.</p><pre>{<br>    &quot;queryType&quot;: &quot;groupBy&quot;,<br>    &quot;dataSource&quot;: {<br>        &quot;type&quot;: &quot;table&quot;,<br>        &quot;name&quot;: &quot;items&quot;<br>    },<br>    &quot;intervals&quot;: [<br>        &quot;2022-04-16T00:00:00Z/2022-04-16T23:59:59.999999999Z&quot;<br>    ],<br>    &quot;dimensions&quot;: [<br>        {<br>            &quot;type&quot;: &quot;extraction&quot;,<br>            &quot;dimension&quot;: &quot;name&quot;,<br>            &quot;extractionFn&quot;: {<br>                &quot;type&quot;: &quot;stringFormat&quot;,<br>                &quot;format&quot;: &quot;%s&quot;<br>            }<br>        },<br>        {<br>            &quot;type&quot;: &quot;extraction&quot;,<br>            &quot;dimension&quot;: &quot;customer_id&quot;,<br>            &quot;extractionFn&quot;: {<br>                &quot;type&quot;: &quot;stringFormat&quot;,<br>                &quot;format&quot;: &quot;%s&quot;<br>            }<br>        },<br>        {<br>            &quot;type&quot;: &quot;extraction&quot;,<br>            &quot;dimension&quot;: &quot;guid&quot;,<br>            &quot;outputName&quot;: &quot;background&quot;,<br>            &quot;extractionFn&quot;: {<br>                &quot;type&quot;: &quot;cascade&quot;,<br>                &quot;extractionFns&quot;: [<br>                    {<br>                        &quot;type&quot;: &quot;stringFormat&quot;,<br>                        &quot;format&quot;: &quot;%s_background&quot;<br>                    },<br>                    {<br>                        &quot;type&quot;: &quot;registeredLookup&quot;,<br>                        &quot;lookup&quot;: &quot;custA_metadata&quot;,<br>                        &quot;retainMissingValue&quot;: true<br>                    }<br>                ]<br>            }<br>        }<br>    ],<br>    &quot;filter&quot;: {<br>        &quot;type&quot;: &quot;and&quot;,<br>        &quot;fields&quot;: [<br>            {<br>                &quot;type&quot;: &quot;in&quot;,<br>                &quot;dimension&quot;: &quot;guid&quot;,<br>                &quot;values&quot;: [<br>                    &quot;en-US&quot;<br>                ],<br>                &quot;extractionFn&quot;: {<br>                    &quot;type&quot;: &quot;cascade&quot;,<br>                    &quot;extractionFns&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;stringFormat&quot;,<br>                            &quot;format&quot;: &quot;%s_language&quot;<br>                        },<br>                        {<br>                            &quot;type&quot;: &quot;registeredLookup&quot;,<br>                            &quot;lookup&quot;: &quot;custA_metadata&quot;,<br>                            &quot;retainMissingValue&quot;: true<br>                        }<br>                    ]<br>                }<br>            }<br>        ]<br>    },<br>    &quot;granularity&quot;: &quot;all&quot;,<br>    &quot;aggregations&quot;: [],<br>    &quot;postAggregations&quot;: []<br>}</pre><p>How does it work, both in the dimensions and the filters? We declare our object with type “dimension” or “in” and request to get the guid dimension. Then we apply the cascade extraction function, and then apply two functions: the first will transform the guid to the key in the lookup (e.g. &lt;guid&gt;_background ) and the second will use the transformation result and get it from the lookup. I use retainMissingValue: true but of course you can drop it if it suits you.</p><p>Notice that the dimension has an outputName , which will be the name of the looked-up-dimension in the response.<br>And the filter has a values:[...] , which contains the values to filter by <em>in the lookup</em>.</p><p>Thank you Avi Rogalsky for this.</p><h3>GroupBy fetch with Go</h3><p>As explained above, we need to utilize the Cascade extraction.</p><p>With the <a href="https://github.com/grafadruid/go-druid/">grafadruid/go-druid</a> Go library, we can use these:</p><pre>dimensions := []builder.Dimension{<br> dimension.NewExtraction().<br> SetDimension(&quot;guid&quot;).<br> SetOutputName(&quot;background&quot;).<br> SetExtractionFn(extractionfn.NewCascade().<br>  SetExtractionFns([]builder.ExtractionFn{<br>    extractionfn.NewStringFormat().SetFormat(&quot;%s_background&quot;),<br>    extractionfn.NewRegisteredLookup().SetLookup(&quot;custA_metadata&quot;).<br>     SetRetainMissingValue(true),<br>  }))}</pre><pre>filters := filter.NewAnd().SetFields([]builder.Filter{<br> filter.NewIn().SetDimension(&quot;guid&quot;).<br> SetValues(&quot;en-US&quot;).<br> SetExtractionFn(extractionfn.NewCascade().<br>  SetExtractionFns([]builder.ExtractionFn{<br>    extractionfn.NewStringFormat().SetFormat(&quot;%s_language&quot;),<br>    extractionfn.NewRegisteredLookup().SetLookup(&quot;custA_metadata&quot;),<br>  }))})</pre><pre>q := query.NewGroupBy().<br>   SetDimensions(dimensions).<br>   SetFilter(filters).<br>   ...</pre><p>That’s it.<br>You should be set now with using these complex lookups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b421a59154f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ElasticSearch scripted field: subtract Epoch timestamp and ISO datetime]]></title>
            <link>https://elisegev.medium.com/elasticsearch-scripted-field-subtract-epoch-timestamp-and-iso-datetime-e26d087c8a36?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26d087c8a36</guid>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Fri, 21 May 2021 17:35:32 GMT</pubDate>
            <atom:updated>2021-05-22T05:51:43.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*NpDcYlgexZ4-3G2pVr344Q.png" /></figure><p>ElasticSearch allows putting data into date-time fields in different formatting. You may have one field that was put as a numeric Epoch time (Unix / POSTIX time), and another that was put as an ISO datetime.</p><pre>fieldEpoch: 1621616091<br>fieldISO:   2021-05-21T15:04:05Z</pre><p>Then, you might want to create a field script that would subtract one from the other.</p><p>Luckily, ElasticSearch allows putting the data in different formatting, but internally, <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html">it always stores them as Epoch time</a> (long number). Therefore, it offers a way to simply get the date as Epoch, regardless of the formatting that the date was stored as: doc[&quot;fieldISO&quot;].value.millis</p><p>One can use this functionality in a scripted field, to subtract the two fields:</p><pre>if (!doc[&#39;fieldEpoch&#39;].empty &amp;&amp; !doc[&#39;fieldISO&#39;].empty) {<br>  return doc[&#39;fieldEpoch&#39;].value - doc[&#39;fieldISO&#39;].value.millis;<br>} else {<br>  return 0;<br>}</pre><p>The output of this would be the difference between the two fields, in milliseconds. It might be convenient to divide by 1,000 to switch to seconds difference:</p><pre>if (!doc[&#39;fieldEpoch&#39;].empty &amp;&amp; !doc[&#39;fieldISO&#39;].empty) {<br>  return ((doc[&#39;fieldEpoch&#39;].value - doc[&#39;fieldISO&#39;].value.millis) / 1000);<br>} else {<br>  return 0;<br>}</pre><p>But notice that dividing eliminates the precision point (2,600 milliseconds will become 2 seconds instead of 2.6 seconds).</p><p><strong>Tip:</strong> If you’re using Kibana, to create this as a scripted field, go to Management &gt; (Kibana) Index Patterns &gt; (choose your index) &gt; Choose the tab “Scripted field” &gt; Click “Add scripted field”. You can preview that the script works by clicking “Get help with the syntax and preview the results of your script.” and then “Preview results” tab.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26d087c8a36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running PHP-FPM in CLI]]></title>
            <link>https://elisegev.medium.com/running-php-fpm-in-cli-e1f0f4b4f59a?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f0f4b4f59a</guid>
            <category><![CDATA[php-fpm]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[php-cli]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 04:55:25 GMT</pubDate>
            <atom:updated>2020-12-08T04:03:08.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gpg7SDrR_08Ruazv7zrZIw.png" /></figure><p>The standard for running an NGINX webserver for PHP is with PHP-FPM — PHP FastCGI Process Manager(see <a href="https://www.nginx.com/resources/wiki/start/topics/examples/phpfcgi/">nginx docs</a>, <a href="https://www.digitalocean.com/community/tags/php">digitalocean docs</a>). I experienced some major performance enhancements when switching from standard PHP on Apache HTTPD webserver to NGINX with PHP-FPM in my websites.</p><p>PHP-FPM started as an independent project (many stackoverflow answers hold broken links to its old standalone documentation) that offered an alternative to PHP FastCGI (which in turn is a take on <a href="https://en.wikipedia.org/wiki/FastCGI">FastCGI</a>), but eventually embraced by the official PHP group (see <a href="https://www.php.net/manual/en/install.fpm.php">php.net</a>).</p><p>The problem with using PHP-FPM is that it is customized for webservers (the whole purpose of FastCGI is an interface between applications and webservers), whereas as engineers, we often need to execute PHP scripts in command-line (CLI). i.e. for cronjobs, bash scripts, batch operations done without the intervention of a web-browser and so on. Some of these can be resolved with a mere curl, but it’s not always convenient enough.</p><h3>Solution</h3><p>Recommendations vote for <a href="http://www.php-cli.com/">php-cli</a>, so one can use that.<strong><br>My “yet another” solution was to create </strong><a href="https://github.com/EekoS/php-fpm-cli"><strong>php-fpm-cli</strong></a><strong> </strong>(forked from <a href="https://gist.github.com/muhqu/91497df3a110f594b992">Mathias Leppich’s gist</a>), which adds to that gist support for loading the PHP script from a file, using query-string parameters and verification of the http-status-code if exists. In this article I’ll explain a bit on the behind the scenes.</p><h3>Setup and how does it work</h3><p>Basically to run PHP with PHP-FPM, we use the FastCGI socket/host (explained in detail in <a href="https://docs.oracle.com/cd/E36784_01/html/E36870/cgi-fcgi-1.html">Oracle’s CGI FastCGI manual</a> or <a href="https://manpages.ubuntu.com/manpages/xenial/man1/cgi-fcgi.1.html">Ubuntu’s</a>, and it’s the same for PHP-FPM). Since PHP-FPM v7 it is located in:</p><pre>/run/php-fpm/www.sock</pre><p>(prior PHP-FPM versions had it in /var/run/php5-fpm.sock for example — it is noted in the listenfield of /etc/php-fpm.d/www.conf,or use something like find / -type f -iname &quot;php*.sock&quot; 2&gt;/dev/null to locate it) <br>(Also note that in Nginx it is configured with unix:prefix, not relevant to this flow)</p><p>To be able to do that, we need the cgi-fcgi command, which is available when installing either of these, depending on your OS:</p><pre>#RHEL / CentOS<br>yum --enablerepo=epel install fcgi<br><br>#Ubuntu / Debian<br>apt-get install libfcgi0ldbl</pre><p>We also need to allow PHP-FPM access to the executed file, so we configure the “listen.acl_users” field in its .conf file to allow access to the PHP scripts’ owners (those set by chown). This will prevent errors like “Could not connect to /run/php-fpm/www.sock”. Run this (might require sudo):</p><pre>vi /etc/php-fpm.d/www.conf<br>#or /etc/php5/fpm/pool.d/www.conf in older versions</pre><p>and change the following line to something similar:</p><pre>listen.acl_users = apache,nginx,myuser</pre><p>Then restart the php-fpm service:</p><pre>systemctl restart php-fpm<br>#or sudo systemctl restart php7.0-fpm</pre><p>I would note that PHP-FPM v5 and earlier did not support “listen.acl_users” and so we’ll need to change listen.owner and listen.group — but I don’t recommend that for newer versions where acl_users is supported. It is very limiting and can introduce issues with your webserver (Nginx).</p><p>All set. you can run your PHP script in CLI:</p><pre>./php-fqm-cli -f &lt;path_to_php_file&gt; -q &quot;&lt;query_params&gt;&quot;<br><br># Example:<br>./php-fqm-cli -f myscript.php -q &quot;param1=val1&amp;param2=val2&quot;</pre><p>If you want to configure the php-fpm-cli script, to support more FastCGI parameters other than SCRIPT_FILENAME, QUERY_STRING, REQUEST_METHOD, you can use the following for reference (and also CGI FastCGI manuals I mentioned above):</p><pre>/etc/nginx/fastcgi_params</pre><h4>References</h4><ol><li><a href="https://maxchadwick.xyz/blog/getting-the-php-fpm-status-from-the-command-line">https://maxchadwick.xyz/blog/getting-the-php-fpm-status-from-the-command-line</a></li><li><a href="https://www.thatsgeeky.com/2012/02/directly-connecting-to-php-fpm/">https://www.thatsgeeky.com/2012/02/directly-connecting-to-php-fpm/</a></li><li><a href="http://www.inanzzz.com/index.php/post/653v/testing-php-fpm-without-having-a-web-server">http://www.inanzzz.com/index.php/post/653v/testing-php-fpm-without-having-a-web-server</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f0f4b4f59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Couchbase N1QL WHERE…IN]]></title>
            <link>https://elisegev.medium.com/couchbase-n1ql-where-in-120a414e0f13?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/120a414e0f13</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[n1ql]]></category>
            <category><![CDATA[couchbase]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 17:50:23 GMT</pubDate>
            <atom:updated>2019-08-21T17:50:23.988Z</atom:updated>
            <content:encoded><![CDATA[<p>Couchbase query language N1QL is very annoying when it comes to WHERE...IN clause. I find it very odd that it decided to go different than RBDMS SQL queries, and require square brackets [&quot;value1&quot;, &quot;value2&quot;] instead of the round brackets that are so common pretty much in every tool (and for DB people: in RDBMS SQL).</p><p>A full functioning example for Couchbase N1QL:</p><pre>SELECT fields FROM bucket WHERE field IN [&quot;value1&quot;, &quot;value2&quot;, ...]</pre><p>And the following example <strong>will not work:</strong></p><pre>SELECT fields FROM bucketWithBadQuery WHERE fieldWithBadWhere IN (&quot;value1&quot;, &quot;value2&quot;, ...)</pre><p>By the way, I came across this when I tried doing a nice query that additionally doesSELECT COUNT(*) ... GROUP BY field and SELECT parentNode.field FROM bucket UNNEST bucket.parentNode AS parentNode for the first time, and integrating all those clauses together needed some extra effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=120a414e0f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t just create Setter methods, try creating operation methods]]></title>
            <link>https://elisegev.medium.com/dont-just-create-setter-methods-try-creating-operation-methods-ed95e27117f6?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed95e27117f6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 19:19:47 GMT</pubDate>
            <atom:updated>2018-12-16T19:19:47.203Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java, I come across a lot of unused “setter” and “getter” methods. Creating setters and getters often strikes roots with developers that work with Hibernate and Lombok. Hibernate needs the setters in order to set the values in the data model objects, and in Lombok it’s just adding an annotation, that maybe makes people lazy in deciding whether or not those setters or getters are needed.</p><p>This blog post is created after I saw a piece of code that someone wrote in my workplace — which made use of a setter, when it was unnecessary and caused code duplication and messy code.</p><p>I simplified things and changed the topic that the code relates to. Now the code is managing monitors (screens) in a company, telling if they are turned on (active = 1) or off (active = 0). The reason that active is integer and not boolean is that the developer wished to save the active state in the database in a compact way (e.g. instead of a string of “true” or “false” to use Boolean.valueOf).</p><p>This was the <strong>bad</strong> code that ended up in our system:</p><pre>public class Monitor {<br>  private Integer active;</pre><pre>  public Integer getActive() {<br>    return active;<br>  }</pre><pre>  public void setActive(Integer active) {<br>    this.active = active;<br>  }<br>}</pre><pre>public class MonitorDto {<br>  private boolean active;<br>  //setter and getter here<br>}</pre><pre>public class MonitorService {<br>  public void saveMonitor(Monitor monitor) {<br>    //save the monitor to the database<br>  }</pre><pre>  public void activateMonitor(Long monitorId) {<br>    Monitor monitor = findMonitorById(monitorId); //say method exists<br>    <strong>monitor.setActive(1);</strong><br>    saveMonitor(monitor);<br>  }<br>}</pre><pre>public class MonitorController {</pre><pre>  @Autowired<br>  private MonitorService monitorService;</pre><pre>  @PutMethod(&quot;/monitor/save&quot;)<br>  public String save(@RequestParam MonitorDto monitorDto) { <br>    Monitor monitor = new Monitor();<br>    <strong>monitor.setActive(monitorDto.getActive() ? 1 : 0);</strong></pre><pre>    monitorService.saveMonitor(monitor);<br>    return ... //something<br>    //skipping handling errors for code simplicity<br>  }</pre><pre>  @GetMapping(&quot;/monitor/activate/{id}&quot;)<br>  public String save(<a href="http://twitter.com/PathVariable">@PathVariable</a> Long id) { <br>    monitorService.activateMonitor(id);<br>    return ... //something<br>    //skipping handling errors for code simplicity<br>  }<br>}</pre><p>If we refer to the active state (and its type) in a Monitor to be a “secret recipe” — then the main issue with this code is that 3 classes “know the secret recipe” for a monitor, which make it “not so secret”.<br>Those classes are: the data model itself (Monitor class), the service that manages it (MonitorService class) and the API for the world (MonitorController class). <br>The problem could have been worse, if we hadn’t had a DTO (MonitorDto) for our API (MonitorController). Without it, the logic of turning a boolean value into the relevant integer value could have been required from the client. Oh my…</p><p>There are better ways to approach this.</p><h4>Solution 1: Keep it simple</h4><p>A familiar solution would be to expose the logic of turning a boolean value for “active” Monitor, only in our data model (Monitor class). All other classes would not know of the “secret recipe” that the “active” state is saved as an integer — and would work with the tools the data model gave them — which is a setter of boolean type.</p><p>It would look like this:</p><pre>public class Monitor {<br> private Integer active;</pre><pre> public boolean getIsActive() {<br>   return active ? 1 : 0;<br> }</pre><pre> public void setActive(<strong>boolean active</strong>) {<br>   this.active = active ? 1 : 0;<br> }<br>}</pre><pre>public class MonitorDto {<br> private boolean active;<br> //setter and getter here<br>}</pre><pre>public class MonitorService {<br> public void saveMonitor(Monitor monitor) {<br>   //save the monitor to the database<br> }</pre><pre> public void activateMonitor(Long monitorId) {<br>   Monitor monitor = findMonitorById(monitorId); //say method exists<br>   monitor.setIsActive(true);<br>   saveMonitor(monitor);<br> }<br>}</pre><pre>public class MonitorController {</pre><pre> <a href="http://twitter.com/Autowired">@Autowired</a><br> private MonitorService monitorService;</pre><pre> @PutMethod(&quot;/monitor/save&quot;)<br> public String save(<a href="http://twitter.com/RequestParam">@RequestParam</a> MonitorDto monitorDto) { <br>   Monitor monitor = new Monitor();<br>   monitor.setActive(monitorDto.getActive());<br>   monitorService.saveMonitor(monitor);<br>   return ... //something<br>   //skipping handling errors for code simplicity<br> }</pre><pre> @GetMapping(&quot;/monitor/activate/{id}&quot;)<br> public String save(<a href="http://twitter.com/PathVariable">@PathVariable</a> Long id) { <br>   monitorService.activateMonitor(id);<br>   return ... //something<br>   //skipping handling errors for code simplicity<br> }<br>}</pre><p>As you can see, the “secret recipe” is “contained” only to the data model. That is relatively neat. But still the clients of our data model need to be aware that there are two states to “active”, and need to understand that TRUE means active, and FALSE means inactive. Pretty basic to understand in this simple example, but think of greater problems we want to expose methods (“internal” APIs) for — that can get hairy. Well, luckily, there’s a better way.</p><h4>Solution 2: Borrow from DDD</h4><p>We can borrow some concepts from Domain-Driven Design (DDD), to expose “operations” and disallow mutating existing models.<br>Basically this means that we don’t “blindly” expose a setter, but instead, we expose an easy to understand API.</p><p>It would look like this:</p><pre>public class Monitor {<br>  private Integer active;</pre><pre>  public Monitor(active) {<br>    this.active = active ? 1 : 0;<br>  }<br>  <br>  public boolean getIsActive() {<br>    return active ? 1 : 0;<br>  }<br>  <br>  <strong>public void activate() {</strong><br>    this.active = 1;<br>  }<br>  <br>  <strong>public void deactivate() {</strong><br>    this.active = 0;<br>  }<br>}</pre><pre>public class MonitorDto {<br> private boolean active;<br> //setter and getter here<br>}</pre><pre>public class MonitorService {<br> public void saveMonitor(Monitor monitor) {<br>   //save the monitor to the database<br> }</pre><pre>public void activateMonitor(Long monitorId) {<br>   Monitor monitor = findMonitorById(monitorId); //say method exists<br>   monitor.activate();<br>   saveMonitor(monitor);<br> }<br>}</pre><pre>public class MonitorController {</pre><pre><a href="http://twitter.com/Autowired">@Autowired</a><br> private MonitorService monitorService;</pre><pre>@PutMethod(&quot;/monitor/save&quot;)<br> public String save(<a href="http://twitter.com/RequestParam">@RequestParam</a> MonitorDto monitorDto) { <br>   Monitor monitor = new Monitor(monitorDto.getActive());<br>   monitorService.saveMonitor(monitor);<br>   return ... //something<br>   //skipping handling errors for code simplicity<br> }</pre><pre>@GetMapping(&quot;/monitor/activate/{id}&quot;)<br> public String save(<a href="http://twitter.com/PathVariable">@PathVariable</a> Long id) { <br>   monitorService.activateMonitor(id);<br>   return ... //something<br>   //skipping handling errors for code simplicity<br> }<br>}</pre><p>The cool thing here is we have the simplest API possible: If the data model’s client wants to active, he simply uses Monitor.activate() and to deactivate — he simply uses Monitor.deactivate(). This way no logic exits Monitor class. It is the only one knowing how the “secret recipe” of “active” state data-type is stored.</p><p>Oh… BTW… Not “auto creating” setters and thinking before creating them or even the “operations” I introduced in Solution 2, will make it easier for you to create immutable classes or immutable fields. If Monitor class would have a field named “model” that doesn’t ever change — then it could’ve been an immutable field (with the “final” keyword).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed95e27117f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running tests and creating code coverage reports for React / NodeJS project continuously with…]]></title>
            <link>https://elisegev.medium.com/running-tests-and-creating-code-coverage-reports-for-react-nodejs-project-continuously-with-60312b6a2dd0?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/60312b6a2dd0</guid>
            <category><![CDATA[deployment-pipelines]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 14:19:31 GMT</pubDate>
            <atom:updated>2022-04-18T18:23:09.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>Running tests and creating code coverage reports for React / NodeJS project continuously with Jenkins Pipelines, Jest &amp; Cobertura or Jest-JUnit and push to Artifactory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya0lZxk6fDZcT5p6fABa4w.png" /><figcaption>Showing the JavaScript line code coverage on the far bottom-right, alongside the Java line code coverage (in color)</figcaption></figure><p>The foundation for a healthy project is a high standard of automated tests. When your code is well tested, with tests that cover actual scenarios and user behaviors, modifying the code is not as risky task as it was otherwise. Of course it doesn’t mean your project is bulletproof, but the potential damage to your users decreases.</p><p>When you’re working in a team, running the automated tests <strong>continuously </strong>has great benefits (“OMG don’t update your code from the source control, you won’t be able to build the project until a fix is checked-in!” for example). Nonetheless, continuously keeping track of the code coverage your tests provide also has benefits (developers keep checking-in code that future modifications in it would be risky, for example).</p><p>This guide will walk you through continuously running tests and creating code coverage reports in Jenkins. <br>It is written with React in mind (+TypeScript), but it can work with any <a href="https://jestjs.io/docs/en/testing-frameworks">Jest-supported JavaScript framework</a> (one can even use Istanbul directly without Jest).<br>It does assume that you previously setup your project to run tests (e.g. following <a href="https://medium.com/@mateuszsokola/configuring-react-16-jest-enzyme-typescript-7122e1a1e6e8">React + Jest + Enzyme + TypeScript guide</a>).</p><p>I originally wanted to have the code coverage report parsed by JaCoCo so the Jenkins job list can show the total number of lines covered. I did not find a way to do this, and this is why this guide is using Cobertura. As an alternative, if this number is not important to you and you don’t want to install the Cobertura Jenkins Plugin, you can use the Jest-JUnit alternative, also described in this guide.</p><h3>Project structure and tools in use</h3><ul><li>ReactJS, but can be any JavaScript framework</li><li>Jest (tested with v22) — testing solution for React made by Facebook that has IstanbulJS built-in, to produce a code coverage report</li><li>Webpack — bundler, but can be any bundler</li><li>NodeJS (tested with v10.4.1)</li><li>NPM (tested with v6.1.0, notice some older versions such as 3–5 have some quirks with running Jest tests sometimes)</li><li>Jenkins (with <a href="https://jenkins.io/doc/book/pipeline/">Pipelines</a>) — continuous integration tool, running processes based on code (Jenkinsfile)</li><li>Artifactory + <a href="https://github.com/jfrog/jenkins-artifactory-plugin">Artifactory Jenkins Plugin</a> — artifact management</li></ul><h3>Reporters</h3><p>We have three ways to produce a code coverage report:</p><ul><li><a href="https://wiki.jenkins.io/display/JENKINS/Cobertura+Plugin">Cobertura Jenkins Plugin</a> — a utility for code coverage that will collect the report from Jest</li><li><a href="https://github.com/jest-community/jest-junit">Jest-JUnit</a> — Exports the Jest code coverage report to XML formatted as a Java JUnit report</li><li>Plain HTML — exports the code coverage report as an IstanbulJS-formatted HTML</li></ul><p>I’ll exemplify the use of all, separately.</p><h3>Option 1: Code coverage with Cobertura</h3><p>Cobertura Jenkins Plugin has a nice feature, that it can show the total percentage of code-lines covered in Jenkins views. “Bottom lines” are always more convenient for glimpses, but this is also comfortable when you have a physical monitor displaying Jenkins’ lines coverage to the developers and/or the managers.</p><h4>Step 1: Setup report creation</h4><p>Edit your package.json and add the following lines:</p><pre>{<br>  &quot;name&quot;: &quot;continuous-test-code-coverage-guide&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack&quot;,<br>    &quot;test&quot;: &quot;jest --coverage --coverageDirectory=output/coverage/jest&quot;<br>  },<br>  ...<br>  &quot;jest&quot;: {<br>    &quot;coverageReporters&quot;: [<br>      &quot;text&quot;,<br>      &quot;cobertura&quot;<br>    ]<br>    ...<br>  }<br>}</pre><p>Now, running npm run test for this package.json will produce two code coverage reports in output/coverage/jest — one is in text format, and the other in “cobertura” format.</p><p>We use the text format because it prints a nice report to the console, which is comfortable to developers running the test script on their dev-machine.<br>We use the “cobertura” format so the result can be parsed by the Jenkins Cobertura Plugin.</p><h4>Step 2: Create a Jenkins pipeline file</h4><p>Create a Jenkinsfile file, and put the following content (with the relevant modifications):</p><pre>#!/bin/groovy<br>pipeline {<br>  tools {<br>    nodejs &#39;default-nodejs&#39;<br>  }<br>  stages {<br>    stage(&#39;Startup&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm install&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Test&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm run test&#39;<br>        }<br>      }<br>      post {<br>        always {<br>          step([$class: &#39;CoberturaPublisher&#39;, coberturaReportFile: &#39;output/coverage/jest/cobertura-coverage.xml&#39;])<br>        }<br>      }<br>    }<br>    stage(&#39;Build&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm start&#39;<br>          sh &#39;npm pack&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Deploy&#39;) {<br>      when {<br>        expression {<br>          currentBuild.result == null || currentBuild.result == &#39;SUCCESS&#39;<br>        }<br>      }<br>      steps {<br>        script {<br>          def server = Artifactory.server &#39;My_Artifactory&#39;<br>          uploadArtifact(server)<br>        }<br>      }<br>    }<br>  }<br>}</pre><pre>def uploadArtifact(server) {<br>  def uploadSpec = &quot;&quot;&quot;{<br>            &quot;files&quot;: [<br>              {<br>                &quot;pattern&quot;: &quot;continuous-test-code-coverage-guide*.tgz&quot;,<br>                &quot;target&quot;: &quot;npm-stable/&quot;<br>              }<br>           ]<br>          }&quot;&quot;&quot;<br>  server.upload(uploadSpec)<br><br>  def buildInfo = Artifactory.newBuildInfo()<br>  server.upload spec: uploadSpec, buildInfo: buildInfo<br>  server.publishBuildInfo buildInfo<br>}</pre><p>The line calling CoberturaPublisher will publish the report that npm run test created (see previous step).</p><p>npm start created the dist/ folder with the bundled code (see previous step), and npm pack created a tgz file that wraps it.</p><p>uploadArtifact will upload the tgz file (on successful builds) to your JFrog Artifactory. I recommend using the <a href="https://github.com/jfrog/jenkins-artifactory-plugin">Artifactory Plugin</a> to setup the Artifactory parameters in Jenkins &gt; Manage Jenkins &gt; Configure System&gt; Artifactory, but nonetheless, the <a href="https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins">Artifactory help guide</a> for setting up the server’s parameters within the Jenkinfile is simple enough.</p><h4>Step 3: Create the Jenkins Pipeline job</h4><p>Go to Jenkins, and create a new job. Choose a Pipeline job. Choose to run the pipeline from the Jenkinsfile we created in step 2.</p><p>If you need options here, try installing some Jenkins plugins (e.g. BlueOcean).</p><p>The end results for running this job:</p><ol><li>Use Jenkins &gt; Edit View &gt; Columns &gt; Add column &gt; Cobertura coverage, to view the total numbers in a glimps on your Jenkins jobs list.</li><li>Inside this pipeline job we created, you should have a “Test Result Trend” column in the right-hand side, with data in it.</li><li>Inside this pipeline job we created, you should have a “Coverage Report” and “Test Result Analyzer” options on the left-hand menu, with data in them.</li><li>Same as 2+3, specific for each build in this pipeline job we created.</li><li>Inside each build you should have an Artifactory Build Info option on the left-hand menu.</li></ol><p><strong><em>Notice that after Option 2 part of the guide, there’s a section for tips.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGPKxS-LzPR5ASY8JcXU6Q.png" /></figure><h3>Option 2: Code coverage with Jest-JUnit</h3><p>The Jest-JUnit integration with Jenkins lacks some functionality, but it doesn’t require installing the Cobertura Jenkins Plugin (for example if its license is not approved by your company).</p><h4>Setting up code coverage report creation</h4><p>Install Jest-JUnit as a devDependency of your project:<br>npm install — dev jest-junit</p><p>Then, edit your package.json and add the following lines:</p><pre>{<br>  &quot;name&quot;: &quot;continuous-test-code-coverage-guide&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack&quot;,<br>    &quot;test&quot;: &quot;jest --coverage --coverageDirectory=output/coverage/jest&quot;<br>  },<br>  ...<br>  &quot;jest&quot;: {<br>    &quot;coverageReporters&quot;: [<br>      &quot;text&quot;<br>    ],<br>    &quot;reporters&quot;: [<br>      &quot;default&quot;,<br>      &quot;jest-junit&quot;<br>    ],<br>    ...<br>  },<br>  &quot;jest-junit&quot;: {<br>    &quot;output&quot;: &quot;output/coverage/junit/junit.xml&quot;,<br>    &quot;usePathForSuiteName&quot;: &quot;true&quot;<br>  }<br>}</pre><p>Now, running npm run test for this package.json will produce a code coverage report in output/coverage/junit/junit.xml (thanks to reporters: jest-junit) and on the console (thanks to coverageReportes: text + reporters: default).</p><h4>Step 2: Create a Jenkins pipeline file</h4><p>Create a Jenkinsfile file, and put the following content (with the relevant modifications):</p><pre>#!/bin/groovy<br>pipeline {<br>  tools {<br>    nodejs &#39;default-nodejs&#39;<br>  }<br>  stages {<br>    stage(&#39;Startup&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm install&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Test&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm run test&#39;<br>        }<br>      }<br>      post {<br>        always {<br>          junit &#39;output/coverage/junit/junit.xml&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Build&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm start&#39;<br>          sh &#39;npm pack&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Deploy&#39;) {<br>      when {<br>        expression {<br>          currentBuild.result == null || currentBuild.result == &#39;SUCCESS&#39;<br>        }<br>      }<br>      steps {<br>        script {<br>          def server = Artifactory.server &#39;My_Artifactory&#39;<br>          uploadArtifact(server)<br>        }<br>      }<br>    }<br>  }<br>}</pre><pre>def uploadArtifact(server) {<br>  def uploadSpec = &quot;&quot;&quot;{<br>            &quot;files&quot;: [<br>              {<br>                &quot;pattern&quot;: &quot;continuous-test-code-coverage-guide*.tgz&quot;,<br>                &quot;target&quot;: &quot;npm-stable/&quot;<br>              }<br>           ]<br>          }&quot;&quot;&quot;<br>  server.upload(uploadSpec)</pre><pre>  def buildInfo = Artifactory.newBuildInfo()<br>  server.upload spec: uploadSpec, buildInfo: buildInfo<br>  server.publishBuildInfo buildInfo<br>}</pre><p>The line calling junit will publish the report that npm run test created (see previous step).</p><p>npm start created the dist/ folder with the bundled code (see previous step), and npm pack created a tgz file that wraps it.</p><p>uploadArtifact will upload the tgz file to your JFrog Artifactory. I recommend using the <a href="https://github.com/jfrog/jenkins-artifactory-plugin">Artifactory Plugin</a> to setup the Artifactory parameters in Jenkins &gt; Manage Jenkins &gt; Configure System&gt; Artifactory, but nonetheless, the <a href="https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins">Artifactory help guide</a> for setting up the server’s parameters within the Jenkinfile is simple enough.</p><h4>Step 3: Create the Jenkins Pipeline job</h4><p>Go to Jenkins, and create a new job. Choose a Pipeline job. Choose to run the pipeline from the Jenkinsfile we created in step 2.</p><p>If you need options here, try installing some Jenkins plugins (e.g. BlueOcean).</p><p>The end results for running this job:</p><ol><li>Inside the pipeline job we created, there a “Test Result” with data on the left-hand menu.</li><li>Inside each build you should have an Artifactory Build Info option on the left-hand menu.</li></ol><h3>Option 3: Plain HTML</h3><p>If you don’t want to install any additional plugin anywhere, you can simply post the Jest (Istanbul) HTML report into Jenkins. By this you are relying on the Istanbul report format, which might be comfortable to most (but is different than Java reports, in case your team is used to them).</p><h4>Setting up code coverage report creation</h4><p>Edit your package.json and add the following lines:</p><pre>{<br>  &quot;name&quot;: &quot;continuous-test-code-coverage-guide&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack&quot;,<br>    &quot;test&quot;: &quot;jest --coverage --coverageDirectory=output/coverage/jest&quot;<br>  },<br>  ...<br>  &quot;jest&quot;: {<br>    &quot;coverageReporters&quot;: [<br>      &quot;text&quot;,<br>      &quot;html&quot;<br>    ]<br>    ...<br>  }<br>}</pre><p>Now, running npm run test for this package.json will produce a code coverage report in output/coverage/jest/index.html (thanks to coverageReporters: html) and on the console (thanks to coverageReportes: text).</p><p>Hint: you can change “html” to “lcov” as well, if you like its format better. It is also an HTML report.</p><h4>Step 2: Create a Jenkins pipeline file</h4><p>Create a Jenkinsfile file, and put the following content (with the relevant modifications):</p><pre>#!/bin/groovy<br>pipeline {<br>  tools {<br>    nodejs &#39;default-nodejs&#39;<br>  }<br>  stages {<br>    stage(&#39;Startup&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm install&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Test&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm run test&#39;<br>        }<br>      }<br>      post {<br>        always {<br>          publishHTML target: [<br>            allowMissing         : false,<br>            alwaysLinkToLastBuild: false,<br>            keepAll             : true,<br>            reportDir            : &#39;output/coverage/jest&#39;,<br>            reportFiles          : &#39;index.html&#39;,<br>            reportName           : &#39;Test Report&#39;<br>          ]<br>        }<br>      }<br>    }<br>    stage(&#39;Build&#39;) {<br>      steps {<br>        script {<br>          sh &#39;npm start&#39;<br>          sh &#39;npm pack&#39;<br>        }<br>      }<br>    }<br>    stage(&#39;Deploy&#39;) {<br>      when {<br>        expression {<br>          currentBuild.result == null || currentBuild.result == &#39;SUCCESS&#39;<br>        }<br>      }<br>      steps {<br>        script {<br>          def server = Artifactory.server &#39;My_Artifactory&#39;<br>          uploadArtifact(server)<br>        }<br>      }<br>    }<br>  }<br>}</pre><pre>def uploadArtifact(server) {<br>  def uploadSpec = &quot;&quot;&quot;{<br>            &quot;files&quot;: [<br>              {<br>                &quot;pattern&quot;: &quot;continuous-test-code-coverage-guide*.tgz&quot;,<br>                &quot;target&quot;: &quot;npm-stable/&quot;<br>              }<br>           ]<br>          }&quot;&quot;&quot;<br>  server.upload(uploadSpec)</pre><pre>def buildInfo = Artifactory.newBuildInfo()<br>  server.upload spec: uploadSpec, buildInfo: buildInfo<br>  server.publishBuildInfo buildInfo<br>}</pre><p>The line calling publishHTML will publish the report that npm run test created (see previous step).</p><p>Hint: if you used lcov in the previous step, here replace the value of reportDir with output/coverage/jest/lcov-report.</p><p>npm start created the dist/ folder with the bundled code (see previous step), and npm pack created a tgz file that wraps it.</p><p>uploadArtifact will upload the tgz file to your JFrog Artifactory. I recommend using the <a href="https://github.com/jfrog/jenkins-artifactory-plugin">Artifactory Plugin</a> to setup the Artifactory parameters in Jenkins &gt; Manage Jenkins &gt; Configure System&gt; Artifactory, but nonetheless, the <a href="https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins">Artifactory help guide</a> for setting up the server’s parameters within the Jenkinfile is simple enough.</p><h4>Step 3: Create the Jenkins Pipeline job</h4><p>Go to Jenkins, and create a new job. Choose a Pipeline job. Choose to run the pipeline from the Jenkinsfile we created in step 2.</p><p>If you need options here, try installing some Jenkins plugins (e.g. BlueOcean).</p><p>The end results for running this job:</p><ol><li>Inside the pipeline job we created, there a “Test Result” with data on the left-hand menu.</li><li>Inside each build you should have an Artifactory Build Info option on the left-hand menu.</li></ol><h3>Tips</h3><h4>Fail low coverage results</h4><p>You can set Jest to fail for low coverage results (for example, if developers kept checking-in code without testing it).<br>Read the documentation for this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60312b6a2dd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run prettier in WebStorm or IntelliJ on Windows]]></title>
            <link>https://elisegev.medium.com/run-prettier-in-webstorm-or-intellij-on-windows-6b64c69d1957?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b64c69d1957</guid>
            <category><![CDATA[webstorm]]></category>
            <category><![CDATA[prettier]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 02:50:16 GMT</pubDate>
            <atom:updated>2018-03-15T02:54:48.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Prettier can format your code, and one can have JetBrains WebStorm or IntelliJ do that from within the IDE.</p><p>This guide assumes you <a href="https://prettier.io/docs/en/install.html">installed prettier globally</a>.</p><h3>Versions older than 2018.1</h3><p>Go to File&gt; Preferences (WebStorm) or Settings(IntelliJ) &gt; Tools&gt; External Tools.<br>Click the Plus sign to add a new External Tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*ITMNn8wOC90vezY0i1lQVg.png" /><figcaption>Plus sign to add External Tool</figcaption></figure><p>Fill in the following data:</p><p>Name: prettier<br>Program: C:\Users\&lt;username&gt;\AppData\Roaming\npm\prettier.cmd<br>Arguments: — write $FilePathRelativeToProjectRoot$<br>Workin directory: $ProjectFileDir$</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*Oqwh5kxT0VXyhx0jlMi76A.png" /><figcaption>Create a new External Tool</figcaption></figure><p>Now, to have a key shortcut to run prettier, and still on Preferences/Settings, go to Keymap &gt; External Tools &gt; External Tools &gt; prettier (if it doesn’t appear there, apply changes, close Preferences/Settings and reopen it).<br>Right-click the External Tool prettier and choose “Add Keyboard Shortcut”.<br>Choose the key shortcut you prefer and approve all the way to your code. For example: Ctrl + Shift + s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*7AbylAzNA2kLOzAMB6mH_g.png" /><figcaption>Add Keyboard Shortcut dialog</figcaption></figure><p>That’s it. You’re all set to use prettier within WebStorm or IntelliJ on your Windows, with your selected key shortcut.</p><h3>Version 2018.1 and later</h3><p>Use the <a href="https://prettier.io/docs/en/webstorm.html">new File Watchers option</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b64c69d1957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build/Create Docker Images Continuously with Jenkins]]></title>
            <link>https://elisegev.medium.com/build-create-docker-images-continuously-with-jenkins-b64dc717e8f1?source=rss-f92aeadd0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b64dc717e8f1</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Eli Segev]]></dc:creator>
            <pubDate>Sun, 06 Aug 2017 16:31:24 GMT</pubDate>
            <atom:updated>2017-08-06T16:31:24.948Z</atom:updated>
            <content:encoded><![CDATA[<p>When using Docker to deploy an application, it is best to rebuild the application continuously — for example whenever the application is rebuilt. This way, one’s integration servers can be automatically up-to-date, and run end-to-end tests on the latest code.<br>Docker has great positive influence on development processes and continuous integration of code, in this sense.<br>The shortage of a formal instructions guide to creating Docker images caused me to waste more time than it should’ve been, on setting up this kind of important (but simple) process. For that reason, I decided to write it on my own, in hopes it will save the next person some time.</p><h3>One-time preparations</h3><p>Begin by installing the “<a href="https://wiki.jenkins-ci.org/display/JENKINS/Docker+build+step+plugin">docker-build-step</a>” Jenkins plugin.</p><h4>Installing Docker engine</h4><p>One option is to have Jenkins automatically manage your Docker engine setup. For that, go to Jenkins’ “Global Tool Configurations” and choose to automatically install the latest Docker version from docker.io (“Install latest from docker.io”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*tj4Z4XWgvAHE0FgoJSQtzQ.png" /></figure><p>An alternative is to manually install Docker engine on your Jenkins Nodes.<br>For that, you will need to login to your relevant Jenkins Nodes, and install the engine (<a href="https://docs.docker.com/engine/installation/">instructions here — choose your Node’s setup</a>).</p><h4>Allow Jenkins to control Docker engine</h4><p>This is the tricky part, that misconfiguring can cause a lot of pain. Jenkins needs to run the Docker commands (such as build) with the Docker engine. So, to have Jenkins control the Docker engine, you will need to go to Jenkins’ “Configure System” and there scroll down to “Docker Builder” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*Pd7hKkGksMlkZHVNQo3t5A.png" /><figcaption>Instructions to this configuration follows.</figcaption></figure><p>For the “Docker URL” field, you will need to fill in a TCP URL.<br>If you let Jenkins install Docker engine automatically on your Nodes, then the following should work: tcp://127.0.0.1:4243 or tcp://127.0.0.1:2375 (Use “Test Connection” button to see which works).<br>If you installed Docker engine manually, or the two previous options won’t work, you will need to configure the Docker engine service to allow this port.<br>As a super user, run: systemctl edit docker <br>Add the following text to the [Service] section:</p><pre>ExecStart=/usr/bin/docker daemon -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock</pre><p>Save, and exit the editor. Then, run the following commands to refresh the configurations in the Docker engine service:</p><pre>systemctl daemon-reload<br>systemctl restart docker</pre><p>Now back on Jenkins put tcp://&lt;node_ip&gt;:2375 on the “Docker URL” field, and test that the configurations took affect, with “Test Connection” button. If all still won’t work — check your firewall settings.</p><p><strong><em>More on ExecStart configurations:</em></strong><br><a href="https://success.docker.com/KBase/Using_systemd_to_control_the_Docker_daemon">https://success.docker.com/KBase/Using_systemd_to_control_the_Docker_daemon</a></p><h3>The build job</h3><p>Create a new freestyle Jenkins job. <br>Sync your Dockerfile code from your source-control (at least that’s my recommendation), and download all your Dockerfile requirements (e.g. your application artifact) from your repository manager (e.g. Artifactory). <br>On the “Build” section, add the “Execute Docker command” build-step.<br>Fill in all the relevant information (the context being where the Dockerfile requirements exist — mostly $WORKSPACE).<br>Run the job.</p><h4>Fixing “Build step failed with exception java.lang.NullPointerException: uri was not specified”</h4><p>If you get the following exception on your build process, it means you misconfigured Jenkins control over the Docker engine. Please retry those steps.</p><pre>ERROR: Build step failed with exception<br>java.lang.NullPointerException: uri was not specified<br>    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:204)<br>    at com.github.dockerjava.core.DockerClientConfig$DockerClientConfigBuilder.withUri(DockerClientConfig.java:406)<br>    at org.jenkinsci.plugins.dockerbuildstep.DockerBuilder$DescriptorImpl.createDockerClient(DockerBuilder.java:123)<br>    at org.jenkinsci.plugins.dockerbuildstep.DockerBuilder$DescriptorImpl.getDockerClient(DockerBuilder.java:201)<br>    at org.jenkinsci.plugins.dockerbuildstep.DockerBuilder.perform(DockerBuilder.java:71)<br>    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)<br>    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)<br>    at hudson.model.Build$BuildExecution.build(Build.java:205)<br>    at hudson.model.Build$BuildExecution.doRun(Build.java:162)<br>    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:537)<br>    at hudson.model.Run.execute(Run.java:1744)<br>    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)<br>    at hudson.model.ResourceController.execute(ResourceController.java:98)<br>    at hudson.model.Executor.run(Executor.java:374)<br>Build step &#39;Execute Docker container&#39; marked build as failure</pre><p><strong><em>More reading on this exception:</em></strong><br><a href="https://stackoverflow.com/questions/30046507/using-docker-plugin-on-jenkins">https://stackoverflow.com/questions/30046507/using-docker-plugin-on-jenkins</a><br><a href="https://stackoverflow.com/questions/38204371/jenkins-and-docker-uri-was-not-specified">https://stackoverflow.com/questions/38204371/jenkins-and-docker-uri-was-not-specified</a><br><a href="https://stackoverflow.com/questions/38497408/jenkins-with-docker-plugin-java-lang-nullpointerexception-uri-was-not-specified">https://stackoverflow.com/questions/38497408/jenkins-with-docker-plugin-java-lang-nullpointerexception-uri-was-not-specified</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b64dc717e8f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>