<?xml version="1.0" encoding="UTF-8" ?>
        <feed xmlns="http://www.w3.org/2005/Atom">
            <title>Carlos says bla bla</title>
            <subtitle>What is going on in my mind and its surroundings</subtitle>
            <link rel="self" href="https://carlosvin.github.io/feeds/en.xml" />
            <link href="https://carlosvin.github.io" />
            <id>https://carlosvin.github.io/</id>
            <updated>2021-02-14T00:00:00.000Z</updated>
            <entry>
            <title>Android Studio Portable Download</title>
            <link href="https://carlosvin.github.io/posts/android-studio-portable-download/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/android-studio-portable-download/es"/>   
            <id>https://carlosvin.github.io/posts/android-studio-portable-download/en</id>
            <updated>2013-10-29T12:00:00.000Z</updated>
            <summary>Link to download Android Studio Portable</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>If you want to use <a href="https://developer.android.com/studio">Android Studio</a> without installation, as a portable software, here you have the link to <a href="https://developer.android.com/studio/preview/">last portable version of Android Studio</a>.</p>
</div>]]></content>
            <category term="Android"/>
    <category term="Java"/>
    <category term="Software"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Python's asyncio: What, How, When</title>
            <link href="https://carlosvin.github.io/posts/async-what-how-when/en" />
               
            <id>https://carlosvin.github.io/posts/async-what-how-when/en</id>
            <updated>2014-04-20T11:35:00.000Z</updated>
            <summary>Jesse Jiryu Davis talk about asyncio Python library</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>I&#8217;ve been listening a <a href="https://emptysqua.re/blog/">A. Jesse Jiryu Davis</a> talk about the library <a href="https://www.python.org">Python</a>'s <a href="https://docs.python.org/3.4/library/asyncio.html">asycnio</a> library.</p>
</div>
<div class="paragraph">
<p><a href="https://docs.python.org/3.4/library/asyncio.html">Asycnio</a> is a library added to <a href="https://www.python.org">Python</a> 3.4. that provides infrastructure for writing single-threaded concurrent code which let us to save memory.</p>
</div>
<div class="videoblock">
<div class="content">
<iframe src="https://www.youtube.com/embed/9WV7juNmyE8?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>]]></content>
            <category term="Python"/>
    <category term="Asyncio"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Cheat-sheets for developers</title>
            <link href="https://carlosvin.github.io/posts/cheat-sheets-for-developers/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/cheat-sheets-for-developers/es"/>   
            <id>https://carlosvin.github.io/posts/cheat-sheets-for-developers/en</id>
            <updated>2019-06-13T00:00:00.000Z</updated>
            <summary>Cheat sheets, round-ups, quick references, links</summary>
            <content type="html"><![CDATA[<div class="quoteblock">
<blockquote>
All cheat sheets, round-ups, quick reference cards, quick reference guides and quick reference sheets in one page. The only one you need.
</blockquote>
<div class="attribution">
&#8212; cheat-sheets.org
</div>
</div>
<div class="paragraph">
<p><a href="http://www.cheat-sheets.org/" target="_blank" rel="noopener">cheat-sheets.org</a></p>
</div>]]></content>
            <category term="Tips and Tricks"/>
    <category term="Cheat Sheet"/>
    <category term="Guides"/>
    <category term="Learning"/>
    <category term="Quick References"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Choosing a Modern C++ stack</title>
            <link href="https://carlosvin.github.io/posts/choosing-modern-cpp-stack/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/choosing-modern-cpp-stack/es"/>   
            <id>https://carlosvin.github.io/posts/choosing-modern-cpp-stack/en</id>
            <updated>2020-06-13T00:00:00.000Z</updated>
            <summary>Why I'd choose Meson+Doctest tech stack to create a new C++ project with a reusable and easy-to-run example.</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_choosing_build_system_meson">Choosing Build System (Meson)</a>
<ul class="sectlevel2">
<li><a href="#_cmake_vs_meson">CMake vs Meson</a></li>
<li><a href="#_other_build_systems_comparisons">Other build systems comparisons</a></li>
</ul>
</li>
<li><a href="#_unit_testing_framework">Unit Testing Framework</a>
<ul class="sectlevel2">
<li><a href="#_doctest_a_catch_alternative">doctest: A Catch alternative</a></li>
</ul>
</li>
<li><a href="#_example">Example</a>
<ul class="sectlevel2">
<li><a href="#_project_output_artifacts">Project output artifacts</a></li>
<li><a href="#_project_structure_fork_project">Project structure (Fork project)</a></li>
</ul>
</li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>I&#8217;m starting a new project in C++, but I&#8217;ve run into a couple of questions before starting:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Which build system should I use?</p>
</li>
<li>
<p>Which unit testing framework?</p>
</li>
</ol>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
If you just want project template so you can have a C++ project skeleton ready in seconds, just go to <a href="https://github.com/carlosvin/uuid-cpp" class="bare">https://github.com/carlosvin/uuid-cpp</a> and follow the <a href="https://github.com/carlosvin/uuid-cpp/blob/master/README.md" target="blank_">instructions in README.md</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_choosing_build_system_meson">Choosing Build System (<a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a>)</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I have used before <a href="https://www.gnu.org/software/make/manual/make.html" target="_blank" rel="noopener">Make</a>, <a href="https://maven.apache.org/" target="_blank" rel="noopener">Maven</a>, <a href="https://scons.org/" target="_blank" rel="noopener">Scons</a>, <a href="https://gradle.org/" target="_blank" rel="noopener">Gradle</a> and <a href="https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html" target="_blank" rel="noopener">Autotools</a>, but I have some reasons to try find something else:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html" target="_blank" rel="noopener">Autotools</a></dt>
<dd>
<p>It is not easy to configure and maintain. There are several configuration files and several configuration steps.</p>
</dd>
<dt class="hdlist1"><a href="https://gradle.org/" target="_blank" rel="noopener">Gradle</a></dt>
<dd>
<p>C feature is still incubating. Not very fast. You can check a similar example project at link:/posts/gradle-cpp/[Build C project with Gradle].</p>
</dd>
<dt class="hdlist1"><a href="https://www.gnu.org/software/make/manual/make.html" target="_blank" rel="noopener">Make</a></dt>
<dd>
<p>I don&#8217;t love the syntax. Files tends to get messy as project grows.</p>
</dd>
<dt class="hdlist1"><a href="https://scons.org/" target="_blank" rel="noopener">Scons</a></dt>
<dd>
<p>It is just slower and not as easy to understand than <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a>.</p>
</dd>
<dt class="hdlist1"><a href="https://maven.apache.org/" target="_blank" rel="noopener">Maven</a></dt>
<dd>
<p>It is slow and you might end up "<em>Javatizing</em>" your C++ project structure.</p>
</dd>
</dl>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
I&#8217;ve listed just things I don&#8217;t like, those projects have other great features.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_cmake_vs_meson"><a href="https://cmake.org/" target="_blank" rel="noopener">CMake</a> vs <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a></h3>
<div class="paragraph">
<p>After discarding previous ones, I&#8217;m considering <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a> or <a href="https://cmake.org/" target="_blank" rel="noopener">CMake</a>. Both are fast build systems:</p>
</div>
<div class="paragraph">
<p>Although <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a> is written in <a href="https://python.org/" target="_blank" rel="noopener">Python</a>, it generates a <a href="https://ninja-build.org/" target="_blank" rel="noopener">Ninja</a> build project. First time you configure the project you have to run <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a>, but for building or testing you are actually running <a href="https://ninja-build.org/" target="_blank" rel="noopener">Ninja</a>.</p>
</div>
<div class="paragraph">
<p><a href="https://cmake.org/" target="_blank" rel="noopener">CMake</a> is also able to generate <a href="https://ninja-build.org/" target="_blank" rel="noopener">Ninja</a> files among other formats, <a href="https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html">check CMake generators documentation for more information</a>.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://cmake.org/" target="_blank" rel="noopener">CMake</a></dt>
<dd>
<p>It has a big advantage over <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a>, it is mature and widely used in many projects, which means there are many examples and it will fulfill your C++ project building needs.</p>
</dd>
<dt class="hdlist1"><a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a></dt>
<dd>
<p>It is a young project compared with <a href="https://cmake.org/" target="_blank" rel="noopener">CMake</a>, but it is growing quite fast and it has been adopted in other big projects like <a href="">Gnome</a>, they have an initiative to <a href="https://wiki.gnome.org/Initiatives/GnomeGoals/MesonPorting">port from Autotools to Meson</a>.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p><strong>Finally I&#8217;ve chosen</strong> <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a> because syntax is really clear to me, when I read <code>meson.build</code> file I can quickly understand what is happening during build process.</p>
</div>
<div class="listingblock">
<div class="title">Steps to compile and test a project</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ meson build .  <b class="conum">(1)</b>
$ <span class="hljs-built_in">cd</span> build
$ ninja build    <b class="conum">(2)</b>
$ ninja <span class="hljs-built_in">test</span>     <b class="conum">(3)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>First time you configure the project</p>
</li>
<li>
<p>Each time you build it</p>
</li>
<li>
<p>Each time you run tests</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_other_build_systems_comparisons">Other build systems comparisons</h3>
<div class="paragraph">
<p>I&#8217;ve found two interesting comparisons about available C++ build systems, they might be a little be biased because those comparisons come from <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a> and <a href="https://scons.org/" target="_blank" rel="noopener">Scons</a>.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://bitbucket.org/scons/scons/wiki/SconsVsOtherBuildTools">C++ build systems comparison from Scons</a>.</p>
</li>
<li>
<p><a href="https://mesonbuild.com/Simple-comparison.html">C++ build systems comparison from Meson</a>.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_unit_testing_framework">Unit Testing Framework</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I have used some <a href="https://en.wikipedia.org/wiki/XUnit" target="_blank" rel="noopener">xUnit</a> based libraries like <a href="https://github.com/unittest-cpp/unittest-cpp">UnitTest++</a>, <a href="https://cpputest.github.io/">CppUTest</a> or <a href="https://github.com/google/googletest">Google Test</a> which match perfectly with <a href="https://github.com/google/googletest/tree/master/googlemock">Google Mock</a>. If you want a safe bet that fulfills almost of your testing needs I highly recommend <a href="https://github.com/google/googletest">Google Test</a>.</p>
</div>
<div class="paragraph">
<p>But time ago I found a testing framework with some interesting features, <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>It is just a header file with no external dependencies, so very easy to start (wget + include downloaded file).</p>
</li>
<li>
<p>You can use normal unit test style or <a href="">BDD</a>-style</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you want to know more about <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a>, I recommend you to give it a try, it is a matter of 2 minutes to have a <a href="https://github.com/philsquared/Catch/blob/master/docs/tutorial.md#writing-tests">simple example up and running</a>. You can also read some interesting articles like <a href="https://github.com/philsquared/Catch/blob/master/docs/why-catch.md">Why do we need yet another C test framework?] or https://blog.coldflake.com/posts/Testing-C-with-a-new-Catch/[Testing C++ With A New Catch</a>.</p>
</div>
<div class="sect2">
<h3 id="_doctest_a_catch_alternative"><a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a>: A <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a> alternative</h3>
<div class="paragraph">
<p>There is another testing framework named <a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a>, with same benefits as <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a>, but it promises to be faster and lighter (<a href="https://github.com/onqtam/doctest/blob/master/doc/markdown/benchmarks.md">performance results</a>) than <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a>.</p>
</div>
<div class="paragraph">
<p><a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a> is modeled after <a href="https://github.com/philsquared/Catch" target="_blank" rel="noopener">Catch</a> and some parts of the code have been taken directly, but there are <a href="https://github.com/onqtam/doctest/blob/master/doc/markdown/faq.md#how-is-doctest-different-from-catch">differences</a>.</p>
</div>
<div class="paragraph">
<p>It hasn&#8217;t been easy to decide, both are really similar, following you can see differences:</p>
</div>
<div class="listingblock">
<div class="title">diff between doctest and catch branches</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-diff" data-lang="diff"><span class="hljs-meta">@@ -1,12 +1,12 @@</span>
<span class="hljs-deletion">-#define CATCH_CONFIG_MAIN // It tells Catch to provide a main() - only do this in one cpp file</span>
<span class="hljs-addition">+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN</span>

<span class="hljs-deletion">-#include &quot;catch.hpp&quot;</span>
<span class="hljs-addition">+#include &quot;doctest.h&quot;</span>
#include &quot;Uuid.h&quot;
#include &lt;string&gt;

constexpr int MAX_ITERS = 100;

<span class="hljs-deletion">-TEST_CASE(&quot;Uuid&quot;, &quot;[uuid]&quot;)</span>
<span class="hljs-addition">+TEST_CASE(&quot;Uuid&quot;)</span>
{
for (int i = 0; i &lt; MAX_ITERS; i++)
{
<span class="hljs-meta">@@ -26,7 +26,7 @@</span> TEST_CASE(&quot;Uuid&quot;, &quot;[uuid]&quot;)

// BDD style

<span class="hljs-deletion">-SCENARIO(&quot;UUID creation&quot;, &quot;[Uuid]&quot;)</span>
<span class="hljs-addition">+SCENARIO(&quot;UUID creation&quot;)</span>
{

GIVEN(&quot;A random UUID &quot;)</code></pre>
</div>
</div>
<div class="paragraph">
<p>I&#8217;ve finally chosen <a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a> because it promises to be faster: <a href="https://github.com/onqtam/doctest/blob/master/doc/markdown/benchmarks.md">performance results</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
I&#8217;ve created project using both frameworks you can find them in corresponding branches: <a href="https://github.com/carlosvin/uuid-cpp/tree/doctest">doctest branch</a> or <a href="https://github.com/carlosvin/uuid-cpp/tree/catch">catch branch</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_example">Example</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I&#8217;ve created an example to illustrate this article: <a href="https://github.com/carlosvin/uuid-cpp" class="bare">https://github.com/carlosvin/uuid-cpp</a>.</p>
</div>
<div class="paragraph">
<p>It is a basic implementation of UUID pseudo-random generator based on <a href="https://www.cplusplus.com/reference/random/mt19937" target="_blank" rel="noopener">mt19937</a> which is not cryptographically secure.</p>
</div>
<div class="sect2">
<h3 id="_project_output_artifacts">Project output artifacts</h3>
<div class="paragraph">
<p>When we install the project using <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a> (<a href="https://ninja-build.org/" target="_blank" rel="noopener">Ninja</a>), we will get some artifacts generated and copied in our system.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Shared library: <code>libuuid</code>.</p>
</li>
<li>
<p>Header library for developers who want to use the shared library: <code>include/Uuid.h</code>.</p>
</li>
<li>
<p>Executable <code>uuidgen</code> (<a href="">UUID</a> generator).</p>
</li>
<li>
<p>Test executable (not installed). It tests shared library.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For example, if you execute <code>ninja install</code> on Linux, you will get something like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">/usr/<span class="hljs-built_in">local</span>/lib/libuuid.so
/usr/<span class="hljs-built_in">local</span>/include/Uuid.h
/usr/<span class="hljs-built_in">local</span>/bin/uuidgen</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_project_structure_fork_project">Project structure (<a href="https://github.com/carlosvin/uuid-cpp">Fork project</a>)</h3>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/meson.build">meson.build</a></dt>
<dd>
<p>Root project file configuration. It defines project properties and subdirectories.</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">meson.build</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python">project(
    <span class="hljs-string">&#x27;cpp-meson-example&#x27;</span>, <span class="hljs-comment"># project name</span>
    <span class="hljs-string">&#x27;cpp&#x27;</span>, <span class="hljs-comment"># C++ project, e.g: for C project</span>
    version : <span class="hljs-string">&#x27;1.0.0&#x27;</span>,
    license : <span class="hljs-string">&#x27;MIT&#x27;</span>,
    default_options : [<span class="hljs-string">&#x27;cpp_std=c++11&#x27;</span>]) <span class="hljs-comment"># compile for C++</span>

<span class="hljs-comment"># it will be referred from subdir projects</span>
inc = include_directories(<span class="hljs-string">&#x27;include&#x27;</span>)

<span class="hljs-comment"># meson will try to find a meson.build file inside following directories</span>
subdir(<span class="hljs-string">&#x27;include&#x27;</span>)
subdir(<span class="hljs-string">&#x27;src&#x27;</span>)
subdir(<span class="hljs-string">&#x27;test&#x27;</span>)</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/include/">include</a></dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1">meson.build</dt>
<dd>
<p>Build configuration file for include directory.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">include/meson.build</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-comment"># Select header files to be installed</span>
install_headers(<span class="hljs-string">&#x27;Uuid.h&#x27;</span>)</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/include/Uuid.h">Uuid.h</a></dt>
<dd>
<p>Header file, it is the library interface definition which will be included from projects using that library</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">include/Uuid.h</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-keyword">namespace</span> ids {

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Uuid</span> {</span>
    <span class="hljs-keyword">private</span>:
    <span class="hljs-comment">// ...</span></code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/src">src</a></dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/src/meson.build">meson.build (src)</a></dt>
<dd>
<p>It declares 2 output artifacts, library <code>libuuid</code> and executable <code>uuidgen</code>. Executable depends on the libary, it will use the libary to generate <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" target="_blank" rel="noopener">UUID</a>.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">src/meson.build</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python">libuuid = shared_library(
    <span class="hljs-string">&#x27;uuid&#x27;</span>, <b class="conum">(1)</b>
    <span class="hljs-string">&#x27;Uuid.cpp&#x27;</span>, <b class="conum">(2)</b>
    include_directories : inc, <b class="conum">(3)</b>
    install : true) <b class="conum">(4)</b>

uuidgen = executable(
    <span class="hljs-string">&#x27;uuidgen&#x27;</span>, <b class="conum">(5)</b>
    <span class="hljs-string">&#x27;main.cpp&#x27;</span>, <b class="conum">(6)</b>
    include_directories : inc, <b class="conum">(7)</b>
    link_with : libuuid, <b class="conum">(8)</b>
    install : true) <b class="conum">(9)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>library name</p>
</li>
<li>
<p>source files to be compile</p>
</li>
<li>
<p>previously declared include directories in root <code>meson.build</code></p>
</li>
<li>
<p><code>libuuid</code> will be part of project installation</p>
</li>
<li>
<p>executable name</p>
</li>
<li>
<p>source files to compile</p>
</li>
<li>
<p>previously declared include directories in root <code>meson.build</code></p>
</li>
<li>
<p>linking executable with shared previously declared shared library <code>libuuid</code></p>
</li>
<li>
<p><code>uuidgen</code> executable be part of project installation</p>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/src/main.cpp">main.cpp</a></dt>
<dd>
<p>Entry point for main executable <code>uuidgen</code>.</p>
</dd>
</dl>
</div>
</li>
</ol>
</div>
<div class="listingblock">
<div class="title">src/main.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&quot;Uuid.h&quot;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    ids::Uuid uuid;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; uuid.to_str() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/src/Uuid.cpp">Uuid.cpp</a></dt>
<dd>
<p>Implementation of declared class in header file.</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">src/Uuid.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&quot;Uuid.h&quot;</span></span>

Uuid::Uuid()
{ <span class="hljs-comment">// ...</span></code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/test/">test</a></dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/test/meson.build">meson.build (test)</a></dt>
<dd>
<p>File to configure tests build process.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">test/meson.build</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python">testexe = executable(
    <span class="hljs-string">&#x27;testexe&#x27;</span>, <b class="conum">(1)</b>
    <span class="hljs-string">&#x27;uuid_test.cpp&#x27;</span>, <b class="conum">(2)</b>
    include_directories : inc, <b class="conum">(3)</b>
    link_with : libuuid) <b class="conum">(4)</b>

test(<span class="hljs-string">&#x27;Uuid test&#x27;</span>, testexe) <b class="conum">(5)</b>

test(<span class="hljs-string">&#x27;Uuid test with args and env&#x27;</span>, testexe, args : [<span class="hljs-string">&#x27;arg1&#x27;</span>, <span class="hljs-string">&#x27;arg2&#x27;</span>], env : [<span class="hljs-string">&#x27;FOO=bar&#x27;</span>]) <b class="conum">(6)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>test executable name</p>
</li>
<li>
<p>tests source files to be compiled</p>
</li>
<li>
<p>declared include directories in root <code>meson.build</code></p>
</li>
<li>
<p>link test executable with previously declared shared library <code>libuuid</code></p>
</li>
<li>
<p>test execution</p>
</li>
<li>
<p>we can specify other test execution passing arguments or environment variables</p>
<div class="dlist">
<dl>
<dt class="hdlist1">doctest.h</dt>
<dd>
<p><a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a> library in a single header file. You can try to automate library installation as part of your build process, but I haven not figured out yet a way to do it with <a href="https://mesonbuild.com/" target="_blank" rel="noopener">Meson</a>. For now, I have installed it manually:</p>
</dd>
</dl>
</div>
</li>
</ol>
</div>
<div class="listingblock">
<div class="title">Add <a href="https://github.com/onqtam/doctest" target="_blank" rel="noopener">doctest</a> to your project</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash"><span class="hljs-built_in">cd</span> <span class="hljs-built_in">test</span>
wget https://raw.githubusercontent.com/onqtam/doctest/master/doctest/doctest.h</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://github.com/carlosvin/uuid-cpp/blob/master/test/uuid_test.cpp">uuid_test.cpp</a></dt>
<dd>
<p>Tests implementation.</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">test/uuid_test.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&quot;doctest.h&quot;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&quot;Uuid.h&quot;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string&gt;</span></span>

<span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> MAX_ITERS = <span class="hljs-number">100</span>;

TEST_CASE(<span class="hljs-string">&quot;Uuid&quot;</span>)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; MAX_ITERS; i++)
    {
        ids::Uuid uuid;
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> uuid_str{uuid.to_str()};

        INFO(uuid_str);

        <span class="hljs-comment">// If assertion fails test execution is stopped</span>
        REQUIRE(uuid_str.size() == <span class="hljs-number">36</span>);

        <span class="hljs-comment">// If assertion fails test execution continues</span>
        CHECK(uuid.most &gt; <span class="hljs-number">0</span>);
        CHECK(uuid.least &gt; <span class="hljs-number">0</span>);
    }
}

<span class="hljs-comment">// BDD style</span>

SCENARIO(<span class="hljs-string">&quot;UUID creation&quot;</span>)
{

    GIVEN(<span class="hljs-string">&quot;A random UUID &quot;</span>)
    {

        ids::Uuid uuid;
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> uuid_str{uuid.to_str()};

        REQUIRE(uuid_str.size() == <span class="hljs-number">36</span>);

        WHEN(<span class="hljs-string">&quot;get the most and least&quot;</span>)
        {
            THEN(<span class="hljs-string">&quot;should be more than 0&quot;</span>)
            {
                CHECK(uuid.most &gt; <span class="hljs-number">0</span>);
                CHECK(uuid.least &gt; <span class="hljs-number">0</span>);
            }
        }
    }
}</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
You can find how to build and test the example project at: <a href="https://github.com/carlosvin/uuid-cpp#how-to-build-the-example" class="bare">https://github.com/carlosvin/uuid-cpp#how-to-build-the-example</a>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>]]></content>
            <category term="C++"/>
    <category term="Unit Testing"/>
    <category term="Build System"/>
    <category term="Meson"/>
    <category term="Catch"/>
    <category term="doctest"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Mutex C++</title>
            <link href="https://carlosvin.github.io/posts/cpp-mutex/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/cpp-mutex/es"/>   
            <id>https://carlosvin.github.io/posts/cpp-mutex/en</id>
            <updated>2014-04-24T15:50:00.000Z</updated>
            <summary>Mutex wrapper on C++98 pthread mutex and a the better C++11 std::mutex solution</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p><a href="https://en.wikipedia.org/wiki/C++11" target="_blank" rel="noopener">C++11</a> has added many improvements to help us developing multi-thread systems. I&#8217;m going to talk about <a href="https://en.wikipedia.org/wiki/Mutex" target="_blank" rel="noopener">Mutex</a>.</p>
</div>
<div class="paragraph">
<p>In <a href="https://clang.llvm.org/cxx_status.html" target="_blank" rel="noopener">previous C++11 compiler versions</a>, we can get a <a href="https://en.wikipedia.org/wiki/POSIX_Threads" target="_blank" rel="noopener">pthread</a> <a href="https://en.wikipedia.org/wiki/Mutex" target="_blank" rel="noopener">Mutex</a>, but we must initialize it and destroy it in old C style, in the end you must do more things than just lock/unlock.</p>
</div>
<div class="paragraph">
<p>With <a href="https://en.cppreference.com/w/cpp/thread/mutex" target="_blank" rel="noopener">C++11 Mutex Class</a>, we just lock/unclock the object.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;mutex&gt;</span></span>

<span class="hljs-built_in">std</span>::mutex mtx;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">do_something</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> </span>{
  mtx.lock();
  <span class="hljs-comment">// critical section</span>
  mtx.unlock();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can just use <a href="https://en.wikipedia.org/wiki/Mutex" target="_blank" rel="noopener">Mutex</a> with a <a href="https://en.cppreference.com/w/cpp/thread/lock_guard" target="_blank" rel="noopener">generic lock guard</a>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
If you still have to stick to <a href="https://clang.llvm.org/cxx_status.html" target="_blank" rel="noopener">previous C++11 compiler versions</a>, maybe it is useful to you a wrapper class I created that helps you to work with <a href="https://en.wikipedia.org/wiki/POSIX_Threads" target="_blank" rel="noopener">pthread</a> <a href="https://en.wikipedia.org/wiki/Mutex" target="_blank" rel="noopener">Mutex</a>, so you just have to lock/unlock the Mutex object: <a href="https://gist.github.com/carlosvin/11257689" target="_blank" rel="noopener">Gist code</a>.
</td>
</tr>
</table>
</div>]]></content>
            <category term="C++"/>
    <category term="pthread"/>
    <category term="Mutex"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>C++ Struct memory alignment</title>
            <link href="https://carlosvin.github.io/posts/cpp-pragma-pack/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/cpp-pragma-pack/es"/>   
            <id>https://carlosvin.github.io/posts/cpp-pragma-pack/en</id>
            <updated>2012-11-26T11:00:00.000Z</updated>
            <summary>Understanding pragma pack preprocessor directive and how it affects to memory alignment</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_struct_example">Struct example</a></li>
<li><a href="#_pragma_pack_directive_in_c_struct">#pragma pack directive in C++ struct</a></li>
<li><a href="#_performance_test">Performance test</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>A C++ struct is an element that groups attributes with different types so we can manipulate them all together using same reference. It is like a class with public visibility by default for functions and attributes.</p>
</div>
<div class="paragraph">
<p>If we want to work in a lower level, closer to machine, it might be useful understand how that data structure is stored in memory and how to control that mapping.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_struct_example">Struct example</h2>
<div class="sectionbody">
<div class="paragraph">
<p>It has two attributes: an integer (4 bytes) and a boolean (1 byte).</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-c++" data-lang="c++"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStruct</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};</code></pre>
</div>
</div>
<div class="paragraph">
<p>If we get the instance size using <code>sizeof</code> we should get 5 bytes size and memory would be like:</p>
</div>
<div id="5-bytes" class="imageblock center">
<div class="content">
<img src="../images/c-mem-struct/5b.png" alt="5Bytes" width="200" height="auto">
</div>
<div class="title">Figure 1. 5 bytes struct which uses 5 bytes in memory</div>
</div>
<div class="paragraph">
<p><strong>But</strong> is not that simple, memory alignment depends on compiler and system. We will learn how to control compiler alignment policy, so we can avoid getting unexpected allocation memory sizes.</p>
</div>
<div class="paragraph">
<p>For example, in my local host, if I get the <code>sizeof</code> the previous structure without <code>pragma</code> declarations, <strong>I get a 8 bytes size</strong>. We are getting 8 Bytes instead of expected 5 Bytes because the compiler allocates more memory at the end of structure so it fits in 2n bytes blocks. Memory actually looks like:</p>
</div>
<div id="8-bytes" class="imageblock center">
<div class="content">
<img src="../images/c-mem-struct/8b.png" alt="5Bytes" width="200" height="auto">
</div>
<div class="title">Without pragma: 5 bytes structure that actually spends 8 bytes in memory</div>
</div>
<div class="listingblock">
<div class="title">It prints structure and attributes size, in this case <strong>4 + 1 is not 5</strong></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-c++" data-lang="c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span>  <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStruct</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};

<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span> <span class="hljs-params">(<span class="hljs-keyword">size_t</span> sz, <span class="hljs-keyword">size_t</span> sz_flag, <span class="hljs-keyword">size_t</span> sz_timeout)</span>
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\tflag: &quot;</span> &lt;&lt; sz_flag &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\t+&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\ttimeout: &quot;</span> &lt;&lt; sz_timeout &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\t=&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span> &lt;&lt; sz_timeout + sz_flag &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">&quot;sizeof struct:  &quot;</span> &lt;&lt; sz &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span>
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStruct&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    print (<span class="hljs-keyword">sizeof</span>(SampleStruct), <span class="hljs-keyword">sizeof</span>(SampleStruct::flag), <span class="hljs-keyword">sizeof</span>(SampleStruct::timeout));
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; -- &quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/7c18ee6585e57366">Executing code with pragma pack directive</a>: We get 8 bytes instead of 5 bytes</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">SampleStruct
flag: 1 Bytes
+
timeout: 4 Bytes
=
5 Bytes
sizeof struct:  8 Bytes
--</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
If we want to know the exact structure size we have to specify compiler how to align the memory, to do so we have <code>#pragma pack(n)</code> directive.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_pragma_pack_directive_in_c_struct">#pragma pack directive in C++ struct</h2>
<div class="sectionbody">
<div class="paragraph">
<p>It is a preprocessor directive to indicate to compiler how to align data in memory.</p>
</div>
<div class="listingblock">
<div class="title">Example with different memory alignment configurations</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-c++" data-lang="c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span> <span class="hljs-params">(<span class="hljs-keyword">size_t</span> sz, <span class="hljs-keyword">size_t</span> sz_flag, <span class="hljs-keyword">size_t</span> sz_timeout)</span>
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; flag: &quot;</span> &lt;&lt; sz_flag &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span>&lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; +&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; timeout: &quot;</span> &lt;&lt; sz_timeout &lt;&lt; <span class="hljs-string">&quot;Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; =&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; &quot;</span> &lt;&lt; sz_timeout + sz_flag &lt;&lt; <span class="hljs-string">&quot;Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; sizeof struct:  &quot;</span> &lt;&lt; sz &lt;&lt; <span class="hljs-string">&quot; Bytes&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (1)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack1</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (2)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack2</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (4)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack4</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>


<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStruct</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};


<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span>
</span>{

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack1&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    print (<span class="hljs-keyword">sizeof</span>(SampleStructPack1), <span class="hljs-keyword">sizeof</span>(SampleStructPack1::flag), <span class="hljs-keyword">sizeof</span>(SampleStructPack1::timeout));
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; -- &quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack2&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    print (<span class="hljs-keyword">sizeof</span>(SampleStructPack2), <span class="hljs-keyword">sizeof</span>(SampleStructPack2::flag), <span class="hljs-keyword">sizeof</span>(SampleStructPack2::timeout));

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack4&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    print (<span class="hljs-keyword">sizeof</span>(SampleStructPack4), <span class="hljs-keyword">sizeof</span>(SampleStructPack4::flag), <span class="hljs-keyword">sizeof</span>(SampleStructPack4::timeout));

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStruct&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    print (<span class="hljs-keyword">sizeof</span>(SampleStruct), <span class="hljs-keyword">sizeof</span>(SampleStruct::flag), <span class="hljs-keyword">sizeof</span>(SampleStruct::timeout));
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; -- &quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/7c18ee6585e57366">Executing code with pragma pack directive</a>, we have different results depending of pragma value.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">SampleStructPack1 <b class="conum">(1)</b>
 flag: 1 Bytes
 +
 timeout: 4Bytes
 =
 5Bytes
 sizeof struct:  5 Bytes
 --

SampleStructPack2 <b class="conum">(2)</b>
 flag: 1 Bytes
 +
 timeout: 4Bytes
 =
 5Bytes
 sizeof struct:  6 Bytes

SampleStructPack4 <b class="conum">(3)</b>
 flag: 1 Bytes
 +
 timeout: 4Bytes
 =
 5Bytes
 sizeof struct:  8 Bytes

SampleStruct <b class="conum">(4)</b>
 flag: 1 Bytes
 +
 timeout: 4Bytes
 =
 5Bytes
 sizeof struct:  8 Bytes</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>SampleStructPack1 <code>#pragma pack (1)</code>: It allocates 1 byte memory block, so our sample struct fits perfectly, in this case it is true that <code>4 + 1 = 5</code>.</p>
</li>
<li>
<p>SampleStructPack2 <code>#pragma pack (2)</code>: Minimum block size is 2 bytes. Integer attribute fits because it just needs 2 blocks of 2 Bytes. Boolean attribute needs just 1 Byte, but minimum block size is 2 Bytes, that&#8217;s why total allocated memory is 6 bytes, <code>4 + 2 = 6</code>.</p>
</li>
<li>
<p>SampleStructPack4 <code>#pragma pack (4)</code>: It is like previous one, but in this case we are wasting more memory for boolean attribute, it needs 1 Byte, but we are allocating 4 Bytes.</p>
</li>
<li>
<p>SampleStruct (default compiler alignment): As you can see it behaves exactly like <code>#pragma pack (4)</code>, so we can deduct it is the default compiler alignment.</p>
</li>
</ol>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
Why don&#8217;t we always use smallest memory alignment (<code>#pragma pack (1)</code>) so we can save more memory?
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
Because of performance loss.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_performance_test">Performance test</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The test will allocate same number of elements in arrays for each structure type (1, 2, 4).</p>
</div>
<div class="listingblock">
<div class="title">Test results: <a href="https://coliru.stacked-crooked.com/a/954ad542659c7591">execute performance test</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">SampleStructPack1: 500000000000000000 bytes allocated <span class="hljs-keyword">in</span> 94311 nanoseconds
SampleStructPack2: 600000000000000000 bytes allocated <span class="hljs-keyword">in</span> 1777 nanoseconds
SampleStructPack4: 800000000000000000 bytes allocated <span class="hljs-keyword">in</span> 1519 nanoseconds</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, the smallest memory alignment spends more time allocating and releasing memory.</p>
</div>
<div class="listingblock">
<div class="title">Performance test source code:</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-c++" data-lang="c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;chrono&gt;</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (1)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack1</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (2)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack2</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack (4)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStructPack4</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> pack(0)</span>


<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SampleStruct</span>
{</span>
    <span class="hljs-keyword">bool</span> flag;
    <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> timeout;
};

<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">long</span> MAX_ELEMENTS = <span class="hljs-number">100000000000000000</span>;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">allocate1</span><span class="hljs-params">()</span>
</span>{
    SampleStructPack1 elements [MAX_ELEMENTS];
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack1: &quot;</span> &lt;&lt; <span class="hljs-keyword">sizeof</span>(elements) &lt;&lt; <span class="hljs-string">&quot; bytes allocated&quot;</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">allocate2</span><span class="hljs-params">()</span>
</span>{
    SampleStructPack2 elements [MAX_ELEMENTS];
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack2: &quot;</span> &lt;&lt; <span class="hljs-keyword">sizeof</span>(elements) &lt;&lt; <span class="hljs-string">&quot; bytes allocated&quot;</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">allocate4</span><span class="hljs-params">()</span>
</span>{
    SampleStructPack4 elements [MAX_ELEMENTS];
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;SampleStructPack4: &quot;</span> &lt;&lt; <span class="hljs-keyword">sizeof</span>(elements) &lt;&lt; <span class="hljs-string">&quot; bytes allocated&quot;</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">chrono1</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> begin = high_resolution_clock::now() ;
    allocate1();
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; in &quot;</span> &lt;&lt; duration_cast&lt;nanoseconds&gt;(high_resolution_clock::now() - begin).count() &lt;&lt; <span class="hljs-string">&quot; nanoseconds&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">chrono2</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> begin = high_resolution_clock::now() ;
    allocate2();
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; in &quot;</span> &lt;&lt; duration_cast&lt;nanoseconds&gt;(high_resolution_clock::now() - begin).count() &lt;&lt; <span class="hljs-string">&quot; nanoseconds&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">chrono4</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> begin = high_resolution_clock::now() ;
    allocate4();
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot; in &quot;</span> &lt;&lt; duration_cast&lt;nanoseconds&gt;(high_resolution_clock::now() - begin).count() &lt;&lt; <span class="hljs-string">&quot; nanoseconds&quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}


<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span>
</span>{
    chrono1();
    chrono2();
    chrono4();

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
</div>
</div>]]></content>
            <category term="C++"/>
    <category term="Performance"/>
    <category term="Compilers"/>
    <category term="Memory"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Easily creating a golang command line tool</title>
            <link href="https://carlosvin.github.io/posts/create-cmd-tool-golang/en" />
               
            <id>https://carlosvin.github.io/posts/create-cmd-tool-golang/en</id>
            <updated>2021-02-14T00:00:00.000Z</updated>
            <summary>Let's see how to easily and quickly create a command line tool in golang</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_flags">Flags</a></li>
<li><a href="#_viper">Viper</a></li>
<li><a href="#_meta_viper">Meta-Viper</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://golang.org/" target="_blank" rel="noopener">Golang</a> is the one of the most useful technologies I&#8217;ve recently learned. <a href="https://golang.org/" target="_blank" rel="noopener">Golang</a> has a pretty nice support for networking, command line or logging out of the box, you don&#8217;t need any dependency. But there are libraries making developers' life even easier.</p>
</div>
<div class="paragraph">
<p>I&#8217;ve already talked about <a href="/posts/rest-service-go-vs-java/" target="blank_">creating REST service in go</a>, today I&#8217;d like to focus on creating a command line tool.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flags">Flags</h2>
<div class="sectionbody">
<div class="listingblock">
<div class="title">Command line tool to read number of lines as an input integer parameter <a href="https://golang.org/" target="_blank" rel="noopener">Golang</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
	<span class="hljs-string">&quot;flag&quot;</span>
	<span class="hljs-string">&quot;fmt&quot;</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
	<span class="hljs-keyword">var</span> nFlag = flag.Int(<span class="hljs-string">&quot;lines&quot;</span>, <span class="hljs-number">1234</span>, <span class="hljs-string">&quot;number of lines&quot;</span>)
	flag.Parse()
	fmt.Printf(<span class="hljs-string">&quot;Lines %d\n&quot;</span>, *nFlag)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With previous simple code we have already some useful capabilities</p>
</div>
<div class="listingblock">
<div class="title">Print help menu</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd --<span class="hljs-built_in">help</span>

&gt; Usage of cmd:
    -lines int
        number of lines (default 1234)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Use default value</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd

&gt; Lines 1234</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Pass a value to the command tool</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd --lines=2

&gt; Lines 2</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Pass an invalid value</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd --lines=asdf

&gt; invalid value <span class="hljs-string">&quot;asdf&quot;</span> <span class="hljs-keyword">for</span> flag -lines: parse error
Usage of cmd:
    -lines int
        number of lines (default 1234)
<span class="hljs-built_in">exit</span> status 2</code></pre>
</div>
</div>
<div class="paragraph">
<p>For a simple command line tool, in most of the cases, we will have enough with the default language support. But if we want to bring more features to the combo like reading configuration from environment variables or from files, then a library like the awesome <a href="https://github.com/spf13/viper" target="_blank" rel="noopener">Viper</a> will come really handy.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_viper">Viper</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://github.com/spf13/viper" target="_blank" rel="noopener">Viper</a> is very powerful and well documented library widely used from many projects, I will not get into the details or how to use it, because I&#8217;ve created an abstraction to simplify its usage, I named it <a href="https://github.com/carlosvin/meta-viper" target="_blank" rel="noopener">Meta-Viper</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_meta_viper">Meta-Viper</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://github.com/carlosvin/meta-viper" target="_blank" rel="noopener">Meta-Viper</a> abstracts you of the details of reading configuration from files, environment or flags. This extra simplicity comes with a tradeoff, we are missing some flexibility.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s see some features with an example.</p>
</div>
<div class="listingblock">
<div class="title">Firstly we have to create a go modules project with the meta-viper dependency</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">go mod init example.com/meta-viper <b class="conum">(1)</b>

go get github.com/carlosvin/meta-viper <b class="conum">(2)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Create a go modules project</p>
</li>
<li>
<p>Install the meta-viper dependency</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>Now let&#8217;s create a program that is configurable from files, command line params and environment variables.</p>
</div>
<div class="listingblock">
<div class="title">main.go</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
	<span class="hljs-string">&quot;log&quot;</span>
	<span class="hljs-string">&quot;os&quot;</span>

	config <span class="hljs-string">&quot;github.com/carlosvin/meta-viper&quot;</span>
)

<span class="hljs-comment">// Here is where you define the struct that will hold the configuration values</span>
<span class="hljs-comment">// cfg_name is the parameter name</span>
<span class="hljs-comment">// cfg_desc is the parameter description that will be shown in the command line help</span>
<span class="hljs-keyword">type</span> appConfig <span class="hljs-keyword">struct</span> {
	Host      <span class="hljs-keyword">string</span> <span class="hljs-string">`cfg_name:&quot;host&quot; cfg_desc:&quot;Server host&quot;`</span>
	Port      <span class="hljs-keyword">int</span>    <span class="hljs-string">`cfg_name:&quot;port&quot; cfg_desc:&quot;Server port&quot;`</span>
	SearchAPI <span class="hljs-keyword">string</span> <span class="hljs-string">`cfg_name:&quot;apis.search&quot; cfg_desc:&quot;Search API endpoint&quot;`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
	<span class="hljs-comment">// Instantiate the structure with default values</span>
	cfg := &amp;appConfig{
		Host:      <span class="hljs-string">&quot;localhost&quot;</span>,
		Port:      <span class="hljs-number">6000</span>,
		SearchAPI: <span class="hljs-string">&quot;google&quot;</span>,
	}

	<span class="hljs-comment">// Meta-Viper instance is loading the configuration from wherever is available: files, env, or input params</span>
	_, err := config.New(cfg, os.Args)
	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
		<span class="hljs-built_in">panic</span>(err)
	}
	log.Printf(<span class="hljs-string">&quot;Loaded Configuration %v...&quot;</span>, cfg)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now let&#8217;s see some examples how this command line tool is able to load configuration.</p>
</div>
<div class="listingblock">
<div class="title">Print usage (help)</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd --<span class="hljs-built_in">help</span>

Usage of flagsConfig:
    --apis.search string    Search API endpoint (default <span class="hljs-string">&quot;google&quot;</span>)
    --config string         Configuration name
    --config-dirs strings   Configuration directories search paths (default [.,config,configs,cfg])
    --host string           Server host (default <span class="hljs-string">&quot;localhost&quot;</span>)
    --port int              Server port (default 6000)
pflag: <span class="hljs-built_in">help</span> requested
<span class="hljs-built_in">exit</span> status 2</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Run with default values</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ cmd

2021/02/15 23:12:48 No configuration name has been specified, so no configuration file will be loaded. Using flags and environment variables.
2021/02/15 23:12:48 Loaded Configuration &amp;{localhost 6000 google}...</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Read the port from environment variable and host from input param</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ PORT=9999 cmd --host=myhost

2021/02/15 23:15:47 No configuration name has been specified, so no configuration file will be loaded. Using flags and environment variables.
2021/02/15 23:15:47 Loaded Configuration &amp;{myhost 9999 google}...</code></pre>
</div>
</div>
<div class="paragraph">
<p>The last example will aggregate all the possible sources of configuration, it will extend the previous one adding configuration from a file. So let&#8217;s create a configuration file:</p>
</div>
<div class="listingblock">
<div class="title">the-config.json</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
    <span class="hljs-attr">&quot;apis&quot;</span>: {
        <span class="hljs-attr">&quot;search&quot;</span>: <span class="hljs-string">&quot;duckduckgo&quot;</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Read configuration from the-config.json file, from environment and from input params</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ PORT=9999 cmd --host=myhost --config=the-config

2021/02/15 23:22:17 Loaded Configuration &amp;{myhost 9999 duckduckgo}...</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Here you can find a <a href="https://github.com/carlosvin/meta-viper/tree/master/examples/multi-env" target="_blank" rel="noopener">multi-environment example</a> a little bit more complete.
</td>
</tr>
</table>
</div>
</div>
</div>]]></content>
            <category term="Golang"/>
    <category term="cmd"/>
    <category term="tools"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Custom Maven Plugin: Override default build lifecycle</title>
            <link href="https://carlosvin.github.io/posts/creating-custom-maven-plugin-default/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/creating-custom-maven-plugin-default/es"/>   
            <id>https://carlosvin.github.io/posts/creating-custom-maven-plugin-default/en</id>
            <updated>2018-05-12T13:00:00.000Z</updated>
            <summary>How to create a custom Maven plugin which overrides default build lifecycle</summary>
            <content type="html"><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>I explained in previous article <a href="/posts/creating-custom-maven-plugin">Example how to create custom Maven Plugin</a> which <a href="https://maven.apache.org/ref/3.5.3/maven-core/lifecycles.html#site_Lifecycle">overrides site lifecycle</a>.</p>
</div>
<div class="paragraph">
<p>I have created another example to demonstrate how to override <a href="https://maven.apache.org/ref/3.5.3/maven-core/lifecycles.html#default_Lifecycle">default Maven build lifecycle</a>. Default build lifecycle is used to construct your software project, for example, it is executed when you run <code>mvn install</code> in a <code>jar</code> type project.</p>
</div>
<div class="paragraph">
<p>You can find source code example at <a href="https://github.com/carlosvin/lifecycle-maven-plugin" class="bare">https://github.com/carlosvin/lifecycle-maven-plugin</a>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
I&#8217;ve also created an <a href="https://maven.apache.org/guides/introduction/introduction-to-archetypes.html" target="_blank" rel="noopener">archetype</a> so you can easily play with the example.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_create_an_example_project">Create an example project</h2>
<div class="sectionbody">
<div class="listingblock">
<div class="title">Generate the project using archetype</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">mvn archetype:generate \
  -DarchetypeGroupId=com.github.carlosvin.archetype \
  -DartifactId=lifecycle-maven-plugin-archetype \
  -DarchetypeVersion=0.6</code></pre>
</div>
</div>
</div>
</div>]]></content>
            <category term="Maven"/>
    <category term="Java"/>
    <category term="Build Systems"/>
    <category term="Maven Plugins"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Example how to create custom Maven Plugin</title>
            <link href="https://carlosvin.github.io/posts/creating-custom-maven-plugin/en" />
               
            <id>https://carlosvin.github.io/posts/creating-custom-maven-plugin/en</id>
            <updated>2018-03-11T18:00:00.000Z</updated>
            <summary>Example to understand Maven plugins concepts and how to create a custom Maven plugin from scratch</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_maven_plugin_concepts">Maven plugin concepts</a></li>
<li><a href="#_create_your_custom_plugin_site_lifecycle">Create your custom plugin (Site Lifecycle)</a>
<ul class="sectlevel2">
<li><a href="#_project_structure">Project structure</a></li>
<li><a href="#_dependency_injection">Dependency Injection</a></li>
<li><a href="#_write_a_custom_mojo">Write a custom Mojo</a></li>
</ul>
</li>
<li><a href="#_unit_tests">Unit tests</a></li>
<li><a href="#_integration_tests">Integration tests</a>
<ul class="sectlevel2">
<li><a href="#_how_does_invoker_plugin_work">How does Invoker Plugin work?</a></li>
<li><a href="#_configure_invoker_plugin">Configure Invoker Plugin</a></li>
<li><a href="#_create_an_integration_test_project">Create an Integration Test Project</a></li>
</ul>
</li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Maven has lots of plugins to assist you in project construction, testing, packaging and deployment. For example if you want to compile C++ code instead of Java, you can use <a href="https://www.mojohaus.org/maven-native/native-maven-plugin/">native-maven-plugin</a>. But what if you need something more specific? Then you can create a custom Maven plugin.</p>
</div>
<div class="paragraph">
<p>I will explain how to create a simple custom maven plugin to generate static blog site from Markdown files. I know we can already do that with <a href="https://maven.apache.org/plugins/maven-site-plugin/examples/creating-content.html">maven-site-plugin</a> since version 3.3, I will just use it for learning purposes.</p>
</div>
<div class="paragraph">
<p>You can find the source code of this example at <a href="https://github.com/carlosvin/blog-maven-plugin" class="bare">https://github.com/carlosvin/blog-maven-plugin</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_maven_plugin_concepts">Maven plugin concepts</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a></dt>
<dd>
<p>An executable goal in Maven, e.g: <code>mvn your-plugin:your-mojo</code> will execute a maven goal <code>your-mojo</code> declared as part of <code>your-plugin</code>.</p>
</dd>
<dt class="hdlist1">Goal</dt>
<dd>
<p>It is equivalent to <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> execution.</p>
</dd>
<dt class="hdlist1">Lifecycle</dt>
<dd>
<p>It is a well-defined sequence of phases. Each phase consists of a sequence of goals. Let&#8217;s see an example of lifecycle, e.g: <code>FooLifecycle</code> has <code>clean</code>, <code>prepare</code> and <code>assemble</code> phases. Each of those phases has one of more goals. <strong>FooLifecycle</strong>:</p>
<div class="dlist">
<dl>
<dt class="hdlist1">clean</dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1"><strong>rmSources</strong></dt>
<dd>
<p>a goal to remove source files</p>
</dd>
<dt class="hdlist1"><strong>rmBuild</strong></dt>
<dd>
<p>a goal to remove files in cache directory</p>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">prepare</dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1"><strong>installDependencies</strong></dt>
<dd>
<p>a goal to download dependencies for the project</p>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">assemble</dt>
<dd>
<div class="dlist">
<dl>
<dt class="hdlist1"><strong>build</strong></dt>
<dd>
<p>a goal to compile source files</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
<div class="paragraph">
<p>To define a custom life-cycle similar to previous one, we will use <code>src/main/resources/META-INF/plexus/components.xml</code>, we will speak about that file in following sections. Normally is enough to override <a href="https://maven.apache.org/ref/3.5.3/maven-core/lifecycles.html">predefined lifecycles</a>, in this example, we will override <strong>site life-cycle</strong>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
You can find an introduction to Maven life-cycles at <a href="https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html" class="bare">https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html</a>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_create_your_custom_plugin_site_lifecycle">Create your custom plugin (Site Lifecycle)</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The plugin we are about to explain will <a href="https://maven.apache.org/ref/3.5.3/maven-core/lifecycles.html#site_Lifecycle">override site lifecycle</a>, which has only 2 default phases, so when we run <code>mvn site</code> using our new custom plugin it will execute the goals we are about to create.</p>
</div>
<div class="paragraph">
<p>Our plugin will work with <code>md</code> (for <a href="https://commonmark.org/" target="_blank" rel="noopener">Markdown</a>) file bindings: It will build and deploy the project using <a href="https://maven.apache.org/plugins/maven-deploy-plugin/">maven deployment plugin</a>.</p>
</div>
<div class="sect2">
<h3 id="_project_structure">Project structure</h3>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>src/main/java</code></dt>
<dd>
<p>Where Java source code is</p>
</dd>
<dt class="hdlist1"><code>src/main/resources/META-INF/plexus/components.xml</code></dt>
<dd>
<p>file to create/override maven lifecycles and artifact types. Here we can specify which goals will be executed when for an artifact type, for example, we can say that for an artifact of type <code>whatever</code> when we run <code>mvn foo</code> it will verify the files, run tests, run linter, compile and zip al generated files.</p>
</dd>
<dt class="hdlist1"><code>src/test/java</code></dt>
<dd>
<p>Unit tests folder.</p>
</dd>
<dt class="hdlist1"><code>src/it</code></dt>
<dd>
<p>Folder with all integration tests. Those integration tests are running actual projects and checking that outputs are as expected.</p>
</dd>
<dt class="hdlist1"><code>pom.xml</code></dt>
<dd>
<p>File to with Maven project description <a href="https://maven.apache.org/guides/introduction/introduction-to-the-pom.html">(Project Object Model)</a></p>
</dd>
</dl>
</div>
</div>
<div class="sect2">
<h3 id="_dependency_injection">Dependency Injection</h3>
<div class="paragraph">
<p>Maven has finally chosen <a href="https://maven.apache.org/maven-jsr330.html" target="_blank" rel="noopener">JSR-330</a> as <a href="https://javax-inject.github.io/javax-inject/">dependency injection standard</a> (previously it was Plexus Annotations API).</p>
</div>
<div class="paragraph">
<p>To use dependency injection with Maven we have to:</p>
</div>
<div class="paragraph">
<p>Add <code>javax.inject</code> dependency to <code>pom.xml</code>, so we can use <code>@Inject</code>, <code>@Named</code>, and <code>@Singleton</code> annotations in plugin implementation Java code.</p>
</div>
<div class="listingblock">
<div class="title">pom.xml</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>javax.inject<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>javax.inject<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Set up the <code>sisu-maven-plugin</code> to index the <a href="https://maven.apache.org/maven-jsr330.html" target="_blank" rel="noopener">JSR-330</a> components you want made available to Maven.</p>
</div>
<div class="listingblock">
<div class="title">pom.xml</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.eclipse.sisu<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>sisu-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.3.3<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>generate-index<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>main-index<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Add annotations to your Mojo, e.g:</p>
</div>
<div class="listingblock">
<div class="title">BuildMojo.java</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Mojo(name = &quot;build&quot;, defaultPhase = LifecyclePhase.COMPILE)</span> <b class="conum">(1)</b>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BuildMojo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractMojo</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> FileSetManager fileSetManager;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> MdToHtml mdToHtml;


    <span class="hljs-meta">@Inject</span> <b class="conum">(2)</b>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BuildMojo</span><span class="hljs-params">(FileSetManager fileSetManager, MdToHtml mdToHtml)</span> </span>{
        <span class="hljs-keyword">this</span>.fileSetManager = fileSetManager;
        <span class="hljs-keyword">this</span>.mdToHtml = mdToHtml;
        <span class="hljs-comment">//</span>
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>This annotation is not a dependency injection one, we will explain later what it is for.</p>
</li>
<li>
<p>It will inject an instance of FileSetManager and MdToHtml.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_write_a_custom_mojo">Write a custom <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a></h3>
<div class="paragraph">
<p>It is quite straightforward to implement a <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> class, we have to:</p>
</div>
<div class="sect3">
<h4 id="_1_implement_mojo_interface">1. Implement Mojo interface</h4>
<div class="paragraph">
<p>Your <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> class has to implement <code>org.apache.maven.plugin.Mojo</code>, although it is more convenient to extend <code>org.apache.maven.plugin.AbstractMojo</code>, an abstract class to provide most of the infrastructure required to implement a Mojo except for execute method. That interface and class are described at <a href="https://maven.apache.org/developers/mojo-api-specification.html">Mojo API</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BuildMojo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractMojo</span> </span>{
    <span class="hljs-comment">// ...</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_2_configure_mojo_with_java_5_annotations">2. Configure Mojo with Java 5 annotations</h4>
<div class="paragraph">
<p>Annotate <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> class with <code>@Mojo</code> and input parameters with <code>@Parameter</code>. Those annotations belong to another set of annotations to configure Mojos, <a href="https://maven.apache.org/plugin-tools/maven-plugin-plugin/examples/using-annotations.html">Plugin Tools Java5 Annotations</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-comment">/**
* Generate HTML files from Markdown files
*/</span>
<span class="hljs-meta">@Mojo(name = &quot;build&quot;, defaultPhase = LifecyclePhase.COMPILE)</span> <b class="conum">(1)</b>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BuildMojo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractMojo</span> </span>{

    <span class="hljs-comment">/**
    * Output directory path where HTML files are generated
    */</span>
    <span class="hljs-meta">@Parameter( <b class="conum">(2)</b>
      defaultValue = &quot;${project.reporting.outputDirectory}&quot;, <b class="conum">(3)</b>
      property = &quot;siteOutputDirectory&quot;, <b class="conum">(4)</b>
      required = true)</span>
    <span class="hljs-keyword">private</span> File outputDirectory;

    <span class="hljs-comment">/**
    * A specific &lt;code&gt;fileSet&lt;/code&gt; rule to select files and directories.
    * Fileset spec: https://maven.apache.org/shared/file-management/fileset.html
    */</span>
    <span class="hljs-meta">@Parameter</span>
    <span class="hljs-keyword">private</span> FileSet inputFiles;
    <span class="hljs-comment">//</span>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Configures Mojo name and default life-cycle phase. To execute the Mojo in this example we will use <code>mvn site:build</code>: <em>site</em> is the plugin name and <em>build</em> is <code>name</code> parameter.</p>
</li>
<li>
<p>We use <code>@Parameter</code> annotation to pass configuration parameters to Mojo.</p>
</li>
<li>
<p>You can use properties placeholder or any String. If the parameter type is not a String, then Maven will try to cast it.</p>
</li>
<li>
<p>It allows configuration of the Mojo parameter from the command line by referencing a system property that the user sets via the -D option. E.g: <code>mvn site:build -DsiteOutputDirectory=/var/www/html</code> will set siteOutputDirectory attribute to <code>/var/www/html</code>.</p>
</li>
</ol>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
More info in <a href="https://maven.apache.org/guides/plugin/guide-java-plugin-development.html#Parameters">Maven Plugin development guide in Parametera section</a>.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_3_implement_execute_method">3. Implement <em>execute</em> method</h4>
<div class="paragraph">
<p>As I have explained before at <a href="#_1_implement_mojo_interface">1. Implement Mojo interface</a>, our <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> class extends <code>org.apache.maven.plugin.AbstractMojo</code> which has one unimplemented method from <code>org.apache.maven.plugin.Mojo</code> interface. In that method we are going to implement the Maven goal logic.</p>
</div>
<div class="paragraph">
<p><a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> class instance is called from <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> execution life-cycle by invoking <code>execute()</code> method. Before calling <code>execute()</code>, <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> has performed some other tasks related with the Mojo:</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> instantiates Mojo and injects dependencies (<a href="#dependency-injection">Dependency Injection</a>).</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java">Mojo mojo = <span class="hljs-keyword">new</span> BuildMojo(fileSetManager, mdToHtml);</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> configures the <a href="https://maven.apache.org/plugin-developers/index.html" target="_blank" rel="noopener">Mojo</a> by assigning values to parameters.</p>
</div>
<div class="paragraph">
<p>I will simplify <code>execute</code> method implementation in the <a href="https://github.com/carlosvin/blog-maven-plugin">sample project in github</a>, because it is more complicated and this complexity is not relevant for learning purposes.</p>
</div>
<div class="paragraph">
<p><a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> calls execute method: <code>mojo.execute()</code>.</p>
</div>
<div class="listingblock">
<div class="title">BuildMojo.java</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> MojoExecutionException </span>{ <b class="conum">(1)</b>
    <span class="hljs-keyword">if</span> (inputFiles == <span class="hljs-keyword">null</span>) {
        setDefaultInput();
    }
    inputDirPath = Paths.get(inputFiles.getDirectory());

    String[] includedFiles = fileSetManager.getIncludedFiles(inputFiles); <b class="conum">(2)</b>

    outputDirPath = outputDirectory.toPath();
    <span class="hljs-keyword">if</span> (includedFiles == <span class="hljs-keyword">null</span> || includedFiles.length == <span class="hljs-number">0</span>) {
        getLog().warn(<span class="hljs-string">&quot;SKIP: There are no input files. &quot;</span> + getInputFilesToString()); <b class="conum">(3)</b>
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">if</span> (!outputDirectory.exists()) { <b class="conum">(4)</b>
            outputDirectory.mkdirs();
        }
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">for</span> (String f : includedFiles) {
                convertToHtml(Paths.get(f), outputDirectory); <b class="conum">(5)</b>
            }
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> MojoExecutionException(e.getLocalizedMessage(), e); <b class="conum">(6)</b>
        }
    }
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>If there is any error during execution, it should throw MojoExecutionException.</p>
</li>
<li>
<p>A way to get all selected files from <a href="https://maven.apache.org/shared/file-management/fileset.html">FileSet</a>.</p>
</li>
<li>
<p>AbstractMojo supplies logger functionality.</p>
</li>
<li>
<p>If output directory doesn&#8217;t exist, it will be created.</p>
</li>
<li>
<p>It converts each file Markdown to HTML.</p>
</li>
<li>
<p>Convert thrown exception to MojoExecutionException.</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_unit_tests">Unit tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In the example we use <a href="https://junit.org/junit4/">JUnit 4</a>, but you can use any other testing framework.</p>
</div>
<div class="paragraph">
<p>Firstly, you have to add the unit test library dependency to <code>pom.xml</code>.</p>
</div>
<div class="listingblock">
<div class="title">pom.xml</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.11<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then you just have to write your unit tests under <code>src/test/java</code> folder: <a href="https://github.com/carlosvin/blog-maven-plugin/blob/master/src/test/java/com/maven/plugins/blog/PathsTest.java">src/test/java/com/maven/plugins/blog/PathsTest.java</a>.</p>
</div>
<div class="paragraph">
<p>To run the unit tests you just need to execute <code>mvn test</code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_integration_tests">Integration tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The 2 most popular ways to perform integration tests on custom maven plugins are using <a href="https://maven.apache.org/surefire/maven-failsafe-plugin">maven-failsafe-plugin</a> or <a href="https://maven.apache.org/plugins/maven-invoker-plugin">maven-invoker-plugin</a>.</p>
</div>
<div class="paragraph">
<p>I&#8217;ve chosen <a href="https://maven.apache.org/plugins/maven-invoker-plugin">maven-invoker-plugin</a> because for me it is more straightforward. There is <a href="https://stackoverflow.com/questions/40010745/maven-invoker-plugin-vs-maven-failsafe-plugin-which-to-use-for-integration-test">an answer at stackoverflow where they explain thoroughly the differences between them</a>.</p>
</div>
<div class="sect2">
<h3 id="_how_does_invoker_plugin_work">How does Invoker Plugin work?</h3>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>We create projects to use our custom plugin under <code>src/it</code> folder, so our plugin will be applied to test projects.</p>
</li>
<li>
<p>Invoker plugin will simulate a previously configured <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> execution.</p>
</li>
<li>
<p>After Maven execution, A validation script will check if our plugin outputs are the expected ones. For example, if our plugin is supposed to generate a file named <code>foo.file</code>, verification plugin will check if that file exists, if it doesn&#8217;t, integration test will fail.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_configure_invoker_plugin">Configure Invoker Plugin</h3>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-invoker-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.0.1<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">postBuildHookScript</span>&gt;</span>verify<span class="hljs-tag">&lt;/<span class="hljs-name">postBuildHookScript</span>&gt;</span> <b class="conum">(3)</b>
        <span class="hljs-tag">&lt;<span class="hljs-name">showVersion</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">showVersion</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">streamLogs</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">streamLogs</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">noLog</span>&gt;</span>false<span class="hljs-tag">&lt;/<span class="hljs-name">noLog</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">showErrors</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">showErrors</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">executions</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">execution</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>integration-test<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">goals</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>install<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span> <b class="conum">(1)</b>
                <span class="hljs-tag">&lt;<span class="hljs-name">goal</span>&gt;</span>run<span class="hljs-tag">&lt;/<span class="hljs-name">goal</span>&gt;</span> <b class="conum">(2)</b>
            <span class="hljs-tag">&lt;/<span class="hljs-name">goals</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">execution</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">executions</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><code>invoker:install</code> will be executed during the phase pre-integration-test and will install the main project artifact into target/local-repo.</p>
</li>
<li>
<p><code>invoker:run</code> will be executed during the integration-test phase and it will execute all defined integration tests under <code>src/it</code> folder.</p>
</li>
<li>
<p>It configures invoker plugin to execute validation script after integration test project execution. This script may be written with either BeanShell or Groovy (verify.groovy or verify.bsh).</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>We have used other properties to show errors, show maven log and save it to a file.</p>
</div>
<div class="paragraph">
<p>You can check all <code>invoker:run</code> configuration properties at <a href="https://maven.apache.org/plugins/maven-invoker-plugin/run-mojo.html" class="bare">https://maven.apache.org/plugins/maven-invoker-plugin/run-mojo.html</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_create_an_integration_test_project">Create an Integration Test Project</h3>
<div class="paragraph">
<p>It is a project we use to execute custom plugin goals, so we can validate if it produces the expected output.</p>
</div>
<div class="paragraph">
<p>There are 3 important files matching with <a href="http://wiki.c2.com/?ArrangeActAssert" target="_blank" rel="noopener">AAA</a> phases ("Arrange-Act-Assert").</p>
</div>
<div class="sect3">
<h4 id="_arrange_pom_xml">Arrange: pom.xml</h4>
<div class="paragraph">
<p>This file is a project using our custom plugin.</p>
</div>
<div class="paragraph">
<p><a href="https://github.com/carlosvin/blog-maven-plugin/blob/master/src/it/md-html/pom.xml">src/it/md-html/pom.xml</a></p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span>
<span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.maven.plugins.it<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>simple-it<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.0-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>@project.groupId@<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>@project.artifactId@<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>@project.version@<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>It is a very simple pom file where we use placeholders to reference to our plugin under test. When invoker plugin executes following pom file, firstly will replace those placeholders to reference to the latest version sof our custom plugin which was recently installed in the local repository:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.maven.plugins<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>blog<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In that way invoker plugin ensures it is testing the latest version of current project.</p>
</div>
</div>
<div class="sect3">
<h4 id="_act_invoker_properties">Act: invoker.properties</h4>
<div class="paragraph">
<p>It configures how test project will be executed.</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/blog-maven-plugin/blob/master/src/it/md-html/invoker.properties">src/it/md-html/invoker.properties</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-properties" data-lang="properties"><span class="hljs-meta">invoker.goals</span> = <span class="hljs-string">blog:build</span>
<span class="hljs-meta">invoker.name</span> = <span class="hljs-string">Test build MD</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>It will execute <code>mvn blog:build</code>, a goal defined in our custom plugin under example or what is the same, it will execute <a href="https://github.com/carlosvin/blog-maven-plugin/blob/master/src/main/java/com/maven/plugins/blog/BuildMojo.java" target="_blank" rel="noopener">Build Mojo</a> described in section <a href="#_write_a_custom_mojo">Write a custom Mojo</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_assert_verify_groovy">Assert: verify.groovy</h4>
<div class="paragraph">
<p>It is the script to check that plugin execution generated the expected results.</p>
</div>
<div class="paragraph">
<p>Verification script, it is checking if <code>target/site/README.html</code> file was generated by the plugin.</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/blog-maven-plugin/blob/master/src/it/md-html/verify.groovy">src/it/md-html/verify.groovy</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-groovy" data-lang="groovy">File generated = <span class="hljs-keyword">new</span> File( basedir, <span class="hljs-string">&quot;target/site/README.html&quot;</span> );

<span class="hljs-keyword">assert</span> generated.isFile()</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>]]></content>
            <category term="Maven"/>
    <category term="Java"/>
    <category term="Build Systems"/>
    <category term="maven-site-plugin"/>
    <category term="Maven Plugins"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Parameterized Tests in Cypress</title>
            <link href="https://carlosvin.github.io/posts/cypress-parametrized-dynamic-tests/en" />
               
            <id>https://carlosvin.github.io/posts/cypress-parametrized-dynamic-tests/en</id>
            <updated>2021-01-06T00:00:00.000Z</updated>
            <summary>How to write parameterized tests in Cypress</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_explicit_input_data_set">Explicit input data set</a></li>
<li><a href="#_generated_input_data_set">Generated input data set</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a> is a testing framework for anything running on a web browser. I am using it to test this site and I&#8217;ve talked before about it in the post <a href="https://carlosvin.github.io/posts/this-is-sapper/en#_testing">"This is Sapper"</a>.</p>
</div>
<div class="paragraph">
<p>In this post I won&#8217;t explain how to use <a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>, they have a pretty nice documentation: <a href="https://docs.cypress.io/guides/getting-started/installing-cypress.html" target="_blank" rel="noopener">Getting started with Cypress</a>.</p>
</div>
<div class="paragraph">
<p>I will stick to the parameterized tests topic.</p>
</div>
<div class="paragraph">
<p><strong>Parameterized tests</strong>: Also known as dynamic tests, it is an useful technique where you can specify an input dataset and the test case will be repeated for each element in the dataset.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_explicit_input_data_set">Explicit input data set</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Since sometimes you can’t run the test for all the possible inputs, you can select a set of meaningful data to test.</p>
</div>
<div class="listingblock">
<div class="title">Example checking that the relevant pages in the site have valid HTML syntax</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript">describe(<span class="hljs-string">&#x27;validate pages&#x27;</span>, <span class="hljs-function">() =&gt;</span> {
    [ <b class="conum">(1)</b>
        <span class="hljs-string">&quot;/&quot;</span>,
        <span class="hljs-string">&quot;/categories&quot;</span>,
        <span class="hljs-string">&quot;/categories/sapper&quot;</span>,
        <span class="hljs-string">&quot;/posts/creating-custom-maven-plugin-default&quot;</span>,
        <span class="hljs-string">&quot;/posts/choosing-modern-cpp-stack&quot;</span>,
        <span class="hljs-string">&quot;/posts/cpp-mutex&quot;</span>,
        <span class="hljs-string">&quot;/posts/cpp-pragma-pack&quot;</span>,
        <span class="hljs-string">&quot;/posts/creating-custom-maven-plugin&quot;</span>,
        <span class="hljs-string">&quot;/posts/delete-html-tags-py-django&quot;</span>,
        <span class="hljs-string">&quot;/posts/gradle-cpp&quot;</span>,
        <span class="hljs-string">&quot;/posts/java-embedded-db-performance-comparison&quot;</span>,
        <span class="hljs-string">&quot;/posts/react-typescript-parcel&quot;</span>,
        <span class="hljs-string">&quot;/posts/pwa-lessons-learned-cra&quot;</span>,
    ].forEach(<span class="hljs-function">(<span class="hljs-params">url</span>) =&gt;</span> { <b class="conum">(2)</b>
        it(<span class="hljs-string">`should be valid HTML <span class="hljs-subst">${url}</span>`</span>, <span class="hljs-function">() =&gt;</span> { <b class="conum">(3)</b>
            cy.visit(url)
            cy.htmlvalidate()
        })
    })
})</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>List with relevant pages to validate</p>
</li>
<li>
<p>Iterate over the list of pages</p>
</li>
<li>
<p>Test case execution for selected page</p>
</li>
</ol>
</div>
<div class="imageblock">
<div class="content">
<img src="/posts/cypress-parametrized-dynamic-tests/html-validation.png" alt="Test results" width="100%">
</div>
<div class="title">Figure 1. Test results</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_generated_input_data_set">Generated input data set</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Instead of explicitly define a data set, you can generate it, for example, creating a random data set.</p>
</div>
<div class="listingblock">
<div class="title">Example checking that any generated random number is less than 0</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript">describe(<span class="hljs-string">&#x27;random&#x27;</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> inputData = <span class="hljs-built_in">Array</span>.from(<span class="hljs-built_in">Array</span>(<span class="hljs-number">100</span>)).map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> <span class="hljs-built_in">Math</span>.random()) <b class="conum">(1)</b>
    inputData.forEach(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> { <b class="conum">(2)</b>
        it(<span class="hljs-string">`should be valid <span class="hljs-subst">${x}</span>`</span>, <span class="hljs-function">() =&gt;</span> { <b class="conum">(3)</b>
		    expect(x).to.be.lessThan(<span class="hljs-number">1</span>)
        })
    })
})</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>It generates an array of 100 random numbers</p>
</li>
<li>
<p>Iterate over the generated array</p>
</li>
<li>
<p>Test case execution</p>
</li>
</ol>
</div>
<div class="imageblock text-center">
<div class="content">
<img src="/posts/cypress-parametrized-dynamic-tests/random-validation.png" alt="Test results">
</div>
<div class="title">Figure 2. Test results</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Please check the <a href="https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/fundamentals__dynamic-tests">cypress official examples to learn more about dynamic/parameterized testing</a>.
</td>
</tr>
</table>
</div>
</div>
</div>]]></content>
            <category term="Testing"/>
    <category term="Cypress"/>
    <category term="Javascript"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Depurar librería generada con libtool</title>
            <link href="https://carlosvin.github.io/posts/debug-libtool-lib/es" />
               
            <id>https://carlosvin.github.io/posts/debug-libtool-lib/es</id>
            <updated>2013-02-01T14:30:00.000Z</updated>
            <summary>Cómo depurar un librería generada con libtool</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>Cuando vamos a depurar un ejecutable que utiliza una librería generada con <a href="https://www.gnu.org/software/libtool/libtool.html" target="_blank" rel="noopener">libtool</a><sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>, es posible que nos encontremos con el siguiente error:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ gdb ./tests-mylib
<span class="hljs-string">&quot;tests-mylib&quot;</span>: not <span class="hljs-keyword">in</span> executable format: File format not recognized</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>libmylib.so</code></dt>
<dd>
<p>es una librería dinámica generada con <a href="https://www.gnu.org/software/libtool/libtool.html" target="_blank" rel="noopener">libtool</a>.</p>
</dd>
<dt class="hdlist1"><code>tests-mylib</code></dt>
<dd>
<p>es un ejecutable que utiliza la librería mylib.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>Para los que estéis pensando que se me ha olvidado poner la opción de compilación <code>-g</code>, este error ocurre aunque utilicemos <code>-g</code>.</p>
</div>
<div class="paragraph">
<p>El error es debido a que estamos intentando ejecutar un script generado por <a href="https://www.gnu.org/software/libtool/libtool.html" target="_blank" rel="noopener">libtool</a>, es una envoltura sobre el programa real, para facilitar la ejecución de éste <sup class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnotedef_2" title="View footnote.">2</a>]</sup>.</p>
</div>
<div class="listingblock">
<div class="title">Para poder depurar nuestro programa de prueba <code>tests-mylib</code></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">libtool --mode=execute gdb tests-mylib</code></pre>
</div>
</div>
<div id="footnotes">
<hr>
<div class="footnote" id="_footnotedef_1">
<a href="#_footnoteref_1">1</a>. Herramienta que pertenece a la <a href="">Autotools</a> usada para crear bibliotecas de software portables.
</div>
<div class="footnote" id="_footnotedef_2">
<a href="#_footnoteref_2">2</a>. Más información en <a href="https://www.gnu.org/software/libtool/manual/libtool.html#Debugging-executables">documentación de libtool</a>
</div>
</div>]]></content>
            <category term="C++"/>
    <category term="Autotools"/>
    <category term="GNU"/>
    <category term="Tips and Tricks"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Eliminar etiquetas HTML</title>
            <link href="https://carlosvin.github.io/posts/delete-html-tags-py-django/es" />
               
            <id>https://carlosvin.github.io/posts/delete-html-tags-py-django/es</id>
            <updated>2012-10-02T09:30:00.000Z</updated>
            <summary>Cómo eliminar etiquetas HTML utilizando Python o más fácil aún, utilizando Django</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_con_python">Con Python</a></li>
<li><a href="#_django">Django</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>A continuación veremos cómo eliminar las etiquetas HTML de una cadena de caracteres.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_con_python">Con <a href="https://www.python.org">Python</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Función encargada de eliminar las etiquetas HTML:</p>
</div>
<div class="listingblock">
<div class="title">main.py</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-keyword">import</span> re

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">strip_tags</span>(<span class="hljs-params">value</span>):</span>
    <span class="hljs-keyword">return</span> re.sub(<span class="hljs-string">r&#x27;&lt;[^&gt;]*?&gt;&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>, value)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Vamos a hacer una prueba un fragmento de HTML a la función <code>strip_tags</code>:</p>
</div>
<div class="listingblock">
<div class="title">main.py</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-keyword">import</span> re

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">strip_tags</span>(<span class="hljs-params">value</span>):</span>
    <span class="hljs-keyword">return</span> re.sub(<span class="hljs-string">r&#x27;&lt;[^&gt;]*?&gt;&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>, value)

html_text = <span class="hljs-string">&quot;&quot;&quot;
    &lt;!DOCTYPE HTML&gt;
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;Title&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;p&gt;Paragraph&lt;/p&gt;
        &lt;/body&gt;
    &lt;/html&gt;&quot;&quot;&quot;</span>

print(strip_tags(html_text))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Si ejecutamos el script tenemos como resultado:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">Title

Paragraph</code></pre>
</div>
</div>
<div class="paragraph">
<p>Si con <a href="https://www.python.org">Python</a> ha sido fácil, vamos a ver con <a href="https://www.djangoproject.com">Django</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_django"><a href="https://www.djangoproject.com">Django</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://www.djangoproject.com">Django</a> una ofrece función para esto: <a href="https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.strip_tags">strip_tags</a>.</p>
</div>
<div class="paragraph">
<p>Antes, solo hay que instalar la librería: <code>pip install django</code>.</p>
</div>
<div class="listingblock">
<div class="title">main.py</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-keyword">from</span> django.utils.html <span class="hljs-keyword">import</span> strip_tags

html_text = <span class="hljs-string">&quot;&quot;&quot;
    &lt;!DOCTYPE HTML&gt;
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;Title&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;p&gt;Paragraph&lt;/p&gt;
        &lt;/body&gt;
    &lt;/html&gt;&quot;&quot;&quot;</span>

<span class="hljs-built_in">print</span> (strip_tags(html_text))</code></pre>
</div>
</div>
</div>
</div>]]></content>
            <category term="Python"/>
    <category term="Django"/>
    <category term="HTML"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Git proxy configuration</title>
            <link href="https://carlosvin.github.io/posts/git-proxy-config/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/git-proxy-config/es"/>   
            <id>https://carlosvin.github.io/posts/git-proxy-config/en</id>
            <updated>2012-11-15T11:00:00.000Z</updated>
            <summary>How to configure git to work through a proxy</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>Sometimes working through a proxy is pretty tedious.</p>
</div>
<div class="paragraph">
<p>We are going to describe how to configure <a href="https://git-scm.com" class="bare">https://git-scm.com</a> to work through a proxy.</p>
</div>
<div class="listingblock">
<div class="title">http proxy</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">git config --global http.proxy http://&lt;username&gt;:&lt;password&gt;@&lt;ip_host&gt;:&lt;port&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">https proxy</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">git config --global https.proxy https://&lt;username&gt;:&lt;password&gt;@&lt;ip_host&gt;:&lt;port&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">to disable using proxy</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">git config --global --<span class="hljs-built_in">unset</span> http.proxy</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p><code>username</code>: The proxy user name.</p>
</li>
<li>
<p><code>ip_host</code>: Proxy host address.</p>
</li>
<li>
<p><code>port</code>: Proxy listening port.</p>
</li>
<li>
<p><code>password</code>: Your proxy password.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>More info in <a href="https://git-scm.com/docs/git-config">official Git configuration</a>.</p>
</div>]]></content>
            <category term="Git"/>
    <category term="Proxy"/>
    <category term="Tips and Tricks"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Build C++ project with Gradle</title>
            <link href="https://carlosvin.github.io/posts/gradle-cpp/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/gradle-cpp/es"/>   
            <id>https://carlosvin.github.io/posts/gradle-cpp/en</id>
            <updated>2014-09-27T00:00:00.000Z</updated>
            <summary>How to build a C++ project using Gradle</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_introduction">Introduction</a></li>
<li><a href="#_case_study">Case study</a>
<ul class="sectlevel2">
<li><a href="#_project_structure">Project Structure</a></li>
<li><a href="#_c_application">C++ Application</a></li>
<li><a href="#_building_with_gradle">Building with Gradle</a></li>
<li><a href="#_try_it_yourself">Try it yourself</a></li>
</ul>
</li>
<li><a href="#_conclusions">Conclusions</a></li>
</ul>
</div>
<div class="sect1">
<h2 id="_introduction">Introduction</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I am more and more worried about building, dependency management and distribution of my projects. I&#8217;d like to find a tool that unifies those processes with independence of the language. I know several tools which almost fit to what I&#8217;m looking for, like <a href="https://www.scons.org" target="_blank" rel="noopener">SCons</a>, <a href="https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html#Autotools-Introduction" target="_blank" rel="noopener">Autotools</a>, <a href="https://ant.apache.org" target="_blank" rel="noopener">Ant</a>, <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> and lately <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>.</p>
</div>
<div class="paragraph">
<p>I&#8217;ve made several projects with <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>, but always they were <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> and <a href="https://developer.android.com/studio/build" target="_blank" rel="noopener">Android</a> projects. <span class="line-through">In <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> projects I&#8217;ve found a <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a> replacement, because it is faster, easier and less verbose</span>. <strong>Update 2020</strong>: With the experience, now if I have to pick a build system for a <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> project I&#8217;d pick <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a>, especially for a professional project, but it is not the topic of this post.</p>
</div>
<div class="paragraph">
<p>About <a href="https://developer.android.com/studio/build" target="_blank" rel="noopener">Android</a> projects I suffered the early adoption of <a href="https://developer.android.com/sdk/installing/studio-build.html" target="_blank" rel="noopener">Android Studio + Gradle</a>, although currently I think the are more mature and they work fine.</p>
</div>
<div class="paragraph">
<p>First of all, I have to say: building C/C++/Objective-C projects with <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> is in <a href="https://docs.gradle.org/current/userguide/feature_lifecycle.html#sec:incubating_state" target="_blank" rel="noopener">incubation</a> phase, although now we can perform advanced tasks like:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Generation several artifacts within same project (libraries and executables).</p>
</li>
<li>
<p>Dependency management between artifacts (no versions).</p>
</li>
<li>
<p>Different "flavors" of the same software, e.g: we can generate a "Community" release and other one with more enabled features called "Enterprise".</p>
</li>
<li>
<p>It allows multi-platform binary generation.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>As I said, this plugin is still having limitations although they are working on it: <a href="https://blog.gradle.org/state-and-future-of-the-gradle-software-model#a-way-forward">Gradle C++ roadmap</a>. <span class="line-through">If they achieve it I&#8217;ll leave <a href="https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html#Autotools-Introduction" target="_blank" rel="noopener">Autotools</a> (I&#8217;m going to regret saying that)</span>. <strong>Update 2020</strong>: Actually few years later I am not using <a href="https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html#Autotools-Introduction" target="_blank" rel="noopener">Autotools</a>, neither <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>, but I am using <a href="https://mesonbuild.com/">Meson</a> and considering <a href="https://docs.bazel.build/versions/master/tutorial/cpp.html">Bazel</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_case_study">Case study</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I&#8217;ve extracted all the case study from <a href="https://docs.gradle.org/current/userguide/native_software.html">Gradle user guide for native software</a>. I&#8217;ve adapted the project to be multi-platform with 2 versions "Community" and "Enterprise".</p>
</div>
<div class="paragraph">
<p>The application consists of an executable and a dynamic library. The executable will use the library.</p>
</div>
<div class="paragraph">
<p><a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> also is able to generate a distributable version and a debug version.</p>
</div>
<div class="paragraph">
<p>You can fork the code on <a href="https://github.com/carlosvin/cpp_gradle" class="bare">https://github.com/carlosvin/cpp_gradle</a>.</p>
</div>
<div class="sect2">
<h3 id="_project_structure">Project Structure</h3>
<div class="paragraph">
<p>We can create whichever directory structure, but it is easier using the proposed by <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>, if not we&#8217;ll have to specify where the code is located.</p>
</div>
<div class="paragraph">
<p>This is the project structure:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">gradle-cpp</dt>
<dd>
<p>Root directory.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">build.gradle</dt>
<dd>
<p>File where is configured <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> project, it is the equivalent to: build.xml for <a href="https://ant.apache.org" target="_blank" rel="noopener">Ant</a>, <a href="">Makefile</a> for C/C++ or pom.xml for <a href="https://maven.apache.org" target="_blank" rel="noopener">Maven</a>.</p>
</dd>
<dt class="hdlist1">src</dt>
<dd>
<p>Folder where the source code is located.</p>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">hello</dt>
<dd>
<p>This folder contains the module hello. This module will generate hello library.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">cpp</dt>
<dd>
<p>This folder contains C++ source files.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">Hello.cpp</dt>
<dd>
<p> File with the implementation of Hello class.</p>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">headers</dt>
<dd>
<p>Folder with header files.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">Hello.h</dt>
<dd>
<p>Class Hello declaration.</p>
</dd>
<dt class="hdlist1">Msg.h</dt>
<dd>
<p>File with constants declarations.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">main</dt>
<dd>
<p>This folder contains the module which produces the executable that uses hello library.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">cpp</dt>
<dd>
<p>This folder contains C++ source files.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">main.cpp</dt>
<dd>
<p>Source code of main function.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">build</dt>
<dd>
<p>Folder created automatically by <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> where it leaves all execution results like unit tests reports, compiled files, package distributions, etc.</p>
</dd>
</dl>
</div>
</div>
<div class="sect2">
<h3 id="_c_application">C++ Application</h3>
<div class="paragraph">
<p>It consists of an executable that uses the functionality implemented at <code>hello</code> library.</p>
</div>
<div class="listingblock">
<div class="title">main.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&quot;Hello.h&quot;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> ** argv)</span>
</span>{
    <span class="hljs-function">Hello <span class="hljs-title">hello</span> <span class="hljs-params">(<span class="hljs-string">&quot;Pepito&quot;</span>)</span></span>;
    hello.sayHello(<span class="hljs-number">10</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>hello</code> library allows greet <code>n</code> <sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup> times to someone who is passed as argument to constructor class.</p>
</div>
<div class="listingblock">
<div class="title">Hello.h</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Hello</span>
{</span>
    <span class="hljs-keyword">private</span>:
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> * who;
    <span class="hljs-keyword">public</span>:
        Hello(<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> * who);
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sayHello</span><span class="hljs-params">(<span class="hljs-keyword">unsigned</span> n = <span class="hljs-number">1</span>)</span></span>;
};</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_building_with_gradle">Building with <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a></h3>
<div class="sect3">
<h4 id="_base_case">Base case</h4>
<div class="paragraph">
<p>The only we need to build the application with <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> is: having <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a><sup class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnotedef_2" title="View footnote.">2</a>]</sup> and the file <code>build.gradle</code>.</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-groovy" data-lang="groovy">apply <span class="hljs-attr">plugin:</span> <span class="hljs-string">&#x27;cpp&#x27;</span>

model {
  components {
    hello(NativeLibrarySpec) {}
    main(NativeExecutableSpec) {
      binaries.all {
        lib <span class="hljs-attr">library:</span> <span class="hljs-string">&quot;hello&quot;</span>
      }
    }
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this simple file, we&#8217;ll be able to compile and install the application in Debug mode for the platform where we are executing <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> (in my case X64).</p>
</div>
<div class="paragraph">
<p>If we execute <code>gradle task</code> from the root of the project, we&#8217;ll get all the tasks we can do with <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>.</p>
</div>
<div class="paragraph">
<p>In our case, we just want our compiled application ready to run, so we have to execute: <code>gradle installMainExecutable</code>.</p>
</div>
<div class="paragraph">
<p>Once execution has finished, we can run the program calling to `build/install/mainExecutable/main`<sup class="footnote">[<a id="_footnoteref_3" class="footnote" href="#_footnotedef_3" title="View footnote.">3</a>]</sup>.</p>
</div>
<div class="listingblock">
<div class="title">Output</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ build/install/mainExecutable/main
1.  Hello Mr. Pepito (Community)
2.  Hello Mr. Pepito (Community)
3.  Hello Mr. Pepito (Community)
4.  Hello Mr. Pepito (Community)
5.  Hello Mr. Pepito (Community)
6.  Hello Mr. Pepito (Community)
7.  Hello Mr. Pepito (Community)
8.  Hello Mr. Pepito (Community)
9.  Hello Mr. Pepito (Community)
10. Hello Mr. Pepito (Community)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_different_flavors">Different "Flavors"</h4>
<div class="paragraph">
<p>With a few lines more we can generate different versions of same application. In our example we are going to build "Community" and "Enterprise" flavors.</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-groovy" data-lang="groovy">apply <span class="hljs-attr">plugin:</span> <span class="hljs-string">&#x27;cpp&#x27;</span>

model {
  flavors {
      community
      enterprise
  }

  components {
    hello(NativeLibrarySpec) {
      binaries.all {
        <span class="hljs-keyword">if</span> (flavor == flavors.enterprise) {
          cppCompiler.define <span class="hljs-string">&quot;ENTERPRISE&quot;</span>
        }
      }
    }
    main(NativeExecutableSpec) {
      binaries.all {
        lib <span class="hljs-attr">library:</span> <span class="hljs-string">&quot;hello&quot;</span>
        }
    }
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>We also have to prepare our application to use compilation parameters.</p>
</div>
<div class="listingblock">
<div class="title">Msg.h</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">ifdef</span> ENTERPRISE</span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> * EDITION = <span class="hljs-string">&quot;Enterprise&quot;</span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> * EDITION = <span class="hljs-string">&quot;Community&quot;</span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In this way it selects a string depending on used flavor.</p>
</div>
<div class="paragraph">
<p>If we execute <code>gradle clean task</code> in the root folder, we&#8217;ll get more available tasks. Before, we had <code>installMainExecutable</code> which has been replaced by <code>installCommunityMainExecutable</code> and <code>installEnterpriseMainExecutable</code>.</p>
</div>
<div class="paragraph">
<p>If we execute both tasks, we&#8217;ll get the application installed in both flavors:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash"><span class="hljs-variable">$gradle</span> installEnterpriseMainExecutable installCommunityMainExecutable

:compileEnterpriseHelloSharedLibraryHelloCpp
:linkEnterpriseHelloSharedLibrary
:enterpriseHelloSharedLibrary
:compileEnterpriseMainExecutableMainCpp
:linkEnterpriseMainExecutable
:enterpriseMainExecutable
:installEnterpriseMainExecutable
:compileCommunityHelloSharedLibraryHelloCpp
:linkCommunityHelloSharedLibrary
:communityHelloSharedLibrary
:compileCommunityMainExecutableMainCpp
:linkCommunityMainExecutable
:communityMainExecutable
:installCommunityMainExecutable

BUILD SUCCESSFUL
Total time: 9.414 secs</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now we can run the application in both flavors:</p>
</div>
<div class="listingblock">
<div class="title">Community</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ build/install/mainExecutable/community/main
1.      Hello Mr. Pepito        (Community)
2.      Hello Mr. Pepito        (Community)
3.      Hello Mr. Pepito        (Community)
4.      Hello Mr. Pepito        (Community)
5.      Hello Mr. Pepito        (Community)
6.      Hello Mr. Pepito        (Community)
7.      Hello Mr. Pepito        (Community)
8.      Hello Mr. Pepito        (Community)
9.      Hello Mr. Pepito        (Community)
10.     Hello Mr. Pepito        (Community)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Enterprise</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ build/install/mainExecutable/enterprise/main
1.      Hello Mr. Pepito        (Enterprise)
2.      Hello Mr. Pepito        (Enterprise)
3.      Hello Mr. Pepito        (Enterprise)
4.      Hello Mr. Pepito        (Enterprise)
5.      Hello Mr. Pepito        (Enterprise)
6.      Hello Mr. Pepito        (Enterprise)
7.      Hello Mr. Pepito        (Enterprise)
8.      Hello Mr. Pepito        (Enterprise)
9.      Hello Mr. Pepito        (Enterprise)
10.     Hello Mr. Pepito        (Enterprise)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_release_or_debug">Release or Debug</h4>
<div class="paragraph">
<p>By default <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> compiles in Debug mode, but we can add the Release mode which enables several optimizations and remove debug flags<sup class="footnote">[<a id="_footnoteref_4" class="footnote" href="#_footnotedef_4" title="View footnote.">4</a>]</sup>.</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-groovy" data-lang="groovy">apply <span class="hljs-attr">plugin:</span> <span class="hljs-string">&#x27;cpp&#x27;</span>
model {
    buildTypes {
        debug
        release
    }
<span class="hljs-comment">// ... the rest of file below doesn&#x27;t change</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If we execute <code>gradle clean task</code> we will get more tasks, they have been split, for example <code>installCommunityMainExecutable</code> has been split in <code>installDebugCommunityMainExecutable</code> and <code>installReleaseCommunityMainExecutable</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_multi_platform">Multi-platform</h4>
<div class="paragraph">
<p>Also we can use cross-compiling features provided by compilers and generate native components for other platforms. To do so we just have to add the supported platforms.</p>
</div>
<div class="paragraph">
<p>This only works if we have installed the <a href="https://en.wikipedia.org/wiki/Toolchain" target="_blank" rel="noopener">Toolchain</a> for the target platform.</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-groovy" data-lang="groovy">apply <span class="hljs-attr">plugin:</span> <span class="hljs-string">&#x27;cpp&#x27;</span>

model {
  buildTypes {
    debug
    release
  }

  platforms {
    x86 {
      architecture <span class="hljs-string">&quot;x86&quot;</span>
    }
    x64 {
      architecture <span class="hljs-string">&quot;x86_64&quot;</span>
    }
    itanium {
      architecture <span class="hljs-string">&quot;ia-64&quot;</span>
    }
  }

  flavors {
    community
    enterprise
  }

  components {
    hello(NativeLibrarySpec) {
      binaries.all {
        <span class="hljs-keyword">if</span> (flavor == flavors.enterprise) {
          cppCompiler.define <span class="hljs-string">&quot;ENTERPRISE&quot;</span>
        }
      }
    }
    main(NativeExecutableSpec) {
      binaries.all {
        lib <span class="hljs-attr">library:</span> <span class="hljs-string">&quot;hello&quot;</span>
      }
    }
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When execute <code>gradle clean task</code> we get the different build options we have.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
In this example, we can build different versions of the application in different flavors for different platforms in Debug or Release mode.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_try_it_yourself">Try it yourself</h3>
<div class="paragraph">
<p>You can find the project at <a href="https://github.com/carlosvin/cpp_gradle" class="bare">https://github.com/carlosvin/cpp_gradle</a>.</p>
</div>
<div class="paragraph">
<p>Requirements:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://www.java.com" target="_blank" rel="noopener">Java</a> 6 or higher.</p>
</li>
<li>
<p>An installed compiler (e.g <a href="">GCC</a>)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You just have to follow next steps:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p><code>git clone <a href="mailto:git@github.com">git@github.com</a>:carlosvin/cpp_gradle.git</code></p>
</li>
<li>
<p><code>cd cpp_gradle</code></p>
</li>
<li>
<p><code>./gradlew task</code> or <code>./gradlew.bat task</code> if you are in Windows. In this way you&#8217;ll see available tasks for this project. The first execution will take more time, because it downloads <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> runtime.</p>
</li>
<li>
<p>If you are in a 64 bits platform, you can use this command to install the application: <code>./gradlew installX64ReleaseEnterpriseMainExecutable</code>.</p>
</li>
<li>
<p>Run the application you just built: <code>build/install/mainExecutable/x64ReleaseEnterprise/main</code>.</p>
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_conclusions">Conclusions</h2>
<div class="sectionbody">
<div class="paragraph">
<p>With a tiny configuration file, we have many different build combinations.</p>
</div>
<div class="paragraph">
<p><a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> for C++ has a promising future, I hope it follows the steps of <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> and <a href="https://developer.android.com/studio/build" target="_blank" rel="noopener">Android</a> support.</p>
</div>
<div class="paragraph">
<p>It is well supported by continuous integration systems.</p>
</div>
<div class="paragraph">
<p>It has many plugins and features.</p>
</div>
<div class="paragraph">
<p><a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> for C++ is a feature under development, we have to be careful:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Don&#8217;t use it in production environments.</p>
</li>
<li>
<p>Many things can change or disappear.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The full example is on <a href="https://github.com/carlosvin/cpp_gradle" class="bare">https://github.com/carlosvin/cpp_gradle</a>. I recommend you to <a href="#_try_it_yourself">Try it yourself</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
If you find any issue in this example, please write a comment, open a defect or fix it yourself at <a href="https://github.com/carlosvin/cpp_gradle" class="bare">https://github.com/carlosvin/cpp_gradle</a>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>More info at <a href="https://docs.gradle.org/current/userguide/native_software.html">Getting Started Gradle Native</a>.</p>
</div>
</div>
</div>
<div id="footnotes">
<hr>
<div class="footnote" id="_footnotedef_1">
<a href="#_footnoteref_1">1</a>. 'n' Positive integer
</div>
<div class="footnote" id="_footnotedef_2">
<a href="#_footnoteref_2">2</a>. Actually <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> is not required if we use the "wrapper", but we aren&#8217;t going to explain it here, <a href="https://docs.gradle.org/current/userguide/gradle_wrapper.html">here you can get more info about Gradle Wrapper</a>.
</div>
<div class="footnote" id="_footnotedef_3">
<a href="#_footnoteref_3">3</a>. .bat in Windows. Without extension in Linux
</div>
<div class="footnote" id="_footnotedef_4">
<a href="#_footnoteref_4">4</a>. We can also specify/modify which optimizations to apply.
</div>
</div>]]></content>
            <category term="Gradle"/>
    <category term="C++"/>
    <category term="Build Software"/>
    <category term="Build System"/>
    <category term="Dependency Management"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Bases de Datos Embebidas Java: Comparación de Rendimiento</title>
            <link href="https://carlosvin.github.io/posts/java-embedded-db-performance-comparison/es" />
               
            <id>https://carlosvin.github.io/posts/java-embedded-db-performance-comparison/es</id>
            <updated>2014-06-07T16:09:00.000Z</updated>
            <summary>Comparación de rendimiento en Java entre tres bases de datos embebidas: Derby/JavaDB, Sqlite y ObjectDB</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_bases_de_datos_embebidas">Bases de datos embebidas</a>
<ul class="sectlevel2">
<li><a href="#_sqlitedb">SqliteDB</a></li>
<li><a href="#_derbydb_o_javadb">DerbyDB o JavaDB</a></li>
<li><a href="#_objectdb">ObjectDb</a></li>
</ul>
</li>
<li><a href="#_los_tests">Los Tests</a>
<ul class="sectlevel2">
<li><a href="#_las_bases_de_datos_jdbc">Las Bases de Datos JDBC</a></li>
<li><a href="#_el_código_fuente">El código fuente</a></li>
<li><a href="#_resultados_de_los_tests">Resultados de los tests</a></li>
</ul>
</li>
</ul>
</div>
<div class="sect1">
<h2 id="_bases_de_datos_embebidas">Bases de datos embebidas</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Se trata de bases de datos que carecen de servidor, están inscrustadas en la propia aplicación y suelen estar almacenadas en ficheros locales. Esto último unido a que suelen tener un modo de funcionamiento en el que mantienen los datos en memoria hace que puedan tener un rendimiento muy alto.</p>
</div>
<div class="paragraph">
<p>Eso sí, este gran grado acoplamiento a la aplicación, hace que tengan peor rendimiento cuando se comparten entre varias aplicaciones debido a colisiones de acceso.</p>
</div>
<div class="paragraph">
<p>Otra ventaja es que no tenemos que encargarnos de mantener y gestionar un servidor de bases de datos.</p>
</div>
<div class="paragraph">
<p>Voy a hacer una comparativa de rendimiento entre 3 bases de datos embebidas <a href="https://es.wikipedia.org/wiki/ACID" target="_blank" rel="noopener">ACID</a> (transaccionales), las <a href="https://es.wikipedia.org/wiki/NoSQL" target="_blank" rel="noopener">NoSQL</a> no entran en esta comparativa que están en otra liga de rendimiento.</p>
</div>
<div class="paragraph">
<p>Contenidos</p>
</div>
<div class="sect2">
<h3 id="_sqlitedb"><a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a></h3>
<div class="paragraph">
<p>Se trata de una librería escrita en <a href="https://es.wikipedia.org/wiki/ANSI_C" target="_blank" rel="noopener">ANSI C</a>, de menos de 500KB, multi-plataforma, sin dependencias externas, almacena todo el contenido de la base de datos en un solo fichero.</p>
</div>
<div class="paragraph">
<p>Es la que da mejor rendimiento en los <a href="#_resultados_de_los_tests">Resultados de los tests</a>.</p>
</div>
<div class="paragraph">
<p>Se puede utilizar desde C y C++, pero también <a href="https://es.wikipedia.org/wiki/Sqlite#Lenguajes_de_programaci.C3.B3n" target="_blank" rel="noopener">desde otros lenguajes de programación</a> (PHP, Python, Java, .NET &#8230;&#8203;).</p>
</div>
<div class="paragraph">
<p>En el caso de <a href="https://es.wikipedia.org/wiki/Java_(lenguaje_de_programaci%C3%B3n)" target="_blank" rel="noopener">Java</a> podemos gestionar esta base de datos a través de <a href="https://es.wikipedia.org/wiki/Java_Database_Connectivity" target="_blank" rel="noopener">JDBC</a>. Podemos obtener la librería de <a href="https://bitbucket.org/xerial/sqlite-jdbc" class="bare">https://bitbucket.org/xerial/sqlite-jdbc</a>.</p>
</div>
<div class="paragraph">
<p>Veamos un ejemplo de la inserción de una serie de objetos de la clase <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/domain/Price.java" target="_blank" rel="noopener">Price.java</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JdbcDb</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">DB</span> </span>{

    <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Column</span> </span>{
        INSTRUMENT,
        MARKET,
        PRICE,
        DATE;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String TABLE_NAME = <span class="hljs-string">&quot;PRICES&quot;</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String SQL_INSERT = <span class="hljs-string">&quot;INSERT INTO &quot;</span> + TABLE_NAME
            + <span class="hljs-string">&quot; (INSTRUMENT, MARKET, PRICE, DATE) VALUES (?,?,?,?)&quot;</span>;

    <span class="hljs-comment">// ...</span>

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(Price p, PreparedStatement preparedStatement)</span> <span class="hljs-keyword">throws</span> SQLException </span>{
        preparedStatement.setString(<span class="hljs-number">1</span>, p.getInstrument());
        preparedStatement.setString(<span class="hljs-number">2</span>, p.getMarket());
        preparedStatement.setDouble(<span class="hljs-number">3</span>, p.getPrice());
        preparedStatement.setTimestamp(<span class="hljs-number">4</span>, <span class="hljs-keyword">new</span> Timestamp(p.getDate().getTime()));
        preparedStatement.addBatch();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(Price... prices)</span> <span class="hljs-keyword">throws</span> SQLException </span>{
        PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT);
        <span class="hljs-keyword">for</span> (Price p : prices) {
            insert(p, preparedStatement);
        }
        preparedStatement.executeBatch();
        preparedStatement.close();
        conn.commit();
    }

    <span class="hljs-comment">// ...</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_derbydb_o_javadb"><a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/DerbyDB.java" target="_blank" rel="noopener">DerbyDB</a> o <a href="https://www.oracle.com/technetwork/es/java/javadb/overview/index.html" target="_blank" rel="noopener">JavaDB</a></h3>
<div class="paragraph">
<p><a href="https://www.oracle.com/technetwork/es/java/javadb/overview/index.html" target="_blank" rel="noopener">JavaDB</a> es una distribución de Oracle de la base de datos de código libre <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/DerbyDB.java" target="_blank" rel="noopener">DerbyDB</a>. Soporta el estándar <a href="https://es.wikipedia.org/wiki/SQL" target="_blank" rel="noopener">ANSI/ISO SQL</a> a través de <a href="https://es.wikipedia.org/wiki/Java_Database_Connectivity" target="_blank" rel="noopener">JDBC</a> y <a href="https://es.wikipedia.org/wiki/Java_EE" target="_blank" rel="noopener">Java EE</a>. Estas librerías están incluidas en el <a href="https://es.wikipedia.org/wiki/Java_Development_Kit" target="_blank" rel="noopener">JDK</a>.</p>
</div>
<div class="paragraph">
<p>Almacena la base de datos en multiples archivos, lo que puede resultar útil para escalar el almacenamiento.</p>
</div>
<div class="paragraph">
<p>Solo podemos utilizarlo en <a href="https://es.wikipedia.org/wiki/Java_(lenguaje_de_programaci%C3%B3n)" target="_blank" rel="noopener">Java</a>, no desde otros lenguajes.</p>
</div>
<div class="paragraph">
<p>Como veremos más adelante ha sido la más lenta en los <a href="#_resultados_de_los_tests">Resultados de los tests</a>.</p>
</div>
<div class="paragraph">
<p>La implementación de ejemplo de una inserción de una serie de objetos de la clase <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/domain/Price.java" target="_blank" rel="noopener">Price.java</a>, es exactamente la misma que la que hemos hecho más arriba en <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a>, esto es una de las bondades de <a href="https://es.wikipedia.org/wiki/Java_Database_Connectivity" target="_blank" rel="noopener">JDBC</a>, que nos permite obtener una conexión para una base de datos específica, pero a partir de ahí casi siempre nos podemos olvidar de la base de datos con la que trabajamos, siempre y cuando soporte nuestras consultas <a href="https://es.wikipedia.org/wiki/SQL" target="_blank" rel="noopener">SQL</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_objectdb"><a href="https://www.objectdb.com/" target="_blank" rel="noopener">ObjectDb</a></h3>
<div class="paragraph">
<p>Es una <a href="https://es.wikipedia.org/wiki/Base_de_datos_orientada_a_objetos">base de datos orientada a objetos</a> que nos permite acceso <a href="https://es.wikipedia.org/wiki/Java_Persistence_API" target="_blank" rel="noopener">JPA</a>, un estándar de Java que persigue no perder las ventajas de la orientación a objetos; esto se suele perder cuando nos acercamos a la capa de persistencia.</p>
</div>
<div class="paragraph">
<p>Resulta realmente sencillo realizar acciones típicas de una base de datos, abstrayéndonos del SQL, por ejemplo veamos cómo quedaría una inserción de un array de objetos de la clase Price con <a href="https://www.objectdb.com/" target="_blank" rel="noopener">ObjectDb</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(Price... prices)</span> <span class="hljs-keyword">throws</span> SQLException </span>{
    em.getTransaction().begin();
    <span class="hljs-keyword">for</span> (Price p : prices) {
        em.persist(p);
    }
    em.getTransaction().commit();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Si a esta facilidad de uso, le unimos que los <a href="#_resultados_de_los_tests">Resultados de los tests</a> de rendimiento han sido muy buenos (cerca de <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a>), puedo decir que he descubierto una base de datos embebida a tener muy en cuenta en futuros proyectos <a href="https://es.wikipedia.org/wiki/Java_(lenguaje_de_programaci%C3%B3n)" target="_blank" rel="noopener">Java</a>, eso sí, al igual que con <a href="https://www.oracle.com/technetwork/es/java/javadb/overview/index.html" target="_blank" rel="noopener">JavaDB</a>, solo nos sirve si vamos a programar en <a href="https://es.wikipedia.org/wiki/Java_(lenguaje_de_programaci%C3%B3n)" target="_blank" rel="noopener">Java</a>.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_los_tests">Los Tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Simplemente consisten en realizar repetidamente una serie operaciones <a href="https://es.wikipedia.org/wiki/CRUD" target="_blank" rel="noopener">CRUD</a>. Para cada base de datos, el test realiza una serie de inserciones, selects, actualizaciones y borrado de objetos de la clase Precio.</p>
</div>
<div class="paragraph">
<p>He utilizado 100000 instancias de la clase <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/domain/Price.java" target="_blank" rel="noopener">Price.java</a>, las mismas para cada tipo de base de datos.</p>
</div>
<div class="paragraph">
<p>Para esto he creado una interfaz <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/DB.java" target="_blank" rel="noopener">DB.java</a> que compartirán cada una de las implementaciones para cada base de datos.</p>
</div>
<div class="listingblock">
<div class="title">DB.java</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">DB</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insert</span><span class="hljs-params">(Price... prices)</span> <span class="hljs-keyword">throws</span> SQLException</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">createTable</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteAll</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">update</span><span class="hljs-params">(Price... prices)</span> <span class="hljs-keyword">throws</span> SQLException</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Set&lt;Price&gt; <span class="hljs-title">selectAll</span><span class="hljs-params">()</span></span>;

}</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_las_bases_de_datos_jdbc">Las Bases de Datos JDBC</h3>
<div class="paragraph">
<p>Solo cambian los datos necesarios para obtener el driver y la conexión a la base de datos, por eso toda la lógica está en la clase <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/JdbcDb.java" target="_blank" rel="noopener">JdbcDb</a> de la que heredan <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a> y <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/DerbyDB.java" target="_blank" rel="noopener">DerbyDB</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_el_código_fuente">El código fuente</h3>
<div class="paragraph">
<p>Podéis descargar el código fuente de <a href="https://github.com/carlosvin/java_embedded_databases" class="bare">https://github.com/carlosvin/java_embedded_databases</a>.</p>
</div>
<div class="paragraph">
<p>Se trata de un proyecto <a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a>, por lo que para ejecutar los tests solo tenéis que ejecutar: <code>grade test</code>.</p>
</div>
<div class="paragraph">
<p><a href="https://www.gradle.org" target="_blank" rel="noopener">Gradle</a> descargará automáticamente las librerías necesarias, compilará y ejecutará los tests.</p>
</div>
<div class="paragraph">
<p>También podéis ver directamente la ejecución en <a href="https://travis-ci.org/carlosvin/java_embedded_databases" class="bare">https://travis-ci.org/carlosvin/java_embedded_databases</a>.</p>
</div>
<div class="paragraph">
<p><a href="https://travis-ci.org/carlosvin/java_embedded_databases"><span class="image"><img src="https://travis-ci.org/carlosvin/java_embedded_databases.svg" alt="image"></span></a></p>
</div>
</div>
<div class="sect2">
<h3 id="_resultados_de_los_tests">Resultados de los tests</h3>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">db.DbTest &gt; testSqliteDB STANDARD_OUT
    Testing with 100000 elements
    100000 Prices SqliteDB, total time 3455 ms <b class="conum">(1)</b>
    	Insert:	 1508 ms
    	Select:	 605 ms
    	Update:	 1319 ms
    	Delete:	 23 ms
    ----------------------------------------------
db.DbTest &gt; testObjectDB STANDARD_OUT
    Testing with 100000 elements
    100000 Prices ObjectDB, total time 6467 ms <b class="conum">(2)</b>
    	Insert:	 2579 ms
    	Select:	 1126 ms
    	Update:	 1698 ms
    	Delete:	 1064 ms
    ----------------------------------------------
db.DbTest &gt; testDerbyDB STANDARD_OUT
    Testing with 100000 elements
    100000 Prices DerbyDB, total time 24808 ms <b class="conum">(3)</b>
    	Insert:	 11467 ms
    	Select:	 695 ms
    	Update:	 6983 ms
    	Delete:	 5663 ms</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a> es el más rápido.</p>
</li>
<li>
<p><a href="https://www.objectdb.com/" target="_blank" rel="noopener">ObjectDb</a> es dos veces más lento que <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a>.</p>
</li>
<li>
<p><a href="https://www.oracle.com/technetwork/es/java/javadb/overview/index.html" target="_blank" rel="noopener">JavaDB</a> o <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/DerbyDB.java" target="_blank" rel="noopener">DerbyDB</a> es el más lento, unas 8 veces más lento que <a href="https://github.com/carlosvin/java_embedded_databases/blob/master/src/main/java/db/SqliteDB.java" target="_blank" rel="noopener">SqliteDB</a></p>
</li>
</ol>
</div>
</div>
</div>
</div>]]></content>
            <category term="Java"/>
    <category term="database"/>
    <category term="embedded"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Remove orphaned packages (Linux)</title>
            <link href="https://carlosvin.github.io/posts/linux-remove-orphaned-files/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/linux-remove-orphaned-files/es"/>   
            <id>https://carlosvin.github.io/posts/linux-remove-orphaned-files/en</id>
            <updated>2012-10-02T11:30:02.000Z</updated>
            <summary>How to remove unused packages in Linux</summary>
            <content type="html"><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>When we install a package in most of Linux distributions, the package system installs other packages needed by the package that we are installing. If we uninstall the package, its dependencies might not be uninstalled, these unused dependencies are called orphaned packages.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s see how to remove orphaned packages.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_archlinux"><a href="https://archlinux.org/" target="_blank" rel="noopener">Archlinux</a></h2>
<div class="sectionbody">
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">pacman -Rsn $(pacman -Qdtq)</code></pre>
</div>
</div>
<div class="paragraph">
<p>How does the command work?</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>pacman -Qdt</code> list all orphaned packages</p>
</li>
<li>
<p><code>pacman -Rsn</code> uninstall the listed packages</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_debian"><a href="https://debian.org/" target="_blank" rel="noopener">Debian</a></h2>
<div class="sectionbody">
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">apt-get remove --purge $(deborphan)</code></pre>
</div>
</div>
</div>
</div>]]></content>
            <category term="Linux"/>
    <category term="Archlinux"/>
    <category term="Debian"/>
    <category term="Tips and Tricks"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Normalizar texto en Python</title>
            <link href="https://carlosvin.github.io/posts/normalize-text-py/es" />
               
            <id>https://carlosvin.github.io/posts/normalize-text-py/es</id>
            <updated>2012-10-02T16:00:00.000Z</updated>
            <summary>Evitar problemas con textos que contienen caractéres no ASCII</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>En muchos idiomas, como es el caso del español, hay caracteres que no tienen representación <a href="https://es.wikipedia.org/wiki/ASCII" target="_blank" rel="noopener">ASCII</a>, como por ejemplo la <strong>á</strong>, que sí que tiene representación en <a href="https://es.wikipedia.org/wiki/Unicode" target="_blank" rel="noopener">Unicode</a>.</p>
</div>
<div class="paragraph">
<p>Para evitar problemas o por simplificar, se ha dado una equivalencia entre los caracteres <a href="https://es.wikipedia.org/wiki/Unicode" target="_blank" rel="noopener">Unicode</a> y los <a href="https://es.wikipedia.org/wiki/ASCII" target="_blank" rel="noopener">ASCII</a>. A continuación os pondré un trozo de código en <a href="https://www.python.org" target="_blank" rel="noopener">Python</a> que hace esta conversión.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-comment"># -*- coding: utf-8 -*-</span>
<span class="hljs-keyword">from</span> unicodedata <span class="hljs-keyword">import</span> normalize

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">normalize_text</span> (<span class="hljs-params"> text </span>):</span>
  <span class="hljs-keyword">return</span> normalize(<span class="hljs-string">&#x27;NFKD&#x27;</span>, text) <b class="conum">(1)</b>
    .encode(<span class="hljs-string">&#x27;ASCII&#x27;</span>, <span class="hljs-string">&#x27;ignore&#x27;</span>) <b class="conum">(2)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Especificamos la forma normal que aplicamos en la normalización. En este caso <code>NFKD</code>. Más información sobre <a href="https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms" target="_blank" rel="noopener">Tipos de formas normales</a>.</p>
</li>
<li>
<p>Confertimos el resultado de la normalización a <a href="https://es.wikipedia.org/wiki/ASCII" target="_blank" rel="noopener">ASCII</a>. En caso de que un carácter sea erróneo simplemente será ignorado.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="title">Ejecutando la función</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-meta">&gt;&gt;&gt; </span>normalize_text ( <span class="hljs-string">&#x27;aáaá eéeé iíií oóoó ñnñn AÀAÀ&#x27;</span> )
<span class="hljs-string">b&#x27;aaaa eeee iiii oooo nnnn AAAA&#x27;</span></code></pre>
</div>
</div>]]></content>
            <category term="Python"/>
    <category term="Tips and Tricks"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Create a PWA with Create React App: Lessons Learned</title>
            <link href="https://carlosvin.github.io/posts/pwa-lessons-learned-cra/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/pwa-lessons-learned-cra/es"/>   
            <id>https://carlosvin.github.io/posts/pwa-lessons-learned-cra/en</id>
            <updated>2020-06-10T00:00:00.000Z</updated>
            <summary>Lessons learned while developing a PWA with CRA: Budget Tracker</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_chosen_technology_stack_for_budget_tracker">Chosen Technology Stack for Budget Tracker</a></li>
<li><a href="#_create_react_application_cra">Create React Application: CRA</a>
<ul class="sectlevel2">
<li><a href="#_service_worker">Service worker</a></li>
<li><a href="#_web_worker">Web worker</a></li>
<li><a href="#_webpack">Webpack</a></li>
</ul>
</li>
<li><a href="#_firebase">Firebase</a>
<ul class="sectlevel2">
<li><a href="#_drawbacks">Drawbacks</a></li>
<li><a href="#_firebase_alternatives">Firebase alternatives</a></li>
</ul>
</li>
<li><a href="#_ui_components_library_material_ui">UI Components Library: Material UI</a></li>
<li><a href="#_charts_library">Charts library</a></li>
<li><a href="#_conclusion">Conclusion</a>
<ul class="sectlevel2">
<li><a href="#_do_not_go_for_cra_if">Do not go for CRA if</a></li>
<li><a href="#_do_not_go_for_firestore_if">Do not go for Firestore if</a></li>
<li><a href="#_do_not_go_blindly_for_the_best_charting_library">Do not go blindly for the best charting library</a></li>
</ul>
</li>
<li><a href="#_what_next">What next?</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>I started working with <a href="https://reactjs.org" target="_blank" rel="noopener">React</a> few year ago, always the project creation was from scratch, not using any template/scaffolding. Regarding bundlers normally I used either <a href="https://webpack.js.org" target="_blank" rel="noopener">Webpack</a> at work or <a href="https://parceljs.org" target="_blank" rel="noopener">Parcel</a> for personal projects.</p>
</div>
<div class="paragraph">
<p>Few months ago, I wanted to start a personal project to keep track of my travel expenses. I was in a kind of rush because at that time, I was almost in the middle of my gap year, I wanted to focus on implementing main functionality and get an <a href="https://en.wikipedia.org/wiki/Minimum_viable_product">MVP</a> (minimum viable product) the sooner the better, so I thought it was the right time to try out <a href="https://create-react-app.dev" target="_blank" rel="noopener">Create React App</a> or <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
<a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a> allows you to have a production ready <a href="https://developers.google.com/web/progressive-web-apps/" target="_blank" rel="noopener">PWA</a> in <a href="https://reactjs.org" target="_blank" rel="noopener">React</a> quickly, which is awesome. They take care of configuration and package dependencies, you only have to take care of dependencies you need for your project and of course, implement your project, <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a> is good, but is not magic.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>As I said, I wanted to be implementing business logic ASAP, so together with using <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a>, I also took other decisions/shortcuts driven by the need of speeding up the development pace, I will talk about those choices in following sections describing some drawbacks and benefits.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_chosen_technology_stack_for_budget_tracker">Chosen Technology Stack for <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a></h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p><a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a></p>
</li>
<li>
<p><a href="https://reactjs.org" target="_blank" rel="noopener">React</a></p>
</li>
<li>
<p><a href="https://www.typescriptlang.org" target="_blank" rel="noopener">Typescript</a></p>
</li>
<li>
<p><a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a></p>
</li>
<li>
<p><span class="line-through"><a href="https://formidable.com/open-source/victory">Victory</a></span> <a href="https://frappe.io/charts" target="_blank" rel="noopener">Frappe charts</a></p>
</li>
<li>
<p><a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a></p>
</li>
<li>
<p><a href="https://firebase.google.com/docs/auth" target="_blank" rel="noopener">Firebase Authentication</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>So far I am quite happy with the outcome, but with the lessons learned while developing this app, <strong>in the future, with enough time, most likely I will not choose same technology stack again</strong>. You can try the application <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> and judge for yourself.</p>
</div>
<div class="paragraph">
<p>Along this post I will describe what are, in my experience, the benefits and drawbacks of taking these shortcuts and technical decisions.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_create_react_application_cra">Create React Application: <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://create-react-app.dev" target="_blank" rel="noopener">Create React App</a> doesn’t support <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">Web Workers</a> neither allows to customize <a href="https://developers.google.com/web/fundamentals/primers/service-workers" target="_blank" rel="noopener">Service Worker</a> implementation without <a href="https://stackoverflow.com/questions/49737652/what-does-eject-do-in-create-react-app">ejecting</a>.</p>
</div>
<div class="sect2">
<h3 id="_service_worker">Service worker</h3>
<div class="paragraph">
<p>You might want to customize your <a href="https://developers.google.com/web/fundamentals/primers/service-workers" target="_blank" rel="noopener">Service Worker</a> to send/receive <a href="https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage">post messages</a>, to perform <a href="https://wicg.github.io/BackgroundSync/spec/">background sync</a> or <a href="https://developer.mozilla.org/en/docs/Web/API/notification">show web notifications</a>. In that case, you will have to <a href="https://stackoverflow.com/questions/49737652/what-does-eject-do-in-create-react-app">eject your project</a> and maintain the configuration by yourself, which might imply a little bit of headache.</p>
</div>
<div class="paragraph">
<p>There are <a href="https://www.freecodecamp.org/news/how-to-customize-service-workers-with-create-react-app-4424dda6210c/">other options to customize service worker and avoid ejecting CRA</a>, but they are not straightforward enough for my taste.</p>
</div>
</div>
<div class="sect2">
<h3 id="_web_worker">Web worker</h3>
<div class="paragraph">
<p>If you need to perform any heavy processing without blocking the main thread, you can just use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">Web Workers</a>, but this feature is not supported by <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a>. The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">Web Workers</a> can communicate with main thread using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage">post messages</a> and it can also show <a href="https://medium.com/young-coder/a-simple-introduction-to-web-workers-in-javascript-b3504f9d9d1c">web push notifications</a>.</p>
</div>
<div class="paragraph">
<p>There are also <a href="https://medium.com/@danilog1905/how-to-use-web-workers-with-react-create-app-and-not-ejecting-in-the-attempt-3718d2a1166b">other options to use Web Workers in CRA and not eject</a>, but they imply quite some extra work.</p>
</div>
</div>
<div class="sect2">
<h3 id="_webpack">Webpack</h3>
<div class="paragraph">
<p><a href="https://webpack.js.org" target="_blank" rel="noopener">Webpack</a> is the bundler used by <a href="https://create-react-app.dev" target="_blank" rel="noopener">CRA</a>. You don’t need to know much about it, unless you <a href="https://stackoverflow.com/questions/49737652/what-does-eject-do-in-create-react-app">eject your project</a>, then you will have to deal with <a href="https://webpack.js.org/configuration/">Webpack configuration file</a>, this is just a warning, just in case you are not comfortable with it.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_firebase">Firebase</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> supports data synchronization between different devices, so it requires a <a href="https://en.wikipedia.org/wiki/Front_and_back_ends">backend</a> side to deal with authentication and to save/read data remotely. I considered two options: <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> or implement <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> API.</p>
</div>
<div class="paragraph">
<p>For this <a href="https://en.wikipedia.org/wiki/Front_and_back_ends">backend</a>, I chose <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> because it is super easy to implement, because there is nothing to implement. You only have to configure <a href="https://support.google.com/firebase/answer/6400716?hl=en">authentication methods</a> and <a href="https://firebase.google.com/docs/firestore/security/get-started">security rules</a> for <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a>.</p>
</div>
<div class="paragraph">
<p>But <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> brings some drawbacks you must know before choosing it.</p>
</div>
<div class="sect2">
<h3 id="_drawbacks">Drawbacks</h3>
<div class="sect3">
<h4 id="_bundle_size">Bundle size</h4>
<div class="paragraph">
<p>I got really shocked first time I analyzed <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> bundle size after integrating it with <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a>, <strong>it grew around a 39%!</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>27% from <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> library.</p>
</li>
<li>
<p>12% from <a href="https://firebase.google.com/docs/auth" target="_blank" rel="noopener">Firebase Authentication</a> library.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Happily <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> implementation is following <a href="https://reactjs.org/docs/code-splitting.html">code-splitting</a> principle, so user experience was not really affected with this integration. But user’s device will eventually have to download this extra 39% (<strong>539KB</strong>).</p>
</div>
</div>
<div class="sect3">
<h4 id="_offline_first_not_really">Offline first, not really</h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
This section is not relevant if your use case doesn’t imply saving data linked to the user.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> requires user to be authenticated, but <a href="https://firebase.google.com/docs/auth/web/anonymous-auth">user can be anonymous</a>, this is really cool feature if you don’t want to force the user to identify to use the app.</p>
</div>
<div class="paragraph">
<p>Another very useful and cool <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> feature is that <a href="https://firebase.google.com/docs/firestore/manage-data/enable-offline">it supports offline mode</a>, so data can be saved and read even there is no Internet connection.</p>
</div>
<div class="paragraph">
<p>Anonymous user + offline mode features will allow an application to work as offline first.</p>
</div>
<div class="paragraph">
<p>So… what is this <a href="#Offline first">not really</a> issue about? Let me explain a tricky scenario. First time the application is opened, <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> needs to authenticate the user, to do so, user’s device has to be connected to Internet, so <strong>you have to consider following scenario</strong> and either be OK with it or deal with it:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p><a href="https://developers.google.com/web/progressive-web-apps/" target="_blank" rel="noopener">PWA</a> is installed in your device.</p>
</li>
<li>
<p>User is not authenticated.</p>
</li>
<li>
<p>User’s device is offline.</p>
</li>
<li>
<p>User opens the <a href="https://developers.google.com/web/progressive-web-apps/" target="_blank" rel="noopener">PWA</a> and tries to save some data.</p>
</li>
<li>
<p><strong>That data won’t be saved correctly</strong>, because there is no user to link the data with, not even an anonymous user, because application needs to call <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> API to create an anonymous user.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>This is not big deal, because it will seldom occur. If you want to deal with it anyway, check next section explaining how and why I did deal with this scenario.</p>
</div>
<div class="sect4">
<h5 id="_how_did_i_deal_with_this_issue_with_budget_tracker">How did I deal with this issue with Budget Tracker?</h5>
<div class="paragraph">
<p>First of all, this <strong>might not be an issue for your use case</strong>, because it will happen only first time application is loaded. I just wanted <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> to be fully offline first, because it brings other benefits.</p>
</div>
<div class="sect5">
<h6 id="_implementation_details">Implementation details</h6>
<div class="ulist">
<ul>
<li>
<p>Implement 2 persistence layers: Local (<a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API" target="_blank" rel="noopener">IndexedDB</a>) and Remote (<a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a>).</p>
</li>
<li>
<p>Save always data locally, regardless user authentication status.</p>
</li>
<li>
<p>If there is any authenticated user, after saving to local layer, propagate same action to remote layer (<a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a>) asynchronously.</p>
</li>
</ul>
</div>
</div>
<div class="sect5">
<h6 id="_benefits">Benefits</h6>
<div class="ulist">
<ul>
<li>
<p>If user is not authenticated, <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> won’t load <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> client bundle. As I explained before, it is 27% of application size.</p>
</li>
<li>
<p>Application reads and writes are faster, because latest valid data is always saved locally.</p>
<div class="ulist">
<ul>
<li>
<p><strong>Clarification</strong>: Save data in <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> is also fast, because data is also cached locally, but it does a little bit more than just saving to <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API" target="_blank" rel="noopener">IndexedDB</a> and you need an authenticated user.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can find a <a href="https://github.com/carlosvin/budget-tracker/blob/master/doc/preformance.md#desktop-slow-clear-storage-0-budgets-1">more detailed performance report</a>, where I analyze 3 different implementations:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Only <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> client.</p>
</li>
<li>
<p>Local (<a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API" target="_blank" rel="noopener">IndexedDB</a>) and remote (<a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a>) persistence layers.</p>
</li>
<li>
<p>Same as previous one, but remote layer implemented in service worker.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The performance results were in general better for option 2.</p>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_model">Data model</h4>
<div class="paragraph">
<p>Firestore API is easy and intuitive, I really like it, but don’t assume it will have same features as other document DBs or SQL DBs.</p>
</div>
<div class="paragraph">
<p>Check if <a href="https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.Firestore/datamodel.html">Firestore limitations</a> fit into your data model, or if it is not too late, define your data model following <a href="https://cloud.google.com/firestore/docs/best-practices">Firestore best practices</a> and having those limitations in mind.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_firebase_alternatives">Firebase alternatives</h3>
<div class="paragraph">
<p>Besides implementing a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> API, there are other services similar to <a href="https://firebase.google.com/" target="_blank" rel="noopener">Firebase</a> with smaller client bundle size and other features which might fit better to your requirements.</p>
</div>
<div class="paragraph">
<p>Consider other alternatives:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Based on <a href="http://couchdb.apache.org/">Apache CouchDB</a>: <a href="https://pouchdb.com">PouchDB</a>, <a href="https://en.wikipedia.org/wiki/Cloudant">Cloudant</a>.</p>
</li>
<li>
<p>Based on <a href="https://parseplatform.org/">Parse server</a>: <a href="https://www.back4app.com">back4apps</a>.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_ui_components_library_material_ui">UI Components Library: <a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>I chose <a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a>.</p>
</div>
<div class="quoteblock">
<blockquote>
React components for faster and easier web development. Build your own design system, or start with Material Design.
</blockquote>
<div class="attribution">
&#8212; https://material-ui.com[Material UI
</div>
</div>
<div class="paragraph">
<p>There were two reasons which drove me to use <a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>To create simple UI components which are accessible, <a href="https://material-ui.com/guides/responsive-ui/#responsive-ui">responsive</a> and with a consistent design is tricky and time consuming.</p>
</li>
<li>
<p>It has SVG set of <a href="https://material-ui.com/components/material-icons/">Material Icons</a>. <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> allows to create categories defined by a name and a selectable icon, so this icon set was really convenient.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>There are some <strong>drawbacks</strong>, not very important in my opinion, maybe the most annoying for me is the first one:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://jestjs.io/docs/en/snapshot-testing">Jest Snapshots</a> + <a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a>: The snapshots are generated with <a href="https://material-ui.com" target="_blank" rel="noopener">Material UI</a> CSS class names, but CSS classes order might not be deterministic, so a test might pass in your local host but not in <a href="https://en.wikipedia.org/wiki/Continuous_integration">CI</a> host. They are working on solve <a href="https://github.com/mui-org/material-ui/issues/14357">this issue, more info at github</a>.</p>
</li>
<li>
<p>Performance: There are some performance <a href="https://github.com/mui-org/material-ui/issues?utf8=%E2%9C%93&amp;q=is%3Aissue+is%3Aopen+performance">issues in Github</a>. During last months, whilst I’ve been using this library, I can say they are working hard on fix them and bring new features.</p>
</li>
<li>
<p>UI components libraries are complex and do quite a lot work, so most of them are quite heavy. <a href="https://bundlephobia.com/result?p=@material-ui/core@4.5.2">Material UI bundle size weights: 304.2kB minified</a>. You can find some <a href="https://material-ui.com/guides/minimizing-bundle-size">recommendations to reduce bundle size at Material UI website</a>.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_charts_library">Charts library</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Many of the chart libraries I’ve found are really powerful and complete, but they are also heavy because they depend on other third party libraries like <a href="https://d3js.org/">D3</a>.</p>
</div>
<div class="paragraph">
<p>Initially I chose <a href="https://formidable.com/open-source/victory">Victory</a>, but I realized that I only needed charts to show percentages and time series and <a href="https://formidable.com/open-source/victory">Victory</a>’s <a href="https://bundlephobia.com/result?p=victory@33.1.2">bundle size is 468KB minified</a>.</p>
</div>
<div class="paragraph">
<p>After quick search in the Internet I discovered other lighter alternatives:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://frappe.io/charts" target="_blank" rel="noopener">Frappe charts</a> <a href="https://bundlephobia.com/result?p=frappe-charts@1.3.0">63KB minified</a>.</p>
</li>
<li>
<p><a href="https://gionkunz.github.io/chartist-js">Chartist</a> <a href="https://bundlephobia.com/result?p=chartist@0.11.4">39KB minified</a>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>I tried them and I liked both. I chose <a href="https://frappe.io/charts" target="_blank" rel="noopener">Frappe charts</a> because I thought its default color scheme fits better with <a href="https://btapp.netlify.com" target="_blank" rel="noopener">Budget Tracker</a> theme.</p>
</div>
<div class="paragraph">
<p>Both libraries come with more chart types than just bars and XY axis, take a quick look at their websites if you are interested about their supported chart set and to check how they look like.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_conclusion">Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I will try to come up with a conclusion better than: <em>"It depends"</em>, <em>"Your use case will tell you"</em> and so on.</p>
</div>
<div class="paragraph">
<p>That said. It depends on your needs :p.</p>
</div>
<div class="paragraph">
<p>Seriously, let’s play <em>"do not go for … if …"</em>:</p>
</div>
<div class="sect2">
<h3 id="_do_not_go_for_cra_if">Do not go for CRA if</h3>
<div class="ulist">
<ul>
<li>
<p>You want to customize <a href="https://developers.google.com/web/fundamentals/primers/service-workers" target="_blank" rel="noopener">Service Worker</a> for <a href="https://developers.google.com/web/updates/2015/12/background-sync">Background sync</a> or <a href="https://developer.mozilla.org/en/docs/Web/API/notification">showing push notifications</a>.</p>
</li>
<li>
<p>You want to use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">Web Workers</a>.</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_do_not_go_for_firestore_if">Do not go for Firestore if</h3>
<div class="ulist">
<ul>
<li>
<p>You are aiming for your app to be hit by many users and you don’t know the estimated amount of reads/writes, otherwise you might get surprised with the bill. <a href="https://firebase.google.com/docs/firestore" target="_blank" rel="noopener">Firestore</a> scales like charm, maybe your budget doesn’t.</p>
</li>
<li>
<p>Bundle size is critical for your web application. Remember that bundle size is not that critical if you are implementing a <a href="https://developers.google.com/web/progressive-web-apps/" target="_blank" rel="noopener">PWA</a>, because your app files are cached.</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_do_not_go_blindly_for_the_best_charting_library">Do not go blindly for the best charting library</h3>
<div class="paragraph">
<p>First of all, check what kind of charts you need. In many applications you are OK with XY axis chart, time series, bars or pie charts. You can easily get an smaller bundle size by just using a simple charting library like <a href="https://frappe.io/charts" target="_blank" rel="noopener">Frappe charts</a> or <a href="https://gionkunz.github.io/chartist-js">Chartist</a></p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Just check what are your requirements, if you are not sure about them, <a href="#_chosen_technology_stack_for_budget_tracker">Chosen Technology Stack for Budget Tracker</a> consists of awesome products which most likely will fit your use case.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_what_next">What next?</h2>
<div class="sectionbody">
<div class="paragraph">
<p>My next technology stack bet goes for <a href="https://svelte.dev" target="_blank" rel="noopener">Svelte</a>/https://sapper.svelte.dev[Sapper,window=_blank], it is promising project, the results for small projects are really impressive, mainly in regards to bundle size, it is ridiculously small and development experience is quick and intuitive.</p>
</div>
<div class="paragraph">
<p>I’ve created a tiny <a href="https://developers.google.com/web/progressive-web-apps/" target="_blank" rel="noopener">PWA</a> to estimate <a href="https://currency-loss.netlify.com">currency exchange loss</a> when you go to a money changer shop: <a href="https://currency-loss.netlify.com">currency-loss.netlify.com</a>. Note, I got that app up and running in few hours, thanks to <a href="https://svelte.dev" target="_blank" rel="noopener">Svelte</a>.</p>
</div>
</div>
</div>]]></content>
            <category term="React"/>
    <category term="Typescript"/>
    <category term="CRA"/>
    <category term="PWA"/>
    <category term="Create React App"/>
    <category term="Firebase"/>
    <category term="Firestore"/>
    <category term="Svelte"/>
    <category term="Sapper"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Create SPA: React + Typescript + Parcel</title>
            <link href="https://carlosvin.github.io/posts/react-typescript-parcel/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/react-typescript-parcel/es"/>   
            <id>https://carlosvin.github.io/posts/react-typescript-parcel/en</id>
            <updated>2019-07-10T11:30:02.000Z</updated>
            <summary>Example project how to create a Single Page Application with React, Typescript and Parcel.</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_read_this_before_parcel_is_not_as_mature_as_webpack">Read this before: Parcel is not as mature as Webpack</a></li>
<li><a href="#_quick_start">Quick start</a>
<ul class="sectlevel2">
<li><a href="#_development_server">Development server</a></li>
<li><a href="#_build_production_bundle">Build production bundle</a></li>
</ul>
</li>
<li><a href="#_step_by_step_project_creation">Step by step project creation</a>
<ul class="sectlevel2">
<li><a href="#_add_required_dependencies">Add required dependencies</a></li>
<li><a href="#_create_application_source_code">Create application source code</a></li>
<li><a href="#_add_commands_build_the_project">Add commands build the project</a></li>
<li><a href="#_configure_typescript_optional">Configure Typescript (optional)</a></li>
</ul>
</li>
<li><a href="#_full_source_code">Full source code</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>I was about to start yet another personal project, it consists of a SPA (Single Page Application) for a travel journal.</p>
</div>
<div class="paragraph">
<p>Some time ago I tried <a href="https://parceljs.org" target="_blank" rel="noopener">Parcel</a>, I really loved how simple it was to create a simple project from scratch, using <a href="https://www.typescriptlang.org/" target="_blank" rel="noopener">Typescript</a> + <a href="https://reactjs.org" target="_blank" rel="noopener">React</a> stack. I’ve decided to create this template or base project, so next time I want to create a new SPA with my favorite frontend stack, I will only have to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">git <span class="hljs-built_in">clone</span> https://github.com/carlosvin/react-typescript-parcel-template.git</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_read_this_before_parcel_is_not_as_mature_as_webpack">Read this before: Parcel is not as mature as Webpack</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you want to create a production ready React application, use <a href="https://webpack.js.org/" target="_blank" rel="noopener">Webpack</a> or better <a href="https://facebook.github.io/create-react-app/" target="_blank" rel="noopener">create-react-app</a> which bring everything you need to develop a <a href="https://developers.google.com/web/progressive-web-apps/">PWA</a> with React and Typescript. Following you can find an example of an app I am developing using <a href="https://facebook.github.io/create-react-app/" target="_blank" rel="noopener">create-react-app</a>: <a href="https://github.com/carlosvin/budget-tracker" class="bare">https://github.com/carlosvin/budget-tracker</a>.</p>
</div>
<div class="paragraph">
<p>Parcel is a package bundler under development, not as mature as webpack. There are no go errors for me, at least in regards to Typescript support, see this <a href="https://github.com/parcel-bundler/parcel/issues/1378">issue in github #1378</a>.</p>
</div>
<div class="paragraph">
<p>I still think it is a promising project, bringing more simplicity and speed to JS bundlers world, I will give it a try again for serious projects when Parcel 2 is ready, check <a href="https://github.com/parcel-bundler/parcel/projects/5">Parcel 2 development status</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_quick_start">Quick start</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_development_server">Development server</h3>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">git <span class="hljs-built_in">clone</span> https://github.com/carlosvin/react-typescript-parcel-template.git
<span class="hljs-built_in">cd</span> react-typescript-parcel-template
yarn install
yarn start</code></pre>
</div>
</div>
<div class="paragraph">
<p>Last <code>yarn start</code> command will:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>start a development server at <a href="http://localhost:1234" class="bare">http://localhost:1234</a> with <a href="https://en.parceljs.org/hmr.html">hot module replacement</a></p>
</li>
<li>
<p>build automatically development javascript files with source maps</p>
</li>
</ul>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Each time you save a file, you will see automatically the result at <code><a href="http://localhost:1234" class="bare">http://localhost:1234</a></code> without refreshing the page
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_build_production_bundle">Build production bundle</h3>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn build</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://en.parceljs.org/production.html#optimisations">Parcel’s default optimizations</a> will be applied to generated files.</p>
</div>
<div class="paragraph">
<p>Files are saved at <code>dist</code> folder. Inside <code>dist</code> folder there is also a file with information about bundle content sizes: <code>dist/report.html</code>.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_step_by_step_project_creation">Step by step project creation</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this section I will describe how I created this project.</p>
</div>
<div class="paragraph">
<p>Firstly, create <code>package.json</code> with <a href="https://yarnpkg.com/lang/en/docs/cli/init/">yarn init</a> command.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn init</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_add_required_dependencies">Add required dependencies</h3>
<div class="paragraph">
<p>Add <a href="https://reactjs.org" target="_blank" rel="noopener">React</a> dependencies.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn add @types/react @types/react-dom react react-dom</code></pre>
</div>
</div>
<div class="paragraph">
<p>Previous command modifies <code>package.json</code> file adding <code>dependencies</code> section and will also install React packages in <code>node_modules</code> folder.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
  <span class="hljs-attr">&quot;name&quot;</span>: <span class="hljs-string">&quot;project_name&quot;</span>,
  <span class="hljs-attr">&quot;version&quot;</span>: <span class="hljs-string">&quot;1.0.0&quot;</span>,
  <span class="hljs-attr">&quot;main&quot;</span>: <span class="hljs-string">&quot;index.js&quot;</span>,
  <span class="hljs-attr">&quot;license&quot;</span>: <span class="hljs-string">&quot;MIT&quot;</span>,
  <span class="hljs-attr">&quot;dependencies&quot;</span>: {
    <span class="hljs-attr">&quot;@types/react&quot;</span>: <span class="hljs-string">&quot;^16.7.18&quot;</span>,
    <span class="hljs-attr">&quot;@types/react-dom&quot;</span>: <span class="hljs-string">&quot;^16.0.11&quot;</span>,
    <span class="hljs-attr">&quot;react&quot;</span>: <span class="hljs-string">&quot;^16.7.0&quot;</span>,
    <span class="hljs-attr">&quot;react-dom&quot;</span>: <span class="hljs-string">&quot;^16.7.0&quot;</span>
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Add <a href="https://www.typescriptlang.org/" target="_blank" rel="noopener">Typescript</a> compiler as development dependency.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn add --dev typescript</code></pre>
</div>
</div>
<div class="paragraph">
<p>We also need <a href="https://parceljs.org/">Parcel bundler</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn add --dev parcel-bundler</code></pre>
</div>
</div>
<div class="paragraph">
<p>I’ve added a non-required dependency, it is a plugin to generate a report of generated bundle contents (the parcel version of <a href="https://github.com/webpack-contrib/webpack-bundle-analyzer">webpack-bundle-analyzer</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">yarn add --dev parcel-plugin-bundle-visualiser</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_create_application_source_code">Create application source code</h3>
<div class="paragraph">
<p>First we create the React application in <code>src/index.tsx</code> file.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-jsx" data-lang="jsx"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;react&quot;</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;react-dom&quot;</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">PureComponent</span> </span>{
    <span class="hljs-function"><span class="hljs-title">render</span>(<span class="hljs-params"></span>)</span> {
        <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello world!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
    }
}

ReactDOM.render(
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>,
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&quot;app&quot;</span>)
);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Parcel can take <code>index.html</code> file as entry file and it figures out how to build the application, so let’s create <code>src/index.html</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-html" data-lang="html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;app&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;./index.tsx&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>We need <code>div</code> tag for React to inject the DOM elements. The <code>script</code> declaration is used by Parcel to find entry point to build.</p>
</div>
</div>
<div class="sect2">
<h3 id="_add_commands_build_the_project">Add commands build the project</h3>
<div class="paragraph">
<p>I’ve added the commands:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>build</code>: Check <em>"Build production bundle"</em> section.</p>
</li>
<li>
<p><code>start</code>: Check <em>"Development server"</em> section.</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">    <span class="hljs-string">&quot;scripts&quot;</span>: {
        <span class="hljs-attr">&quot;start&quot;</span>: <span class="hljs-string">&quot;parcel src/index.html&quot;</span>,
        <span class="hljs-attr">&quot;build&quot;</span>: <span class="hljs-string">&quot;parcel build src/index.html&quot;</span>
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then to it is really easy to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>run development server: <code>yarn start</code></p>
</li>
<li>
<p>generate a production bundle: <code>yarn build</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>There is another approach described in <a href="https://en.parceljs.org/getting_started.html">Parcel documentation</a> that consists of installing Parcel globally.</p>
</div>
<div class="paragraph">
<p>I’ve opted for more isolated approach that affects only project you are working on, you just install Parcel as <code>devDependency</code>. There is a tiny drawback, you can’t just run <code>parcel index.html</code>, because it is not installed in your system, but in <code>node_modules</code>.</p>
</div>
<div class="paragraph">
<p>There is a simple way to run any binary installed in <code>node_modules</code>, you can just run <code>npx parcel index.html</code>.</p>
</div>
<div class="paragraph">
<p>I like more to define build steps in <code>package.json</code> file, so you can have well defined commands more suited to build your project. You can also use these commands as documentation how to build your project.</p>
</div>
</div>
<div class="sect2">
<h3 id="_configure_typescript_optional">Configure Typescript (optional)</h3>
<div class="listingblock">
<div class="title">Create a <code>tsconfig.json</code> file</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
    <span class="hljs-attr">&quot;compilerOptions&quot;</span>: {
        <span class="hljs-attr">&quot;outDir&quot;</span>: <span class="hljs-string">&quot;./dist/&quot;</span>,
        <span class="hljs-attr">&quot;sourceMap&quot;</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">&quot;noImplicitAny&quot;</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">&quot;module&quot;</span>: <span class="hljs-string">&quot;commonjs&quot;</span>,
        <span class="hljs-attr">&quot;target&quot;</span>: <span class="hljs-string">&quot;es5&quot;</span>,
        <span class="hljs-attr">&quot;jsx&quot;</span>: <span class="hljs-string">&quot;react&quot;</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this configuration, Typescript compiler will:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Generate files in <code>dist</code> folder.</p>
</li>
<li>
<p>Generate <a href="https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map">source maps</a>.</p>
</li>
<li>
<p>Will not allow to declare <code>any</code> type, for example following declaration is not allowed: <code>const elements: any;</code></p>
</li>
<li>
<p>Generated module code will be <a href="https://requirejs.org/docs/commonjs.html">CommonJs</a>.</p>
</li>
<li>
<p>Generated code will be <a href="https://es.wikipedia.org/wiki/ECMAScript">ECMAScript</a> 5 compliant.</p>
</li>
<li>
<p>Support <a href="https://www.typescriptlang.org/docs/handbook/jsx.html">JSX</a> in <code>.tsx</code> files.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_full_source_code">Full source code</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can find full example at: <a href="https://github.com/carlosvin/react-typescript-parcel-template" class="bare">https://github.com/carlosvin/react-typescript-parcel-template</a>.</p>
</div>
<div class="paragraph">
<p>Or you can directly download the source code:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/carlosvin/react-typescript-parcel-template/archive/1.0.zip">zip</a></p>
</li>
<li>
<p><a href="https://github.com/carlosvin/react-typescript-parcel-template/archive/1.0.tar.gz">tar.gz</a></p>
</li>
</ul>
</div>
</div>
</div>]]></content>
            <category term="React"/>
    <category term="Typescript"/>
    <category term="Parcel"/>
    <category term="SPA"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Filesystem in C++17</title>
            <link href="https://carlosvin.github.io/posts/recursive-directory-iterator/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/recursive-directory-iterator/es"/>   
            <id>https://carlosvin.github.io/posts/recursive-directory-iterator/en</id>
            <updated>2017-05-28T07:00:00.000Z</updated>
            <summary>We are going to analyze with examples new filesystem features coming with C++17</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_introduction">Introduction</a></li>
<li><a href="#_gettting_started_with_experimental_filesystem_features_c17_g">Gettting started with Experimental Filesystem Features C&#43;&#43;17 (g++)</a></li>
<li><a href="#_c17_filesystem_features">C&#43;&#43;17 Filesystem Features</a>
<ul class="sectlevel2">
<li><a href="#_stdfilesystempath">std::filesystem::path</a></li>
<li><a href="#_directory_separator">Directory separator</a></li>
<li><a href="#_directory_separator_operator">Directory Separator Operator</a></li>
<li><a href="#_createremove_directories">Create/Remove Directories</a></li>
</ul>
</li>
<li><a href="#_full_example_recursive_directory_iterator">Full example: Recursive Directory Iterator</a>
<ul class="sectlevel2">
<li><a href="#_c11">C&#43;&#43;11</a></li>
<li><a href="#_c17">C&#43;&#43;17</a></li>
</ul>
</li>
</ul>
</div>
<div class="sect1">
<h2 id="_introduction">Introduction</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Since C&#43;&#43;17 new filesystem abstractions will be added to C&#43;&#43; environment. So far they are available as <a href="https://en.cppreference.com/w/cpp/experimental">Experimental C&#43;&#43; Features</a>. If you want to dig more about this new library, here it is the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4100.pdf" target="_blank" rel="noopener">final draft of File System Technical Specification</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_gettting_started_with_experimental_filesystem_features_c17_g">Gettting started with Experimental Filesystem Features C&#43;&#43;17 (g++)</h2>
<div class="sectionbody">
<div class="paragraph">
<p>We just have to "tell" compiler that:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>we write C&#43;&#43;17 (<code>-c++1z</code>) and</p>
</li>
<li>
<p>it has to add <em>standard library with filesystem library</em> (<code>-lstdc++fs</code>).</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">g++ -std=c++1z main.cpp -lstdc++fs &amp;&amp; ./a.out</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s see a simple example with <code>std::filesystem::path</code> class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;experimental/filesystem&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">namespace</span> fs = <span class="hljs-built_in">std</span>::experimental::filesystem;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    fs::path aPath {<span class="hljs-string">&quot;./path/to/file.txt&quot;</span>};

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Parent path: &quot;</span> &lt;&lt; aPath.parent_path() &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Filename: &quot;</span> &lt;&lt; aPath.filename() &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Extension: &quot;</span> &lt;&lt; aPath.extension() &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/9f8bebb8b7f0fbe7" target="_blank" rel="noopener">Compile and run: Basic C&#43;&#43;17 example</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">$ g++ -std=c++1z main.cpp -lstdc++fs &amp;&amp; ./a.out
$ ./a.out

Parent path: <span class="hljs-string">&quot;./path/to&quot;</span>
Filename: <span class="hljs-string">&quot;file.txt&quot;</span>
Extension: <span class="hljs-string">&quot;.txt&quot;</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_c17_filesystem_features">C&#43;&#43;17 Filesystem Features</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this section, we are going to explain some <a href="https://en.cppreference.com/w/cpp/filesystem" target="_blank" rel="noopener">std::filesystem</a> features with examples, which will help us to highlight differences between C&#43;&#43;11 and C&#43;&#43;17 so we can get a better idea about what this new library will supply and how it might make developer&#8217;s work easier.</p>
</div>
<div class="sect2">
<h3 id="_stdfilesystempath">std::filesystem::path</h3>
<div class="paragraph">
<p>Upper we have seen a tiny <a href="https://coliru.stacked-crooked.com/a/9f8bebb8b7f0fbe7" target="_blank" rel="noopener">use case for std::filesystem::path</a>. That is a quite powerful and convenient feature that supplies an multi-platform abstraction for paths to files using the correct directory path separator depending on the platform we are building our application for (<code>\</code> for Windows based systems and <code>/</code> for Unix based systems).</p>
</div>
</div>
<div class="sect2">
<h3 id="_directory_separator">Directory separator</h3>
<div class="paragraph">
<p>When we want our application to use the correct directory separator in C&#43;&#43;11, we could use conditional macro declaration:</p>
</div>
<div class="listingblock">
<div class="title">Platform independent directory separator in C&#43;&#43;11</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">ifdef</span> _WIN32</span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> SEP = <span class="hljs-string">&quot;\\&quot;</span>;
<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> SEP = <span class="hljs-string">&quot;/&quot;</span>;
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Separator in my system &quot;</span> &lt;&lt; SEP &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://coliru.stacked-crooked.com/a/5023ee989105fc54" target="_blank" rel="noopener">Compile and run: C&#43;&#43;11 separator example</a>.</p>
</div>
<div class="listingblock">
<div class="title">Platform independent directory separator in C&#43;&#43;17. Cleaner and simpler.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;experimental/filesystem&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">namespace</span> fs = <span class="hljs-built_in">std</span>::experimental::filesystem;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Separator in my system &quot;</span> &lt;&lt; fs::path::preferred_separator &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://coliru.stacked-crooked.com/a/1f2f63b3f5597d05" target="_blank" rel="noopener">Compile and run: C&#43;&#43;17 separator example</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_directory_separator_operator">Directory Separator Operator</h3>
<div class="paragraph">
<p><a href="https://en.cppreference.com/w/cpp/filesystem/path">std::filesystem::path</a> implements <code>/</code> operator, which allows to easily concatenate paths to files and directories.</p>
</div>
<div class="paragraph">
<p>When we want to concatenate paths in C&#43;&#43;11, we have to add extra logic to avoid adding duplicate separators and to select the correct separator for target platform:</p>
</div>
<div class="listingblock">
<div class="title">Concatenate paths in C&#43;&#43;11</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">ifdef</span> _WIN32</span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> SEP = <span class="hljs-string">&quot;\\&quot;</span>;
<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> SEP = <span class="hljs-string">&quot;/&quot;</span>;
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">string</span> root {<span class="hljs-string">&quot;/&quot;</span>};
    <span class="hljs-built_in">string</span> dir {<span class="hljs-string">&quot;var/www/&quot;</span>};
    <span class="hljs-built_in">string</span> index {<span class="hljs-string">&quot;index.html&quot;</span>};

    <span class="hljs-built_in">string</span> pathToIndex{};
    pathToIndex.append(root).append(SEP).append(dir).append(SEP).append(index);

    <span class="hljs-built_in">cout</span> &lt;&lt; pathToIndex &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/290b278ec1de9573" target="_blank" rel="noopener">Compile and run: Concatenate paths in C&#43;&#43;11</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">//var/www//index.html</code></pre>
</div>
</div>
<div class="paragraph">
<p>Checking program output we notice it is not fully correct, we should have checked whether path parts already contains a separator so we don&#8217;t append another separator again. That logic is already implemented in <a href="https://en.cppreference.com/w/cpp/filesystem/path">std::filesystem::path</a>, so C&#43;&#43;17 can be like:</p>
</div>
<div class="listingblock">
<div class="title">Concatenate paths in C&#43;&#43;17</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;experimental/filesystem&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">namespace</span> fs = <span class="hljs-built_in">std</span>::experimental::filesystem;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    fs::path root {<span class="hljs-string">&quot;/&quot;</span>};
    fs::path dir {<span class="hljs-string">&quot;var/www/&quot;</span>};
    fs::path index {<span class="hljs-string">&quot;index.html&quot;</span>};

    fs::path pathToIndex = root / dir / index;

    <span class="hljs-built_in">cout</span> &lt;&lt; pathToIndex &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/a24d50875b4daad1">Compile and run: Concatenate paths in C&#43;&#43;17</a>.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash"><span class="hljs-string">&quot;/var/www/index.html&quot;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Code is cleaner and just correct, there are no duplicated separators.</p>
</div>
</div>
<div class="sect2">
<h3 id="_createremove_directories">Create/Remove Directories</h3>
<div class="paragraph">
<p><a href="https://en.cppreference.com/w/cpp/filesystem" target="_blank" rel="noopener">std::filesystem</a> comes with some utilities to create and remove files and directories, but firstly let&#8217;s try to do so in C&#43;&#43;11.</p>
</div>
<div class="listingblock">
<div class="title">Create and remove nested directories in C&#43;&#43;11</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cstdio&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/stat.h&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> opts = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
    mkdir(<span class="hljs-string">&quot;sandbox&quot;</span>, opts);
    mkdir(<span class="hljs-string">&quot;sandbox/a&quot;</span>, opts);
    mkdir(<span class="hljs-string">&quot;sandbox/a/b&quot;</span>, opts);
    mkdir(<span class="hljs-string">&quot;sandbox/c&quot;</span>, opts);
    mkdir(<span class="hljs-string">&quot;sandbox/c/d&quot;</span>, opts);

    system(<span class="hljs-string">&quot;ls -la sandbox/*&quot;</span>);

    remove(<span class="hljs-string">&quot;sandbox/c/d&quot;</span>);
    remove(<span class="hljs-string">&quot;sandbox/a/b&quot;</span>);
    remove(<span class="hljs-string">&quot;sandbox/c&quot;</span>);
    remove(<span class="hljs-string">&quot;sandbox/a&quot;</span>);
    remove(<span class="hljs-string">&quot;sandbox&quot;</span>);

    system(<span class="hljs-string">&quot;ls -la&quot;</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/26f4763ec5b42adb">Compile and run: Create and remove directories C&#43;&#43;11</a>.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">g++-4.9 -std=c++11 main.cpp -lm &amp;&amp; ./a.out
sandbox/a:
total 12
drwxr-xr-x 3 2001 2000 4096 May 28 12:27 .
drwxr-xr-x 4 2001 2000 4096 May 28 12:27 ..
drwxr-xr-x 2 2001 2000 4096 May 28 12:27 b

sandbox/c:
total 12
drwxr-xr-x 3 2001 2000 4096 May 28 12:27 .
drwxr-xr-x 4 2001 2000 4096 May 28 12:27 ..
drwxr-xr-x 2 2001 2000 4096 May 28 12:27 d
total 8012
drwxrwxrwx 2 2001 2000    4096 May 28 12:27 .
drwxrwxrwx 3 2002 2000 8175616 May 28 12:27 ..
-rwxr-xr-x 1 2001 2000    8168 May 28 12:27 a.out
-rw-rw-rw- 1 2001 2000     517 May 28 12:27 main.cpp</code></pre>
</div>
</div>
<div class="paragraph">
<p>We have to create/remove one by one. We could rewrite this code snippet with less lines (using a loop), but we still have to pay attention to creation/deletion order, we cannot remove parent directory before we have removed all children.</p>
</div>
<div class="paragraph">
<p>Since C&#43;&#43;17, we can create and remove nested directories with just one call.</p>
</div>
<div class="listingblock">
<div class="title">Create and remove nested directories C&#43;&#43;17</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;experimental/filesystem&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">namespace</span> fs = <span class="hljs-built_in">std</span>::experimental::filesystem;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    fs::create_directories(<span class="hljs-string">&quot;sandbox/a/b&quot;</span>);
    fs::create_directories(<span class="hljs-string">&quot;sandbox/c/d&quot;</span>);
    system(<span class="hljs-string">&quot;ls -la sandbox/*&quot;</span>);

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;Were directories removed? &quot;</span> &lt;&lt; fs::remove_all(<span class="hljs-string">&quot;sandbox&quot;</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    system(<span class="hljs-string">&quot;ls -la&quot;</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/62c2d22fa0e7144c">Compile and run: Create and remove nested directories C&#43;&#43;17</a>.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">g++ -std=c++1z -fconcepts -fgnu-tm  -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic -lstdc++fs &amp;&amp; ./a.out
sandbox/a:
total 12
drwxr-xr-x 3 2001 2000 4096 May 28 16:45 .
drwxr-xr-x 4 2001 2000 4096 May 28 16:45 ..
drwxr-xr-x 2 2001 2000 4096 May 28 16:45 b

sandbox/c:
total 12
drwxr-xr-x 3 2001 2000 4096 May 28 16:45 .
drwxr-xr-x 4 2001 2000 4096 May 28 16:45 ..
drwxr-xr-x 2 2001 2000 4096 May 28 16:45 d
Were directories removed? 1
total 10132
drwxrwxrwx 2 2001 2000    4096 May 28 16:45 .
drwxrwxrwx 3 2002 2000 8175616 May 28 16:45 ..
-rwxr-xr-x 1 2001 2000 2170976 May 28 16:45 a.out
-rw-rw-rw- 1 2001 2000     393 May 28 16:45 main.cpp</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_full_example_recursive_directory_iterator">Full example: Recursive Directory Iterator</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This example consists of iterate recursively through dicrectories fintering files by extension.</p>
</div>
<div class="sect2">
<h3 id="_c11">C&#43;&#43;11</h3>
<div class="paragraph">
<p>To keep C&#43;&#43;11 example simple, I haven&#8217;t added filtering  logic, but filtering logic is present in C&#43;&#43;17 example:</p>
</div>
<div class="listingblock">
<div class="title">filesystem.11.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-cpp" data-lang="cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;dirent.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cstring&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;fstream&gt; // std::ofstream</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;memory&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;system_error&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/stat.h&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> UP_DIR = <span class="hljs-string">&quot;..&quot;</span>;
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> CURRENT_DIR = <span class="hljs-string">&quot;.&quot;</span>;
<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> SEP = <span class="hljs-string">&quot;/&quot;</span>;


<span class="hljs-function"><span class="hljs-built_in">string</span> <span class="hljs-title">path</span><span class="hljs-params">(<span class="hljs-built_in">initializer_list</span>&lt;<span class="hljs-built_in">string</span>&gt; parts)</span>
</span>{
    <span class="hljs-built_in">string</span> pathTmp {};
    <span class="hljs-built_in">string</span> separator = <span class="hljs-string">&quot;&quot;</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> &amp; part: parts)
    {
        pathTmp.append(separator).append(part);
        separator = SEP;
    }
    <span class="hljs-keyword">return</span> pathTmp;
}

<span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; <span class="hljs-title">getDirectoryFiles</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span>&amp; dir, <span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; &amp; extensions)</span>
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; files;
    <span class="hljs-function"><span class="hljs-built_in">shared_ptr</span>&lt;DIR&gt; <span class="hljs-title">directory_ptr</span><span class="hljs-params">(opendir(dir.c_str()), [](DIR* dir){ dir &amp;&amp; closedir(dir); })</span></span>;
    <span class="hljs-keyword">if</span> (!directory_ptr)
    {
        <span class="hljs-keyword">throw</span> system_error(error_code(errno, system_category()), <span class="hljs-string">&quot;Error opening : &quot;</span> + dir);
    }

    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">dirent</span> *<span class="hljs-title">dirent_ptr</span>;</span>
    <span class="hljs-keyword">while</span> ((dirent_ptr = readdir(directory_ptr.get())) != <span class="hljs-literal">nullptr</span>)
    {
        <span class="hljs-keyword">const</span> <span class="hljs-built_in">string</span> fileName {dirent_ptr-&gt;d_name};
        <span class="hljs-keyword">if</span> (dirent_ptr-&gt;d_type == DT_DIR)
        {
            <span class="hljs-keyword">if</span> (CURRENT_DIR != fileName &amp;&amp; UP_DIR != fileName)
            {
                <span class="hljs-keyword">auto</span> subFiles = getDirectoryFiles(path({dir, fileName}), extensions);
                files.insert(end(files), begin(subFiles), end(subFiles));
            }
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dirent_ptr-&gt;d_type == DT_REG)
        {
            <span class="hljs-comment">// here we should check also if filename has an extension in extensions vector</span>
            files.push_back(path({dir, fileName}));
        }
    }
    <span class="hljs-keyword">return</span> files;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span> <span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> opt = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
    mkdir(<span class="hljs-string">&quot;sandbox&quot;</span>, opt);
    mkdir(<span class="hljs-string">&quot;sandbox/a&quot;</span>, opt);
    mkdir(<span class="hljs-string">&quot;sandbox/a/b&quot;</span>, opt);

	<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; e_files = {
	    <span class="hljs-string">&quot;./sandbox/a/b/file1.rst&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/a/b/file1.txt&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/a/file2.RST&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/file3.md&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/will_be.ignored&quot;</span>
	};

	<span class="hljs-comment">// create files</span>
	<span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> &amp;f: e_files)
	{
		<span class="hljs-function">ofstream <span class="hljs-title">of</span><span class="hljs-params">(f, ofstream::out)</span></span>;
		of &lt;&lt; <span class="hljs-string">&quot;test&quot;</span>;
	}

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;filtered files: &quot;</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
	<span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> &amp;f: getDirectoryFiles(<span class="hljs-string">&quot;.&quot;</span>, {<span class="hljs-string">&quot;.rst&quot;</span>, <span class="hljs-string">&quot;.RST&quot;</span>, <span class="hljs-string">&quot;.md&quot;</span>})){
	    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">&quot;\t&quot;</span> &lt;&lt; f &lt;&lt; <span class="hljs-built_in">endl</span>;
	}

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/af4228e039a281b3" target="_blank" rel="noopener">Compile and run C&#43;&#43;11 example</a>.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">g++ -std=c++11 -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic -lstdc++fs &amp;&amp; ./a.out
filtered files:
	./main.cpp
	./sandbox/file3.md
	./sandbox/will_be.ignored
	./sandbox/a/b/file1.rst
	./sandbox/a/b/file1.txt
	./sandbox/a/file2.RST
	./a.out</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_c17">C&#43;&#43;17</h3>
<div class="paragraph">
<p>Following example also filters files by extension.</p>
</div>
<div class="listingblock">
<div class="title">filesystem.17.cpp</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash"><span class="hljs-comment">#include &lt;dirent.h&gt;</span>
<span class="hljs-comment">#include &lt;cstring&gt;</span>
<span class="hljs-comment">#include &lt;iostream&gt;</span>
<span class="hljs-comment">#include &lt;fstream&gt; // std::ofstream</span>
<span class="hljs-comment">#include &lt;vector&gt;</span>
<span class="hljs-comment">#include &lt;memory&gt;</span>
<span class="hljs-comment">#include &lt;system_error&gt;</span>
<span class="hljs-comment">#include &lt;sys/stat.h&gt;</span>

using namespace std;

const string UP_DIR = <span class="hljs-string">&quot;..&quot;</span>;
const string CURRENT_DIR = <span class="hljs-string">&quot;.&quot;</span>;
const string SEP = <span class="hljs-string">&quot;/&quot;</span>;


string path(initializer_list&lt;string&gt; parts)
{
    string pathTmp {};
    string separator = <span class="hljs-string">&quot;&quot;</span>;
    <span class="hljs-keyword">for</span> (auto &amp; part: parts)
    {
        pathTmp.append(separator).append(part);
        separator = SEP;
    }
    <span class="hljs-built_in">return</span> pathTmp;
}

vector&lt;string&gt; getDirectoryFiles(const string&amp; dir, const vector&lt;string&gt; &amp; extensions)
{
    vector&lt;string&gt; files;
    shared_ptr&lt;DIR&gt; directory_ptr(opendir(dir.c_str()), [](DIR* dir){ dir &amp;&amp; closedir(dir); });
    <span class="hljs-keyword">if</span> (!directory_ptr)
    {
        throw system_error(error_code(errno, system_category()), <span class="hljs-string">&quot;Error opening : &quot;</span> + dir);
    }

    struct dirent *dirent_ptr;
    <span class="hljs-keyword">while</span> ((dirent_ptr = readdir(directory_ptr.get())) != nullptr)
    {
        const string fileName {dirent_ptr-&gt;d_name};
        <span class="hljs-keyword">if</span> (dirent_ptr-&gt;d_type == DT_DIR)
        {
            <span class="hljs-keyword">if</span> (CURRENT_DIR != fileName &amp;&amp; UP_DIR != fileName)
            {
                auto subFiles = getDirectoryFiles(path({dir, fileName}), extensions);
                files.insert(end(files), begin(subFiles), end(subFiles));
            }
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (dirent_ptr-&gt;d_type == DT_REG)
        {
            // here we should check also <span class="hljs-keyword">if</span> filename has an extension <span class="hljs-keyword">in</span> extensions vector
            files.push_back(path({dir, fileName}));
        }
    }
    <span class="hljs-built_in">return</span> files;
}

int <span class="hljs-function"><span class="hljs-title">main</span></span> ()
{
    auto opt = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
    mkdir(<span class="hljs-string">&quot;sandbox&quot;</span>, opt);
    mkdir(<span class="hljs-string">&quot;sandbox/a&quot;</span>, opt);
    mkdir(<span class="hljs-string">&quot;sandbox/a/b&quot;</span>, opt);

	vector&lt;string&gt; e_files = {
	    <span class="hljs-string">&quot;./sandbox/a/b/file1.rst&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/a/b/file1.txt&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/a/file2.RST&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/file3.md&quot;</span>,
	    <span class="hljs-string">&quot;./sandbox/will_be.ignored&quot;</span>
	};

	// create files
	<span class="hljs-keyword">for</span> (auto &amp;f: e_files)
	{
		ofstream of(f, ofstream::out);
		of &lt;&lt; <span class="hljs-string">&quot;test&quot;</span>;
	}

    cout &lt;&lt; <span class="hljs-string">&quot;filtered files: &quot;</span> &lt;&lt; <span class="hljs-string">endl;
	for (auto &amp;f: getDirectoryFiles(&quot;.&quot;, {&quot;.rst&quot;, &quot;.RST&quot;, &quot;.md&quot;})){
	    cout &lt;&lt; &quot;\t&quot; &lt;&lt; f &lt;&lt; endl</span>;
	}

    <span class="hljs-built_in">return</span> 0;
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://coliru.stacked-crooked.com/a/af4228e039a281b3" target="_blank" rel="noopener">Compile and run C&#43;&#43;17 example</a>.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">g++ -std=c++11 -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic -lstdc++fs &amp;&amp; ./a.out
filtered files:
	./main.cpp
	./sandbox/file3.md
	./sandbox/will_be.ignored
	./sandbox/a/b/file1.rst
	./sandbox/a/b/file1.txt
	./sandbox/a/file2.RST
	./a.out</code></pre>
</div>
</div>
</div>
</div>
</div>]]></content>
            <category term="C++"/>
    <category term="C++11"/>
    <category term="C++17"/>
    <category term="IO"/>
    <category term="Filesystem"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Convert files formats: Windows to Unix</title>
            <link href="https://carlosvin.github.io/posts/recursive-dos-unix/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/recursive-dos-unix/es"/>   
            <id>https://carlosvin.github.io/posts/recursive-dos-unix/en</id>
            <updated>2016-02-12T09:34:00.000Z</updated>
            <summary>Convert Windows formatted files to Unix format per directory recursively</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>If you are developing from a Windows environment to a Unix target environment, most likely you have had this issue: You install source files in Windows format in your Unix environment.</p>
</div>
<div class="paragraph">
<p>There is a way quite simple to convert all your files from Windows to Unix format:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">find . -<span class="hljs-built_in">type</span> f -print0 | xargs -0 dos2unix</code></pre>
</div>
</div>
<div class="paragraph">
<p>I got it, of course, from <a href="https://stackoverflow.com/questions/11929461/how-can-i-run-dos2unix-on-an-entire-directory" class="bare">https://stackoverflow.com/questions/11929461/how-can-i-run-dos2unix-on-an-entire-directory</a></p>
</div>]]></content>
            <category term="Useful Commands"/>
    <category term="Unix"/>
    <category term="Windows"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Replace punctuation symbols in Python</title>
            <link href="https://carlosvin.github.io/posts/remove-replace-punctuation-py/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/remove-replace-punctuation-py/es"/>   
            <id>https://carlosvin.github.io/posts/remove-replace-punctuation-py/en</id>
            <updated>2012-05-09T00:00:00.000Z</updated>
            <summary>An example of how to remove or replace punctuation symbols of a Python string</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>Following I will explain how to replace punctuation symbols by whitespace.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-keyword">import</span> re, string

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">remove_punctuation</span> (<span class="hljs-params"> text </span>):</span>
  <span class="hljs-keyword">return</span> re.sub(<span class="hljs-string">&#x27;[%s]&#x27;</span> % re.escape(string.punctuation), <span class="hljs-string">&#x27; &#x27;</span>, text)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Calling to previous function</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">&gt;&gt;&gt; remove_punctuation (<span class="hljs-string">&quot;El perro, de San Roque, no tiene rabo; ni nunca lo ha tenido.&quot;</span>)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">We will get this output</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash"><span class="hljs-string">&#x27;El perro  de San Roque  no tiene rabo  ni nunca lo ha tenido &#x27;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>We could make the function a little bit more generic to replace punctuation symbols by any other string.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-keyword">import</span> re, string

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">replace_punctuation</span>(<span class="hljs-params">text, replace</span>):</span>
  <span class="hljs-keyword">return</span> re.sub(<span class="hljs-string">&#x27;[%s]&#x27;</span> % re.escape(string.punctuation), replace, text)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Calling the function to replace punctuation symbols by "[stop]"</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-python" data-lang="python"><span class="hljs-meta">&gt;&gt;&gt; </span>replace_punctuation(
  <span class="hljs-string">&quot;El perro, de San Roque, no tiene rabo; ni nunca lo ha tenido.&quot;</span>,
  <span class="hljs-string">&#x27;[stop]&#x27;</span>)

<span class="hljs-comment"># output</span>
<span class="hljs-string">&#x27;El perro[stop] de San Roque[stop] no tiene rabo[stop] ni nunca lo ha tenido[stop]&#x27;</span></code></pre>
</div>
</div>]]></content>
            <category term="Python"/>
    <category term="Tips and Tricks"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Golang over Java for REST services</title>
            <link href="https://carlosvin.github.io/posts/rest-service-go-vs-java/en" />
               
            <id>https://carlosvin.github.io/posts/rest-service-go-vs-java/en</id>
            <updated>2020-11-01T00:00:00.000Z</updated>
            <summary>Why I'd pick Golang over Java to create any new distributed system. I am going to compare a REST service implementation in Java vs the implementation in Golang</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_actual_project_examples">Actual project examples</a></li>
<li><a href="#_the_ecosystems">The Ecosystems</a></li>
<li><a href="#_routing">Routing</a>
<ul class="sectlevel2">
<li><a href="#_go_without_framework">Go - Without framework</a></li>
<li><a href="#_go_gin_framework">Go - Gin Framework</a></li>
<li><a href="#_java_spring_io">Java + Spring.io</a></li>
</ul>
</li>
<li><a href="#_validations">Validations</a>
<ul class="sectlevel2">
<li><a href="#_go_gin_framework_2">Go - Gin Framework</a></li>
<li><a href="#_java_spring_io_2">Java + Spring.io</a></li>
<li><a href="#_filtering_and_middleware">Filtering and Middleware</a></li>
</ul>
</li>
<li><a href="#_dependency_injection_ioc">Dependency injection / IoC</a>
<ul class="sectlevel2">
<li><a href="#_spring_ioc">Spring IoC</a></li>
<li><a href="#_go">Go</a></li>
</ul>
</li>
<li><a href="#_testing">Testing</a>
<ul class="sectlevel2">
<li><a href="#_unit_tests">Unit tests</a></li>
<li><a href="#_integration_tests">Integration tests</a></li>
</ul>
</li>
<li><a href="#_performance">Performance</a>
<ul class="sectlevel2">
<li><a href="#_memory">Memory</a></li>
<li><a href="#_speed">Speed</a></li>
</ul>
</li>
<li><a href="#_conclusions">Conclusions</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Lately I&#8217;ve been working with two different technology stacks almost in parallel, in both cases we were using them to develop <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> services.</p>
</div>
<div class="paragraph">
<p>During this time I&#8217;ve come up with some conclusions and opinions I&#8217;d like to share.</p>
</div>
<div class="paragraph">
<p>A disclaimer, few months ago, I had several years of experience with Java and 0 days of professional experience with Golang.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_actual_project_examples">Actual project examples</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Few months ago I created <a href="https://covid-rest.appspot.com/docs" target="_blank" rel="noopener">an API to extract and structure COVID-19 data</a> from <a href="https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide" target="_blank" rel="noopener">ECDC website</a>. I developed it in <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a>.</p>
</div>
<div class="paragraph">
<p>Few months later I had the luck of work on my first professional project in <a href="https://golang.org" target="_blank" rel="noopener">Go</a> and I decided to create a port of <a href="https://covid-rest.appspot.com/docs" target="_blank" rel="noopener">the API to extract COVID-19 data</a> in <a href="https://golang.org" target="_blank" rel="noopener">Go</a>, just for learning and for fun.</p>
</div>
<div class="paragraph">
<p>Now we have two REST services, almost functionally identical, but developed in two different tech stacks, so we can easily compare some relevant aspects of both.</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<caption class="title">Table 1. Source code for the 2 REST services implementations</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><a href="https://www.java.com" target="_blank" rel="noopener">Java</a> + <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a></th>
<th class="tableblock halign-left valign-top"><a href="https://golang.org" target="_blank" rel="noopener">Go</a> + <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/carlosvin/covid-rest" class="bare">https://github.com/carlosvin/covid-rest</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/carlosvin/covid-rest-go" class="bare">https://github.com/carlosvin/covid-rest-go</a></p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
I actually created that <a href="https://covid-rest.appspot.com/docs">COVID-19 data REST API</a> to be the data source for the <a href="https://covid-stats-pwa.netlify.app" target="_blank" rel="noopener">COVID19-Stats App</a>, a <a href="https://web.dev/progressive-web-apps" target="_blank" rel="noopener">PWA</a> built with <a href="https://svelte.dev" target="_blank" rel="noopener">Svelte</a>, but that&#8217;s another topic.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_ecosystems">The Ecosystems</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you want to create a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> service just in plain Java you will have extra work to do, in Golang a little bit less. That&#8217;s why we use framework, because they&#8217;ve already solved many common problems for us.</p>
</div>
<div class="paragraph">
<p>For this comparison I am going to use <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a> for <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> and <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> for <a href="https://golang.org" target="_blank" rel="noopener">Go</a>, but in both languages there are a lot of production ready nice options.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_routing">Routing</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_go_without_framework">Go - Without framework</h3>
<div class="paragraph">
<p>Go uses the concept of <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> multiplexer or router. You can specify routes using patterns and link those routes to handlers. The router will decide which handler has to execute the request based on the path received.</p>
</div>
<div class="listingblock">
<div class="title">router.go file</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
	<span class="hljs-string">&quot;log&quot;</span>
	<span class="hljs-string">&quot;net/http&quot;</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
	router := http.NewServeMux()
	router.Handle(<span class="hljs-string">&quot;/redirect&quot;</span>, http.RedirectHandler(<span class="hljs-string">&quot;https://carlosvin.github.io/&quot;</span>, <span class="hljs-number">307</span>))
	router.HandleFunc(<span class="hljs-string">&quot;/hello&quot;</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
		w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">&quot;Hello world!&quot;</span>))
	})
	log.Println(<span class="hljs-string">&quot;Listening...&quot;</span>)
	http.ListenAndServe(<span class="hljs-string">&quot;:3000&quot;</span>, router)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Source code is already quite simple, but there might more complex routing use cases.</p>
</div>
</div>
<div class="sect2">
<h3 id="_go_gin_framework">Go - Gin Framework</h3>
<div class="paragraph">
<p>Happily there are frameworks that help us to keep our base code simple, for example when we need to extract path parameters, which is quite common use case in <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a>s, we can use a routing library, I&#8217;ve used <a href="https://github.com/gorilla/mux" target="_blank" rel="noopener">Gorilla Mux</a> and <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> and I liked more <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a>.</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/covid-rest-go/blob/master/main.go">Full example</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">import</span> (
	<span class="hljs-string">&quot;github.com/carlosvin/covid-rest-go/handlers&quot;</span>
	<span class="hljs-string">&quot;github.com/carlosvin/covid-rest-go/readers&quot;</span>
	<span class="hljs-string">&quot;github.com/gin-gonic/gin&quot;</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

	<span class="hljs-comment">// ...</span>

	r := gin.Default()
	r.GET(<span class="hljs-string">&quot;/countries&quot;</span>, router.Countries)
	r.GET(<span class="hljs-string">&quot;/countries/:code&quot;</span>, router.Country)
	r.GET(<span class="hljs-string">&quot;/countries/:code/dates&quot;</span>, router.CountryDates)
	r.GET(<span class="hljs-string">&quot;/countries/:code/dates/:date&quot;</span>, router.CountryDate)
	r.Run()
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/covid-rest-go/blob/master/handlers/countries.go">And this is a handler example</a>, the router.Countries one</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *routerImpl)</span> <span class="hljs-title">Countries</span><span class="hljs-params">(c *gin.Context)</span></span> {
	c.JSON(<span class="hljs-number">200</span>, r.countries())
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_java_spring_io">Java + Spring.io</h3>
<div class="paragraph">
<p>The <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a> is based on the concept of Controller, it is implemented using annotations on the class and methods.</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/covid-rest/blob/master/src/main/java/com/carlosvin/covid/controllers/CountriesController.java" target="_blank" rel="noopener">CountriesController.java</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Validated</span>
<span class="hljs-meta">@RestController</span> <b class="conum">(1)</b>
<span class="hljs-meta">@RequestMapping(&quot;/countries&quot;)</span> <b class="conum">(2)</b>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CountriesController</span> </span>{

	<span class="hljs-comment">// Some source code is not shown, you can find the complete example in the repository</span>

	<span class="hljs-meta">@GetMapping(&quot;/{country}/dates/{isoDateStr}&quot;)</span>  <b class="conum">(3)</b>
	<span class="hljs-function"><span class="hljs-keyword">public</span> DateStatsDto <span class="hljs-title">getDateByCountry</span><span class="hljs-params">(<span class="hljs-meta">@Size(min = 2, max = 2)</span> <span class="hljs-meta">@PathVariable</span> String country, <span class="hljs-meta">@Size(min = 10, max = 20)</span> <span class="hljs-meta">@PathVariable</span> String isoDateStr)</span> <span class="hljs-keyword">throws</span> NotFoundException </span>{
		<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> DateStatsDto(service.getDate(country, DateUtils.convert(isoDateStr)));
	}
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Declare the class as Controller so it is registered in <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a></p>
</li>
<li>
<p>Controller base path definition</p>
</li>
<li>
<p>Handler definition for a nested path under the main controller path. <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a> makes easy to extract path variables defined in the route, you can directly use them as method arguments.</p>
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_validations">Validations</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_go_gin_framework_2">Go - Gin Framework</h3>
<div class="paragraph">
<p><a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> uses an external validation package <a href="https://godoc.org/github.com/go-playground/validator">validator</a>, besides that it is fully integrated with <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
	Name  <span class="hljs-keyword">string</span> <span class="hljs-string">`validate:&quot;required&quot;`</span> <b class="conum">(1)</b>
	Email <span class="hljs-keyword">string</span> <span class="hljs-string">`validate:&quot;required,email&quot;`</span>
}

err := validate.Struct(user) <b class="conum">(2)</b>
validationErrors := err.(validator.ValidationErrors) <b class="conum">(3)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>The validation system uses <a href="https://golang.org" target="_blank" rel="noopener">Go</a> tags, it is not the same as <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> annotations, but in the validation case, it works in pretty same way as annotations.</p>
</li>
<li>
<p>Executes the validation explicitly</p>
</li>
<li>
<p>Extracts validation errors</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_java_spring_io_2">Java + Spring.io</h3>
<div class="paragraph">
<p>You can enable the validation in the controller level, then in the handlers you can also specify the type of validation. Let&#8217;s explain it using the previous example:</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://github.com/carlosvin/covid-rest/blob/master/src/main/java/com/carlosvin/covid/controllers/CountriesController.java" target="_blank" rel="noopener">CountriesController.java</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Validated</span> <b class="conum">(1)</b>
<span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping(&quot;/countries&quot;)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CountriesController</span> </span>{

	<span class="hljs-comment">// Some source code is not shown, you can find the complete example in the repository</span>

	<span class="hljs-meta">@GetMapping(&quot;/{country}/dates/{isoDateStr}&quot;)</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> DateStatsDto <span class="hljs-title">getDateByCountry</span><span class="hljs-params">(
		<span class="hljs-meta">@Size(min = 2, max = 2)</span> <span class="hljs-meta">@PathVariable</span> String country, <b class="conum">(2)</b>
		<span class="hljs-meta">@Size(min = 10, max = 20)</span> <span class="hljs-meta">@PathVariable</span> String isoDateStr)</span> <span class="hljs-keyword">throws</span> NotFoundException </span>{
		<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> DateStatsDto(service.getDate(country, DateUtils.convert(isoDateStr)));
	}
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Declare the class as Controller so it is registered in <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a></p>
</li>
<li>
<p><code>@Size</code> validates that the input argument country has 2 characters</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The validation system is more powerful than you can see in this code snippet, for example adding <code>@Valid</code> annotation opens the door to complex types validation.</p>
</div>
</div>
<div class="sect2">
<h3 id="_filtering_and_middleware">Filtering and Middleware</h3>
<div class="paragraph">
<p>Different approaches, pretty much the same end result.</p>
</div>
<div class="paragraph">
<p>I will elaborate this topic in following days.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_dependency_injection_ioc">Dependency injection / IoC</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_spring_ioc"><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators" target="_blank" rel="noopener">Spring IoC</a></h3>
<div class="paragraph">
<p><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators" target="_blank" rel="noopener">Spring IoC</a> is the most complete and powerful systems I&#8217;ve ever used for <a href="https://en.wikipedia.org/wiki/Inversion_of_control" target="_blank" rel="noopener">IoC</a>, actually, the first time I used Spring professionally was just to deal with <a href="https://en.wikipedia.org/wiki/Inversion_of_control" target="_blank" rel="noopener">IoC</a>. It supports XML configuration files or <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> annotations, I like annotations more, here a simple example from <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators" target="_blank" rel="noopener">Spring IoC</a> documentation:</p>
</div>
<div class="listingblock">
<div class="title">Spring IoC example</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JpaMovieFinder</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MovieFinder</span> </span>{ <b class="conum">(1)</b>
    <span class="hljs-comment">// implementation elided for clarity</span>
}

<span class="hljs-comment">//</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SimpleMovieLister</span> </span>{

    <span class="hljs-keyword">private</span> MovieFinder movieFinder;

    <span class="hljs-meta">@Autowired</span> <b class="conum">(2)</b>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setMovieFinder</span><span class="hljs-params">(MovieFinder movieFinder)</span> </span>{
        <span class="hljs-keyword">this</span>.movieFinder = movieFinder;
    }

    <span class="hljs-comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p><code>JpaMovieFinder</code> is instantiated by <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators" target="_blank" rel="noopener">Spring IoC</a></p>
</li>
<li>
<p>With <code>@Autowired</code> annotation <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators" target="_blank" rel="noopener">Spring IoC</a> knows that has to inject <code>movieFinder</code> argument. It should be a class implementing <code>MovieFinder</code></p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_go">Go</h3>
<div class="paragraph">
<p>Neither <a href="https://golang.org" target="_blank" rel="noopener">Go</a> nor <a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> has any <a href="https://en.wikipedia.org/wiki/Inversion_of_control" target="_blank" rel="noopener">IoC</a> solution, but you can still apply <a href="https://en.wikipedia.org/wiki/Dependency_injection" target="_blank" rel="noopener">Dependency Injection</a> technique to decouple your components and improve the testability of your system.</p>
</div>
<div class="listingblock">
<div class="title">Dependency injection simple example in <a href="https://golang.org" target="_blank" rel="noopener">Go</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-go" data-lang="go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span>

<span class="hljs-comment">// Greeter interface to greet the caller</span>
<span class="hljs-keyword">type</span> Greeter <span class="hljs-keyword">interface</span> {
	greet()
}

<span class="hljs-keyword">type</span> greeterHello <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(g *greeterHello)</span> <span class="hljs-title">greet</span><span class="hljs-params">()</span></span> { <b class="conum">(3)</b>
	fmt.Println(<span class="hljs-string">&quot;Hello!&quot;</span>)
}

<span class="hljs-keyword">type</span> greeterHi <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(g *greeterHi)</span> <span class="hljs-title">greet</span><span class="hljs-params">()</span></span> { <b class="conum">(4)</b>
	fmt.Println(<span class="hljs-string">&quot;Hi!&quot;</span>)
}

<span class="hljs-comment">// App Application representation</span>
<span class="hljs-keyword">type</span> App <span class="hljs-keyword">struct</span> {
	greeters []Greeter <b class="conum">(1)</b>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(app *App)</span> <span class="hljs-title">startup</span><span class="hljs-params">()</span></span> {
	<span class="hljs-keyword">for</span> _, v := <span class="hljs-keyword">range</span> app.greeters {
		v.greet()
	}
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
	greeters := []Greeter{ <b class="conum">(2)</b>
		&amp;greeterHello{},
		&amp;greeterHi{},
		&amp;greeterHello{}}

	app := &amp;App{greeters}

	app.startup()
}

<span class="hljs-comment">/*
&lt;1&gt; `App` accepts an array of `Greeter`
&lt;2&gt; During `App` instantiation we pass different implementations of `Greeter`
&lt;3&gt; Greeter implementation that prints *Hello!*
&lt;4&gt; Greeter implementation that prints *Hi!*
*/</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>It is more verbose, but there is an advantage, there is nothing hidden, everything is explicit and you have full control of instantiation order.</p>
</div>
<div class="paragraph">
<p>As soon as you use <a href="https://en.wikipedia.org/wiki/Dependency_injection" target="_blank" rel="noopener">Dependency Injection</a>, I don&#8217;t have any strong opinion about using <a href="https://en.wikipedia.org/wiki/Inversion_of_control" target="_blank" rel="noopener">IoC</a> system or doing <a href="https://en.wikipedia.org/wiki/Dependency_injection" target="_blank" rel="noopener">Dependency Injection</a> manually.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_testing">Testing</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_unit_tests">Unit tests</h3>
<div class="paragraph">
<p>For unit tests there are no big differences.</p>
</div>
<div class="paragraph">
<p><a href="https://golang.org" target="_blank" rel="noopener">Go</a> comes with a standard <a href="https://golang.org/pkg/testing/" target="_blank" rel="noopener">library for testing and benchmarking</a>.</p>
</div>
<div class="paragraph">
<p>For <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> there are many well-known unit testing frameworks, but Spring already has quite big support for <a href="https://docs.spring.io/spring-batch/docs/current/reference/html/testing.html" target="_blank" rel="noopener">unit testing</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_integration_tests">Integration tests</h3>
<div class="sect3">
<h4 id="_go_2">Go</h4>
<div class="paragraph">
<p>There are no support for Integration Tests in <a href="https://golang.org" target="_blank" rel="noopener">Go</a>, you will have to implement everything by yourself, although it is not difficult, <a href="https://kpat.io/2019/06/testing-with-gin/" target="_blank" rel="noopener">here you can find a simple example</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_spring">Spring</h4>
<div class="paragraph">
<p>On the other hand, <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html" target="_bank">Spring has a great testing support</a>.</p>
</div>
<div class="paragraph">
<p>To write integration tests for <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> services, <a href="https://spring.io/guides/gs/testing-web/" target="_blank" rel="noopener">MockMvc</a> is really convenient.</p>
</div>
<div class="paragraph">
<p>I&#8217;ve used <a href="https://github.com/carlosvin/covid-rest/blob/master/src/test/java/com/carlosvin/covid/CountriesControllerTest.java" target="_blank" rel="noopener">MockMvc in the covid-rest project</a>.</p>
</div>
<div class="listingblock">
<div class="title">MockMvc code snippet from <a href="https://github.com/carlosvin/covid-rest/blob/master/src/test/java/com/carlosvin/covid/CountriesControllerTest.java" target="_blank" rel="noopener">CountriesControllerTest.java</a></div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java">	<span class="hljs-meta">@Autowired</span>
	<span class="hljs-keyword">private</span> MockMvc mockMvc; <b class="conum">(1)</b>

	<span class="hljs-meta">@Test</span>
	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">getCountries</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
		<span class="hljs-keyword">this</span>.mockMvc.perform(get(<span class="hljs-string">&quot;/countries&quot;</span>)) <b class="conum">(2)</b>
				.andDo(print()).andExpect(status().isOk()) <b class="conum">(3)</b>
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.*&quot;</span>, hasSize(<span class="hljs-number">144</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.ES.confirmedCases&quot;</span>,comparesEqualTo(<span class="hljs-number">9191</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.ES.deathsNumber&quot;</span>, comparesEqualTo(<span class="hljs-number">309</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.ES.countryCode&quot;</span>, comparesEqualTo(<span class="hljs-string">&quot;ES&quot;</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.ES.countryName&quot;</span>, comparesEqualTo(<span class="hljs-string">&quot;Spain&quot;</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.ES.path&quot;</span>, comparesEqualTo(<span class="hljs-string">&quot;/countries/ES&quot;</span>)))
				.andExpect(jsonPath(<span class="hljs-string">&quot;$.VC.countryName&quot;</span>, comparesEqualTo(<span class="hljs-string">&quot;Saint Vincent and the Grenadines&quot;</span>)))
				.andDo(document(<span class="hljs-string">&quot;countries/list&quot;</span>, preprocessResponse(prettyPrint(), <span class="hljs-keyword">new</span> CropPreprocessor())));
	}</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>The Spring test runner injects the MockMvc object.</p>
</li>
<li>
<p>We use MockMvc to call to the endpoint we have created.</p>
</li>
<li>
<p>Then we validate the endpoint response: status code and body.</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_performance">Performance</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Besides the languages specific differences, the main difference is the performance. The CPU consumption in <a href="https://golang.org" target="_blank" rel="noopener">Go</a> is smaller, but about the memory the difference is really significant, <strong>the order of 30 times smaller fingerprint</strong>.</p>
</div>
<div class="sect2">
<h3 id="_memory">Memory</h3>
<div class="paragraph">
<p>Here I&#8217;ve found a surprising difference, just by checking the memory consumption in my laptop.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> <code>15.6MB</code></p>
</li>
<li>
<p><a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a> <code>465.9MB</code></p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="/posts/rest-service-go-vs-java/memory-consumption-go-java.png" alt="Memory consumption">
</div>
</div>
</div>
<div class="sect2">
<h3 id="_speed">Speed</h3>
<div class="paragraph">
<p>Following the <a href="https://www.techempower.com/benchmarks/" target="_blank" rel="noopener">TechEmpower benchmarks</a>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a> is in 193 position, 9.9%.</p>
</li>
<li>
<p><a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a> is in 284 position, 4%.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Following the <a href="https://github.com/the-benchmarker/web-frameworks" target="_blank" rel="noopener">The Benchmarker results</a>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/gin-gonic/gin" target="_blank" rel="noopener">Gin framework</a>: position 33.</p>
</li>
<li>
<p><a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a>: position 68.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_conclusions">Conclusions</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If I were you, I&#8217;d choose <a href="https://golang.org" target="_blank" rel="noopener">Go</a> if:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If you value the explicit over implicit, keep in mind that there is a cost, you will most likely have to write more lines of code.</p>
</li>
<li>
<p>If you value the simplicity, <a href="https://golang.org" target="_blank" rel="noopener">Go</a> has a quite reduced set of keywords, which reduces the learning curve and simplifies the code reviews.</p>
</li>
<li>
<p>If RAM memory usage is critical for your project, actually I&#8217;d just keep away from <a href="https://spring.io/guides/gs/rest-service" target="_blank" rel="noopener">Spring Boot (REST)</a>.</p>
</li>
<li>
<p>If the project you are going to work on is a distributed system, specially if it is based on <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a>.</p>
</li>
</ul>
</div>
</div>
</div>]]></content>
            <category term="REST"/>
    <category term="API"/>
    <category term="Web Services"/>
    <category term="Java"/>
    <category term="Golang"/>
    <category term="Gingonic"/>
    <category term="Spring"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>REST URLs</title>
            <link href="https://carlosvin.github.io/posts/rest-urls/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/rest-urls/es"/>   
            <id>https://carlosvin.github.io/posts/rest-urls/en</id>
            <updated>2015-08-16T12:00:00.000Z</updated>
            <summary>Design REST API: URLs</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_rest_basics">REST Basics</a>
<ul class="sectlevel2">
<li><a href="#_rest_verbs">REST Verbs</a></li>
<li><a href="#_accessing_to_resources">Accessing to Resources</a></li>
<li><a href="#_update_resources">Update resources</a></li>
<li><a href="#_delete_resources">Delete Resources</a></li>
<li><a href="#_create_resources">Create Resources</a></li>
<li><a href="#_collections">Collections</a></li>
</ul>
</li>
<li><a href="#_common_mistake">Common mistake</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>First time I designed a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> I made several mistakes, of course. Following I&#8217;m going to explain common mistakes and what I&#8217;ve learned about <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Uniform_resource_locator" target="_blank" rel="noopener">URL</a> with examples.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_rest_basics"><a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> Basics</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p>Using <a href="https://en.wikipedia.org/wiki/Uniform_resource_locator" target="_blank" rel="noopener">URL</a>s for get resources.</p>
</li>
<li>
<p>Using <em>verbs</em> for modify resources.</p>
</li>
<li>
<p>The <em>verbs</em> are provided by the <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> protocol.</p>
</li>
<li>
<p>The <em>verbs</em> have a direct equivalency with <a href="https://en.wikipedia.org/wiki/CRUD" target="_blank" rel="noopener">CRUD</a><sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>.</p>
</li>
<li>
<p>To access to an existent resource we need an identifier.</p>
</li>
</ul>
</div>
<div class="sect2">
<h3 id="_rest_verbs"><a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> Verbs</h3>
<div class="hdlist">
<table>
<tr>
<td class="hdlist1">
POST
</td>
<td class="hdlist2">
<p><strong>Create</strong> new resources.</p>
</td>
</tr>
<tr>
<td class="hdlist1">
GET
</td>
<td class="hdlist2">
<p><strong>Read</strong> already existing resources.</p>
</td>
</tr>
<tr>
<td class="hdlist1">
PUT
</td>
<td class="hdlist2">
<p><strong>Update</strong> already existing resources.</p>
</td>
</tr>
<tr>
<td class="hdlist1">
DELETE
</td>
<td class="hdlist2">
<p><strong>Delete</strong> already existing resources.</p>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>It is clearer in the following table</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> Verb</th>
<th class="tableblock halign-left valign-top"><a href="https://en.wikipedia.org/wiki/CRUD" target="_blank" rel="noopener">CRUD</a> Action</th>
<th class="tableblock halign-left valign-top">Resource must exist</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">No</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Read</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Yes</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Update</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Yes</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Delete</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Yes</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="_accessing_to_resources">Accessing to Resources</h3>
<div class="paragraph">
<p>A resource is <em>what we want to get</em>. For example, a car.</p>
</div>
<div class="paragraph">
<p>To be able to get a car, that information is not enough, you can&#8217;t go to your car dealer and ask for whatever car, you have to specify which one you want:</p>
</div>
<div class="paragraph">
<p><em>Good morning. I&#8217;d like to have a Fiat Bravo 1.9 Emotion 120CV</em>.</p>
</div>
<div class="paragraph">
<p>In this manner the sheller knows which one is.</p>
</div>
<div class="paragraph">
<p>"Fiat Bravo 1.9 Emotion 120CV" is the <strong>identifier</strong>.</p>
</div>
<div class="paragraph">
<p>Transferring the example to <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a>s:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>GET   https://cardealer.com/api/cars/fiat-bravo-19-emotion-120cv</pre>
</div>
</div>
<div class="paragraph">
<p>Now our <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> can supply the car info.</p>
</div>
<div class="paragraph">
<p>This is a very simple example, but actually when we access to a specific resource, we have to use something to identify it, a common and recommendable practice is use <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" target="_blank" rel="noopener">UUID</a>.</p>
</div>
<div class="literalblock">
<div class="content">
<pre>GET  https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f</pre>
</div>
</div>
<div class="paragraph">
<p>But our <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a>, like a shop, it hasn&#8217;t to be so strict. We can ask for cars with several features:</p>
</div>
<div class="paragraph">
<p><em>Good morning, I want a Fiat Bravo</em>.</p>
</div>
<div class="paragraph">
<p>Then, the dealer kindly will show you all Fiat Bravo he has available. Let&#8217;s see how <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> says that.</p>
</div>
<div class="literalblock">
<div class="content">
<pre>GET  https://cardealer.com/api/cars/?brand=fiat&amp;model=bravo</pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> will return all cars with Fiat brand and Bravo model.</p>
</div>
<div class="paragraph">
<p>Brand and model are so called <strong>query parameters</strong>.</p>
</div>
<div class="paragraph">
<p>As you might already notice, to get resource information, we have always used <strong>GET</strong> <em>verb</em></p>
</div>
</div>
<div class="sect2">
<h3 id="_update_resources">Update resources</h3>
<div class="paragraph">
<p>The <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> should also support updating resources. Like reading resources, to update a resource we have to specify which resource we want to update, so we again need an <em>identifier</em>.</p>
</div>
<div class="paragraph">
<p>Before, we wanted to get information (read) and we used <strong>GET</strong> <em>verb</em>. Now the only difference is the verb.</p>
</div>
<div class="paragraph">
<p>We want to <strong>update</strong> so we use the equivalency <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> verb: <strong>PUT</strong>.</p>
</div>
<div class="literalblock">
<div class="content">
<pre>PUT   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f</pre>
</div>
</div>
<div class="paragraph">
<p>Actually something else is missing, we have to say what thing of the car we want to change, for example, let&#8217;s imagine we want to change the engine power and set it to 100CV.</p>
</div>
<div class="paragraph">
<p>We have to send the new engine power to following <a href="https://en.wikipedia.org/wiki/Uniform_resource_locator" target="_blank" rel="noopener">URL</a> <a href="https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f" class="bare">https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f</a> through <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> using <strong>PUT</strong> verb.</p>
</div>
<div class="paragraph">
<p><a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> protocol allows sending data within PUT message, we have to choose a sending format.</p>
</div>
<div class="paragraph">
<p>We can use <a href="https://en.wikipedia.org/wiki/JSON" target="_blank" rel="noopener">JSON</a> or <a href="">XML</a> or whatever, we only have to ensure that sent format is expected in server side.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Designing a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> requires to select a data format.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title"><a href="https://en.wikipedia.org/wiki/JSON" target="_blank" rel="noopener">JSON</a> example</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{ enginePower: <span class="hljs-number">100</span> }</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_delete_resources">Delete Resources</h3>
<div class="paragraph">
<p>Let&#8217;s imagine that now we are the car dealer and we don&#8217;t want to shell the Fiat Bravo Emotion 1.9CV anymore (the cce05bee-386b-11e5-a151-feff819cdc9f). We&#8217;ll keep the <a href="https://en.wikipedia.org/wiki/Uniform_resource_locator" target="_blank" rel="noopener">URL</a> that identifies the resource, but we change the verb: we don&#8217;t want to read (GET), we don&#8217;t want to update (PUT), we want to <strong>to delete (DELETE)</strong>.</p>
</div>
<div class="literalblock">
<div class="content">
<pre>DELETE   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f</pre>
</div>
</div>
<div class="paragraph">
<p>We don&#8217;t have to supply any additional info, only de verb (DELETE) and the resource identifier.</p>
</div>
</div>
<div class="sect2">
<h3 id="_create_resources">Create Resources</h3>
<div class="paragraph">
<p>And the last verb is <strong>to create (POST)</strong>. In this case we don&#8217;t have to identify the resource, because it still doesn&#8217;t exist.</p>
</div>
<div class="literalblock">
<div class="content">
<pre>POST   https://cardealer.com/api/cars/</pre>
</div>
</div>
<div class="paragraph">
<p>But we have to send the data to create the resource.</p>
</div>
<div class="paragraph">
<p>Following with the example, let&#8217;s create a new car, so we include the necessary data within POST <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> message, it is something similar what we did at section <a href="#_update_resources">Update resources</a>, but we are going to send <strong>all required data</strong>, not only the engine power.</p>
</div>
<div class="listingblock">
<div class="title"><a href="https://en.wikipedia.org/wiki/JSON" target="_blank" rel="noopener">JSON</a> example</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
<span class="hljs-attr">&quot;brand&quot;</span>: <span class="hljs-string">&quot;Fiat&quot;</span>,
<span class="hljs-attr">&quot;model&quot;</span>: <span class="hljs-string">&quot;Bravo&quot;</span>
<span class="hljs-string">&quot;year&quot;</span>: <span class="hljs-number">2010</span>
<span class="hljs-string">&quot;doors&quot;</span>: <span class="hljs-number">5</span>,
<span class="hljs-attr">&quot;enginePower&quot;</span>: <span class="hljs-number">120</span>,
<span class="hljs-attr">&quot;version&quot;</span>: <span class="hljs-string">&quot;Emotion&quot;</span>,
<span class="hljs-attr">&quot;clima&quot;</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">&quot;ac&quot;</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">&quot;fuel&quot;</span>: <span class="hljs-string">&quot;Diesel&quot;</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can delegate on the system to assign a new <strong>identifier</strong>, or simply send it within the message:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
  <span class="hljs-attr">&quot;identifier&quot;</span>: <span class="hljs-string">&quot;cce05bee-386b-11e5-a151-feff819cdc9f&quot;</span>
  <span class="hljs-string">&quot;brand&quot;</span>: <span class="hljs-string">&quot;Fiat&quot;</span>,
  <span class="hljs-attr">&quot;model&quot;</span>: <span class="hljs-string">&quot;Bravo&quot;</span>
  <span class="hljs-string">&quot;year&quot;</span>: <span class="hljs-number">2010</span>
  <span class="hljs-string">&quot;doors&quot;</span>: <span class="hljs-number">5</span>,
  <span class="hljs-attr">&quot;enginePower&quot;</span>: <span class="hljs-number">120</span>,
  <span class="hljs-attr">&quot;version&quot;</span>: <span class="hljs-string">&quot;Emotion&quot;</span>,
  <span class="hljs-attr">&quot;clima&quot;</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">&quot;ac&quot;</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">&quot;fuel&quot;</span>: <span class="hljs-string">&quot;Diesel&quot;</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_collections">Collections</h3>
<div class="paragraph">
<p>All actions we have already explained were actually applied over a cars collection.</p>
</div>
<div class="paragraph">
<p>But, what happen if a resource has a nested collection?</p>
</div>
<div class="paragraph">
<p>Continuing with cars example, a car can use a set of engine oils. So the <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> must allow update, delete or create elements in the set.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
For the example we will assume that <em>the oil identifier</em> is the attribute <em>type</em>.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_add_an_element_to_collection">Add an element to collection</h4>
<div class="paragraph">
<p>When we add a car to cars collection, what we do is create a new car, so it is the case of <a href="#_create_resources">Create Resources</a>.</p>
</div>
<div class="paragraph">
<p>To add a new engine oil to the car cce05bee-386b-11e5-a151-feff819cdc9f, that already exists:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">POST   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Response</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
  <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;5W30&quot;</span>,
  <span class="hljs-attr">&quot;otherInfo&quot;</span>: <span class="hljs-string">&quot;This is the best oil for this car&quot;</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If we want to add another one:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">POST   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Response</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
  <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;10W30&quot;</span>,
  <span class="hljs-attr">&quot;otherInfo&quot;</span>: <span class="hljs-string">&quot;This is very good for cold weather&quot;</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_update_a_collection_item">Update a collection item</h4>
<div class="paragraph">
<p>If we want to update the info of oil <em>5W30</em> of car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em>:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">PUT   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/5W30/</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Response</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-json" data-lang="json">{
  <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;5W30&quot;</span>,
  <span class="hljs-attr">&quot;otherInfo&quot;</span>: <span class="hljs-string">&quot;This is no longer the best oil for this car&quot;</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_delete_a_collection_item">Delete a collection item</h4>
<div class="paragraph">
<p>To delete an oil <em>10W30</em> from car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em>:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">DELETE   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/10W30</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_read_a_collection_item">Read a collection item</h4>
<div class="paragraph">
<p>To get the oil info <em>10W30</em> of the car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em>:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/10W30</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_list_collection_items">List collection items</h4>
<div class="paragraph">
<p>As we have seen at <a href="#_read_a_collection_item">Read a collection item</a>, we can get the info of every collection element, but we also can get multiple collection elements, sorted, paged and apply typical collection actions.</p>
</div>
<div class="paragraph">
<p>We can get all supported oils for a car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em>, it is as simple as:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can also get sorted items:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/?sort_by=type&amp;order=asc</code></pre>
</div>
</div>
<div class="paragraph">
<p>We can ask <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> to return the first 10 oils for car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em>:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/?number_of_elements=10</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> can support also pagination:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/?page=3&amp;number_of_elements=2</code></pre>
</div>
</div>
<div class="paragraph">
<p>Above request is telling <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> that returns the page 3 of all oils of car <em>cce05bee-386b-11e5-a151-feff819cdc9f</em> and it has to shown 2 oils per page. If we want to go to next page:</p>
</div>
<div class="listingblock">
<div class="title">Request</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">GET   https://cardealer.com/api/cars/cce05bee-386b-11e5-a151-feff819cdc9f/oils/?page=4&amp;number_of_elements=2</code></pre>
</div>
</div>
<div class="paragraph">
<p>All those features are supported by <strong>query parameters</strong>.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_common_mistake">Common mistake</h2>
<div class="sectionbody">
<div class="paragraph">
<p>First time I tried to design a <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a> <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> I designed an <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a>, but <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a>.</p>
</div>
<div class="paragraph">
<p>My main mistake was the <a href="https://en.wikipedia.org/wiki/Uniform_resource_locator" target="_blank" rel="noopener">URL</a>s design, I added my own <em>verbs</em> skipping <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" target="_blank" rel="noopener">HTTP</a> <em>verbs</em>.</p>
</div>
<div class="listingblock">
<div class="title">Wrong</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">POST    https://example.com/api/cars/ford-focus/delete-oil/5W30</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">The correct way</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-http" data-lang="http">DELETE  https://example.com/api/cars/ford-focus/oils/5W30</code></pre>
</div>
</div>
</div>
</div>
<div id="footnotes">
<hr>
<div class="footnote" id="_footnotedef_1">
<a href="#_footnoteref_1">1</a>. Create, Read, Update, Delete
</div>
</div>]]></content>
            <category term="REST"/>
    <category term="API"/>
    <category term="Web Services"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Multi-Domain Docker Containers</title>
            <link href="https://carlosvin.github.io/posts/reverse-proxy-multidomain-docker/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/reverse-proxy-multidomain-docker/es"/>   
            <id>https://carlosvin.github.io/posts/reverse-proxy-multidomain-docker/en</id>
            <updated>2016-11-24T20:00:00.000Z</updated>
            <summary>How to create different Docker containers with different domain names in the same host</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_use_case">Use case</a></li>
<li><a href="#_how_to_configure_multi_domain_reverse_proxy">How to Configure Multi-Domain Reverse Proxy</a>
<ul class="sectlevel2">
<li><a href="#_example_project_structure">Example Project Structure</a></li>
<li><a href="#_architecture_configuration_docker_compose">Architecture Configuration (docker-compose)</a></li>
<li><a href="#_application_image_configuration">Application Image Configuration</a></li>
<li><a href="#_adding_domain_names_to_your_development_environment_configuration">Adding domain names to your development environment configuration</a></li>
<li><a href="#_everything_ready">Everything ready!</a></li>
</ul>
</li>
</ul>
</div>
<div class="sect1">
<h2 id="_use_case">Use case</h2>
<div class="sectionbody">
<div class="paragraph">
<p>We have several server applications in the same development environment, each application is bundled in a Docker container, e.g: <strong>"Container A"</strong> and <strong>"Container B"</strong>.</p>
</div>
<div class="paragraph">
<p>With Docker those applications have the same IP address. One way to differentiate and access to an specific application is exposing different ports.</p>
</div>
<div class="imageblock center">
<div class="content">
<img src="/images/docker-multidomain/ip.png" alt="ip">
</div>
</div>
<div class="paragraph">
<p>Containers exposing the same IP address and different ports.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If we want to call to <strong>"Application A"</strong> we will do: <code>GET <a href="http://10.20.30.40:8080/colors/red" class="bare">http://10.20.30.40:8080/colors/red</a></code>.</p>
</li>
<li>
<p>If we want to call to <strong>"Application B"</strong> we will do: <code>GET <a href="http://10.20.30.40:8081/fruits/tomato" class="bare">http://10.20.30.40:8081/fruits/tomato</a></code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>But that solution is a little bit confusing, does 8080 mean we are accessing to "application A"?</p>
</div>
<div class="paragraph">
<p>It would be <strong>simpler and easier</strong> to remind something like:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Calling <strong>"Application A"</strong>: <code>GET <a href="http://a.domain.com/colors/red" class="bare">http://a.domain.com/colors/red</a></code>.</p>
</li>
<li>
<p>Calling <strong>"Application B"</strong>: <code>GET <a href="http://b.domain.com/fruits/tomato" class="bare">http://b.domain.com/fruits/tomato</a></code>.</p>
</li>
</ul>
</div>
<div class="imageblock center">
<div class="content">
<img src="/images/docker-multidomain/domain.png" alt="domain">
</div>
</div>
<div class="paragraph">
<p>Accessing applications by domain name.</p>
</div>
<div class="paragraph">
<p>Get that extra semantic value is much simpler than I thought at the beginning and you will see below.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_how_to_configure_multi_domain_reverse_proxy">How to Configure Multi-Domain Reverse Proxy</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I said it is easy, because we almost have to do nothing, another container will do it for us, especifically we are going to use <a href="https://github.com/jwilder/nginx-proxy" target="_blank" rel="noopener">nginx-proxy</a>, it will automatically generate the required <a href="https://www.nginx.com" target="_blank" rel="noopener">NGINX</a> configurations.</p>
</div>
<div class="paragraph">
<p>So, we will have 2 applications + 1 proxy, that is 3 containers.</p>
</div>
<div class="imageblock center">
<div class="content">
<img src="/images/docker-multidomain/proxy.png" alt="domain">
</div>
</div>
<div class="paragraph">
<p>3 containers, 2 applications and 1 proxy</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
You can download the full example at <a href="https://github.com/carlosvin/docker-reverse-proxy-multi-domain" class="bare">https://github.com/carlosvin/docker-reverse-proxy-multi-domain</a>.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_example_project_structure">Example Project Structure</h3>
<div class="dlist">
<dl>
<dt class="hdlist1">docker-compose.yaml</dt>
<dd>
<p>Main configuration file describing architecture in previous picture.</p>
</dd>
<dt class="hdlist1">a</dt>
<dd>
<p>Application A directory.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">Dockerfile</dt>
<dd>
<p>Container A configuration file.</p>
</dd>
</dl>
</div>
</dd>
<dt class="hdlist1">b</dt>
<dd>
<p>Application B directory.</p>
<div class="dlist">
<dl>
<dt class="hdlist1">Dockerfile</dt>
<dd>
<p>Container B configuration file.</p>
</dd>
</dl>
</div>
</dd>
</dl>
</div>
<div class="paragraph">
<p><a href="https://github.com/carlosvin/docker-reverse-proxy-multi-domain" target="_blank" rel="noopener">View Project</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_architecture_configuration_docker_compose">Architecture Configuration (docker-compose)</h3>
<div class="paragraph">
<p>The relationships between containers is the most interesting part in this example.</p>
</div>
<div class="listingblock">
<div class="title">docker-reverse-proxy-multi-domain/docker-compose.yaml</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-yaml" data-lang="yaml"><span class="hljs-attr">a:</span>
  <span class="hljs-attr">build:</span> <span class="hljs-string">a</span> <b class="conum">(4)</b>
  <span class="hljs-attr">environment:</span>
    <span class="hljs-attr">VIRTUAL_HOST:</span> <span class="hljs-string">a.domain.com</span> <b class="conum">(1)</b>
  <span class="hljs-attr">restart:</span> <span class="hljs-string">always</span>

<span class="hljs-attr">b:</span>
  <span class="hljs-attr">build:</span> <span class="hljs-string">b</span> <b class="conum">(5)</b>
  <span class="hljs-attr">environment:</span>
    <span class="hljs-attr">VIRTUAL_HOST:</span>  <span class="hljs-string">b.domain.com</span> <b class="conum">(2)</b>
  <span class="hljs-attr">restart:</span> <span class="hljs-string">always</span>

<span class="hljs-attr">nginx-proxy:</span> <b class="conum">(3)</b>
  <span class="hljs-attr">image:</span> <span class="hljs-string">jwilder/nginx-proxy</span>
  <span class="hljs-attr">ports:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">&quot;80:80&quot;</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">&quot;443:443&quot;</span>
  <span class="hljs-attr">volumes:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">/var/run/docker.sock:/tmp/docker.sock:ro</span>

  <span class="hljs-attr">restart:</span> <span class="hljs-string">always</span>
  <span class="hljs-attr">privileged:</span> <span class="hljs-literal">true</span></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>Configure the domain name for app a.</p>
</li>
<li>
<p>Configure the domain name for app b.</p>
</li>
<li>
<p>From this line there is proxy configuration (copy/paste part).</p>
</li>
<li>
<p>We tell docker-compose has to build Docker images within specified directory.</p>
</li>
<li>
<p>For example, we are saying that docker-compose has to build a Docker image using ../b/Dockerfile file.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_application_image_configuration">Application Image Configuration</h3>
<div class="listingblock">
<div class="title">a/Dockerfile</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-docker" data-lang="docker"><span class="hljs-keyword">FROM</span> httpd:<span class="hljs-number">2.4</span> <b class="conum">(1)</b>
<span class="hljs-keyword">RUN</span><span class="bash"> <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;A&lt;/h1&gt;App A works!&lt;/body&gt;&lt;/html&gt;&quot;</span> &gt; /usr/<span class="hljs-built_in">local</span>/apache2/htdocs/index.html </span><b class="conum">(2)</b></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>We import an image with an apache server.</p>
</li>
<li>
<p>It serves a file that prints "Host A" as default page.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The configuration for application B is pretty much the same:</p>
</div>
<div class="listingblock">
<div class="title">b/Dockerfile</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-docker" data-lang="docker"><span class="hljs-keyword">FROM</span> httpd:<span class="hljs-number">2.4</span>
<span class="hljs-keyword">RUN</span><span class="bash"> <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;B&lt;/h1&gt;App B works!&lt;/body&gt;&lt;/html&gt;&quot;</span> &gt; /usr/<span class="hljs-built_in">local</span>/apache2/htdocs/index.html</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_adding_domain_names_to_your_development_environment_configuration">Adding domain names to your development environment configuration</h3>
<div class="paragraph">
<p>In Linux we just have to map the local address to domain names you have chosen, in the example <code>a.domain.com</code> and <code>b.domain.com</code>.</p>
</div>
<div class="listingblock">
<div class="title">/etc/hosts</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">127.0.0.1    localhost.localdomain localhost
::1          localhost6.localdomain6 localhost6
127.0.0.1    a.domain.com <b class="conum">(1)</b>
127.0.0.1    b.domain.com</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>We just added last 2 lines.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_everything_ready">Everything ready!</h3>
<div class="paragraph">
<p>Now we just have to test the example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">docker-compose build
docker-compose up</code></pre>
</div>
</div>
<div class="paragraph">
<p>The 3 containers are running now.</p>
</div>
<div class="paragraph">
<p>So we can open our favorite web browser and go to <code>a.domain.com</code>. It will show <strong>App A works!</strong>. If we go to <code>b.domain.com</code> then we will see <strong>App B works!</strong>.</p>
</div>
<div class="imageblock center">
<div class="content">
<img src="/images/docker-multidomain/a.screenshot.png" alt="App A works!">
</div>
<div class="title">Figure 1. a.domain.com</div>
</div>
<div class="imageblock center">
<div class="content">
<img src="/images/docker-multidomain/b.screenshot.png" alt="App B works!">
</div>
<div class="title">Figure 2. b.domain.com</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
In most of the Linux distros you will need privileges to run Docker commands (<code>sudo</code>).
</td>
</tr>
</table>
</div>
</div>
</div>
</div>]]></content>
            <category term="Docker"/>
    <category term="Microservices"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Rust web frameworks comparison</title>
            <link href="https://carlosvin.github.io/posts/rust-rest-framework-comparison/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/rust-rest-framework-comparison/es"/>   
            <id>https://carlosvin.github.io/posts/rust-rest-framework-comparison/en</id>
            <updated>2016-04-14T18:40:00.000Z</updated>
            <summary>REST frameworks for Rust Comparison</summary>
            <content type="html"><![CDATA[<div class="paragraph">
<p>I&#8217;m doing some experiments with <a href="https://www.rust-lang.org" target="_blank" rel="noopener">Rust</a> because it is a language that promises to be as fast as <a href="https://en.wikipedia.org/wiki/C%2B%2B" target="_blank" rel="noopener">C/C++</a>, but safer in regards to memory management. Essentially, it doesn&#8217;t allow the developer to do "bad things" with the memory like: forget releasing that is not going to be used anymore or release memory still in use. In such scenarios, <a href="https://www.rust-lang.org" target="_blank" rel="noopener">Rust</a> won&#8217;t compile.</p>
</div>
<div class="paragraph">
<p>Just for learning I&#8217;ve started a small project that offers a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="noopener">REST</a> <a href="https://en.wikipedia.org/wiki/Application_programming_interface" target="_blank" rel="noopener">API</a>, so I&#8217;ve started looking for frameworks to ease/speed up the development. I&#8217;ve found a really useful <a href="https://github.com/flosse/rust-web-framework-comparison" target="_blank" rel="noopener">Rust web frameworks comparison</a>.</p>
</div>]]></content>
            <category term="Frameworks"/>
    <category term="Rustlang"/>
    <category term="Programming Languages"/>
    <category term="REST"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Java serialization ways: Performance Comparison</title>
            <link href="https://carlosvin.github.io/posts/serialization-java-serializable-externalizable/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/serialization-java-serializable-externalizable/es"/>   
            <id>https://carlosvin.github.io/posts/serialization-java-serializable-externalizable/en</id>
            <updated>2014-05-13T15:00:00.000Z</updated>
            <summary>Java serialization ways, performance comparison</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_serializable">Serializable</a></li>
<li><a href="#_externalizable">Externalizable</a></li>
<li><a href="#_performance_tests_serializable_vs_externalizable">Performance tests (Serializable vs. Externalizable)</a>
<ul class="sectlevel2">
<li><a href="#_implementing_serializable">Implementing Serializable</a></li>
<li><a href="#_implementing_externalizable_wrong_way">Implementing Externalizable (wrong way)</a></li>
<li><a href="#_implementing_externalizable_right_way">Implementing Externalizable (right way)</a></li>
<li><a href="#_results_analysis">Results Analysis</a></li>
</ul>
</li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Recently I&#8217;ve had to serialize/deserialize some data in <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> binary format. Lately I use <a href="https://www.json.org" target="_blank" rel="noopener">JSON</a> or <a href="https://en.wikipedia.org/wiki/XML" target="_blank" rel="noopener">XML</a> formats.</p>
</div>
<div class="paragraph">
<p>I remember that to serialize <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> objects they must implement the <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html" target="_blank" rel="noopener">Serializable</a> interface, but I had also read in Internet other way, implementing the <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html" target="_blank" rel="noopener">Externalizable</a> interface, then, which interface must I implement? It depends on what you want such as everything in the life.</p>
</div>
<div class="paragraph">
<p>When to use <a href="#_serializable">Serializable</a> or <a href="#_externalizable">Externalizable</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_serializable">Serializable</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p>To serialize easily. You have to write less code.</p>
</li>
<li>
<p>This way has some restrictions: The object to serialize must implement the default constructor (0 args). It must be responsible to manage the parent class attributes.</p>
</li>
<li>
<p>The performance is not as important, we will see more about that in <a href="#_performance_tests_serializable_vs_externalizable">Performance tests (Serializable vs. Externalizable)</a>.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_externalizable">Externalizable</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p>You must implement the serialization/deserialization methods, so you have to write more code.</p>
</li>
<li>
<p>When you cannot use <a href="#_serializable">Serializable</a>.</p>
</li>
<li>
<p>When you want to improve the performance, as we&#8217;ll see in <a href="#_performance_tests_serializable_vs_externalizable">Performance tests (Serializable vs. Externalizable)</a>.</p>
</li>
<li>
<p>If you have to manage the serialization of parent class attributes, then I recommend you use <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html" target="_blank" rel="noopener">Externalizable</a>, because we&#8217;ll avoid a weird private methods overriding.</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">writeObject</span><span class="hljs-params">(ObjectOutputStream oos)</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">readObject</span><span class="hljs-params">(ObjectInputStream ois)</span></span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_performance_tests_serializable_vs_externalizable">Performance tests (Serializable vs. Externalizable)</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="#_serializable">Serializable</a>: Java, through introspection, guesses the types of class attributes to know how to serialize/deserialize them, but this "magic" is not free, it has a performance penalty.</p>
</div>
<div class="paragraph">
<p>When we use <a href="#_externalizable">Externalizable</a> interface, we decide how to serialize/deserialize, namely we have to write the code that does it. We&#8217;ve lost ease, but also we avoid that <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> does some tasks, so if we override the methods properly, we&#8217;ll get a performance improvement.</p>
</div>
<div class="paragraph">
<p>To know how big is the performance difference between both interfaces, I&#8217;ve written a <a href="https://github.com/carlosvin/serializations-performance-java" target="_blank" rel="noopener">tiny example in which we serialize an object with 2 collections with 100000 elements each one</a>. Here you can find the <a href="http://carlosvin.github.io/serializations-performance-java/classes/com.github.carlosvin.contacts.SerializationTest.html" target="_blank" rel="noopener">tests execution results</a>. There are 3 different implementations:</p>
</div>
<div class="sect2">
<h3 id="_implementing_serializable">Implementing Serializable</h3>
<div class="paragraph">
<p>As we mentioned above, <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> has to guess certain things. During this process it sacrifices some of performance (slowest way), in exchange we get really simple source code, the class to serialize just has to implement the <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html" target="_blank" rel="noopener">Serializable</a> interface.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Contacts</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span> </span>{
  <span class="hljs-comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>serializing: 1133 millisecond</p>
</li>
<li>
<p>deserializing: 506 millisecond</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_implementing_externalizable_wrong_way">Implementing Externalizable (wrong way)</h3>
<div class="paragraph">
<p>If the class implements <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html" target="_blank" rel="noopener">Externalizable</a>, we must tell to <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> how it has to serialize/deserialize the class attributes. We just have to be careful, because if we did it bad, then we&#8217;ll get the worst of the both worlds: more complex implementation and bad performance, i.e: If we serialize/deserialize complex class attributes (like collections), <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> will also have to guess many things about the attributes type.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">readExternal</span><span class="hljs-params">(ObjectInput in)</span> <span class="hljs-keyword">throws</span> IOException, ClassNotFoundException </span>{
  setEmails((Set&lt;String&gt;) in.readObject());
  setPhones((Set&lt;String&gt;) in.readObject());
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">writeExternal</span><span class="hljs-params">(ObjectOutput out)</span> <span class="hljs-keyword">throws</span> IOException </span>{
  out.writeObject(emails);
  out.writeObject(phones);
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>serializing: 737 millisecond</p>
</li>
<li>
<p>deserializing: 367 millisecond</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_implementing_externalizable_right_way">Implementing Externalizable (right way)</h3>
<div class="paragraph">
<p>If we serialize one by one the collection elements, then we&#8217;ll save more time, because <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> serializes simple types, this way avoids guessing things that we actually know.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-java" data-lang="java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">readExternal</span><span class="hljs-params">(ObjectInput in)</span> <span class="hljs-keyword">throws</span> IOException, ClassNotFoundException </span>{
  emails.clear();
  phones.clear();
  <span class="hljs-keyword">int</span> nEmails = in.readInt();
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nEmails; i++) {
    emails.add(in.readUTF());
  }
  <span class="hljs-keyword">int</span> nPhones = in.readInt();
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nPhones; i++) {
    phones.add(in.readUTF());
  }
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">writeExternal</span><span class="hljs-params">(ObjectOutput out)</span> <span class="hljs-keyword">throws</span> IOException </span>{
  out.writeInt(emails.size());
  <span class="hljs-keyword">for</span> (String e : emails) {
    out.writeUTF(e);
  }
  out.writeInt(phones.size());
  <span class="hljs-keyword">for</span> (String p : phones) {
    out.writeUTF(p);
  }
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>serializing: 204 millisecond</p>
</li>
<li>
<p>deserializing: 92 millisecond</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>We&#8217;ve gained performance at expense of write more code.</p>
</div>
</div>
<div class="sect2">
<h3 id="_results_analysis">Results Analysis</h3>
<div class="paragraph">
<p>We don&#8217;t gain performance due to use an interface or the other one.</p>
</div>
<div class="paragraph">
<p>We gain performance because <a href="#_externalizable">Externalizable</a> interface forces us to implement ourselves the guessing code, so <a href="https://www.java.com" target="_blank" rel="noopener">Java</a> doesn&#8217;t have to do that.</p>
</div>
<div class="paragraph">
<p>As we have seen at <a href="#_implementing_externalizable_wrong_way">Implementing Externalizable (wrong way)</a>, si no tenemos cuidado, conseguiremos una mejora poco significativa a costa de complicar nuestro código fuente.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="http://carlosvin.github.io/serializations-performance-java/classes/com.github.carlosvin.contacts.SerializationTest.html" target="_blank" rel="noopener">Test results</a>.</p>
</li>
<li>
<p><a href="https://github.com/carlosvin/serializations-performance-java/">Code in Github</a>.</p>
</li>
</ul>
</div>
</div>
</div>
</div>]]></content>
            <category term="Java"/>
    <category term="Performance"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>Svelte, a bright future with Snowpack</title>
            <link href="https://carlosvin.github.io/posts/svelte-next-bright-future-with-snowpack/en" />
               
            <id>https://carlosvin.github.io/posts/svelte-next-bright-future-with-snowpack/en</id>
            <updated>2020-10-25T00:00:00.000Z</updated>
            <summary>Echoing Richard Harris announcements in Svelte Summit 2020: Sapper 1.0 never gonna happen, the new Svelte Kit, Snowpack as build tool, Javascript Module System.</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_sapper_1_0_is_not_going_to_happen">Sapper 1.0 is not going to happen</a></li>
<li><a href="#_snowpack">Snowpack</a></li>
<li><a href="#_example">Example</a>
<ul class="sectlevel2">
<li><a href="#_build">Build</a></li>
</ul>
</li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Today I finally got some time to watch the video <a href="https://www.youtube.com/watch?v=qSfdtmcZ4d0" target="_blank" rel="noopener">Rich Harris: Futuristic Web Development</a> recorded at <a href="https://sveltesummit.com/" target="_blank" rel="noopener">Svelte Summit 2020</a>. If you have 20 minutes, just stop reading and <a href="https://www.youtube.com/watch?v=qSfdtmcZ4d0" target="_blank" rel="noopener">watch it</a>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
If you have 20 minutes, just stop reading and watch <a href="https://www.youtube.com/watch?v=qSfdtmcZ4d0" target="_blank" rel="noopener">Rich Harris: Futuristic Web Development</a> video.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_sapper_1_0_is_not_going_to_happen">Sapper 1.0 is not going to happen</h2>
<div class="sectionbody">
<div class="paragraph">
<p>As you might know, this blog is powered by <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a>. I am already quite happy with it, so when I hear this announcement, I felt like when they cancel a TV Series that I am enjoying.</p>
</div>
<div class="paragraph">
<p>Happily, there is a good reason, there is going to be a better <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a>, I think they will call it svelte-kit, it is solving some issues and improving some aspects of <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a>, but the main benefit, in my opinion, is that you won&#8217;t have to choose between <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a> or <a href="https://svelte.dev/" target="_blank" rel="noopener">Svelte</a> when you start a new application, everything will be supported by the <a href="https://svelte.dev/" target="_blank" rel="noopener">Svelte</a> ecosystem.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_snowpack">Snowpack</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://www.snowpack.dev" target="_blank" rel="noopener">Snowpack</a> will become the default <a href="https://svelte.dev/" target="_blank" rel="noopener">Svelte</a> builder. It is not a regular bundler like <a href="https://webpack.js.org" target="_blank" rel="noopener">Webpack</a> or <a href="https://rollupjs.org/" target="_blank" rel="noopener">Rollup</a>. It relies on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import" target="_blank" rel="noopener">Javascript modules</a> so your application delegate the modules loading on the web browser; traditionally the chunks are loaded by the bundler (or by source code injected by the bundler).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_example">Example</h2>
<div class="sectionbody">
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
This example is just a copy from the <a href="https://www.youtube.com/watch?v=qSfdtmcZ4d0" target="_blank" rel="noopener">Rich Harris: Futuristic Web Development</a> video.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">How to create the sample project</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">mkdir svelte-next-sample
<span class="hljs-built_in">cd</span> svelte-next-sample
npm init svelte@next
npm install</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Start development server</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm run dev

[snowpack] &gt; Listening on http://localhost:3000</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will find many similarities with <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a>, like the <code>routes</code> and <code>components</code> folders.</p>
</div>
<div class="sect2">
<h3 id="_build">Build</h3>
<div class="listingblock">
<div class="title">Build the project for production</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm run build</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_ssr">SSR</h4>
<div class="paragraph">
<p>By default the project is configured with SSR rendering enabled.</p>
</div>
<div class="listingblock">
<div class="title">SSR with nodejs server and client</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm run build
...

&gt; Optimizing...
  ✔ server
  ✔ client

&gt; Generating app...
  Using @sveltejs/adapter-node <b class="conum">(1)</b>
  Prerendering static pages...
  ✔ <span class="hljs-keyword">done</span></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>This is the default adapter to generate SSR application with a nodejs server and a client.</p>
</li>
</ol>
</div>
</div>
<div class="sect3">
<h4 id="_pure_static_site">Pure static site</h4>
<div class="paragraph">
<p>This blog is a pure static website, it doesn&#8217;t require a server. With <a href="https://sapper.svelte.dev" target="_blank" rel="noopener">Sapper</a> we have the option to execute <code>sapper export</code> and it generates the app with no server required.</p>
</div>
<div class="paragraph">
<p>With this new approach, to generate a static site, we just have to use a different adapter:</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm i -D @sveltejs/adapter-static</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">svelte.config.js</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript"><span class="hljs-built_in">module</span>.exports = {
	<span class="hljs-attr">adapter</span>: <span class="hljs-string">&#x27;@sveltejs/adapter-static&#x27;</span>
};</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm run build

&gt; Generating app...
  Using @sveltejs/adapter-static <b class="conum">(1)</b>
  ✔ <span class="hljs-keyword">done</span></code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>The static adapter is selected</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>But we are not yet done, because the build step is not generating the html file that we can use as entry point. We have to execute one command more: <code>svelte-kit adapt</code>, <a href="https://github.com/carlosvin/carlosvin.github.io/issues/39#issuecomment-774200641" target="_blank" rel="noopener">thanks Joshua for pointing this out</a>.</p>
</div>
<div class="listingblock">
<div class="title">We can add it to the package.json scripts section</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-diff" data-lang="diff">	&quot;scripts&quot;: {
		&quot;dev&quot;: &quot;svelte-kit dev&quot;,
		&quot;build&quot;: &quot;svelte-kit build&quot;,
		&quot;start&quot;: &quot;svelte-kit start&quot;,
<span class="hljs-addition">+		&quot;adapt&quot;: &quot;svelte-kit adapt&quot;</span>
	},</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-bash" data-lang="bash">npm run adapt <b class="conum">(1)</b>
&gt; svelte-kit adapt


&gt; Using @sveltejs/adapter-static
  ✔ <span class="hljs-keyword">done</span>

ls build <b class="conum">(2)</b>
_app  favicon.ico  index.html  robots.txt</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>It generates the static entry point, index.html in build directory.</p>
</li>
<li>
<p>Listing the content of build directory</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</div>]]></content>
            <category term="Svelte"/>
    <category term="Sapper"/>
    <category term="Snowpack"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
  <entry>
            <title>This is Sapper!</title>
            <link href="https://carlosvin.github.io/posts/this-is-sapper/en" />
            <link 
				rel="alternate"
				hreflang="es"
				href="https://carlosvin.github.io/posts/this-is-sapper/es"/>   
            <id>https://carlosvin.github.io/posts/this-is-sapper/en</id>
            <updated>2020-08-28T00:00:00.000Z</updated>
            <summary>This static blog site has been migrated from Nikola to Sapper. In this article we will go through the main reasons, performance results and some other thoughts about using Sapper and Svelte for generate an static web site</summary>
            <content type="html"><![CDATA[<div id="toc" class="toc">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_why_leaving_nikola">Why leaving Nikola</a></li>
<li><a href="#_why_sapper">Why Sapper</a>
<ul class="sectlevel2">
<li><a href="#_dx_developer_experience">DX: Developer experience</a></li>
<li><a href="#_ux_final_result_of_blogs_in_sapper">UX: Final result of blogs in Sapper</a></li>
</ul>
</li>
<li><a href="#_asciidoctor">Asciidoctor</a>
<ul class="sectlevel2">
<li><a href="#_rollup_plugin_asciidoc_to_the_rescue">rollup-plugin-asciidoc to the rescue</a></li>
<li><a href="#_rollup_plugin_glob_to_the_rescue">rollup-plugin-glob to the rescue</a></li>
</ul>
</li>
<li><a href="#_syntax_highlighting">Syntax highlighting</a></li>
<li><a href="#_result">Result</a></li>
<li><a href="#_testing">Testing</a>
<ul class="sectlevel2">
<li><a href="#_writing_a_test">Writing a test</a></li>
</ul>
</li>
<li><a href="#_typescript">Typescript</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>I&#8217;ve migrated my blog infrastructure from <a href="https://getnikola.com" target="_blank" rel="noopener">Nikola</a> + <a href="https://en.wikipedia.org/wiki/ReStructuredText" target="_blank" rel="noopener">reStructuredText</a> to <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> + <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_why_leaving_nikola">Why leaving <a href="https://getnikola.com" target="_blank" rel="noopener">Nikola</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>This blog was powered by <a href="https://getnikola.com" target="_blank" rel="noopener">Nikola</a> since 2014, when <a href="https://jamstack.org" target="_blank" rel="noopener">JAMStack</a> term didn&#8217;t even exist. It really did the job, it has out-of-the-box features that I needed:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Simple multi-lang support.</p>
</li>
<li>
<p><a href="https://en.wikipedia.org/wiki/ReStructuredText" target="_blank" rel="noopener">reStructuredText</a> which I prefer over <a href="https://en.wikipedia.org/wiki/Markdown" target="_blank" rel="noopener">Markdown</a>.</p>
</li>
<li>
<p>It was developed in <a href="https://python.org" target="_blank" rel="noopener">Python</a>, a programming language that I know and I enjoy.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>But, I faced some <strong>issues</strong> which annoyed me for quite some time:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>My config file got bloated.</p>
</li>
<li>
<p>It was not easy to modify or create templates, neither to find templates I liked.</p>
</li>
<li>
<p>Site performance was not awesome, my last <a href="https://developers.google.com/web/tools/lighthouse" target="_blank" rel="noopener">Lighthouse audits</a> report was around 80, depending on the section. Except SEO section, which was 96.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_why_sapper">Why Sapper</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_dx_developer_experience">DX: Developer experience</h3>
<div class="paragraph">
<p>I already used <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> for creating some tiny <a href="https://web.dev/progressive-web-apps" target="_blank" rel="noopener">PWA</a>s <sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>, here 2 examples I developed to learn <a href="https://svelte.dev" target="_blank" rel="noopener">Svelte</a> and <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a>:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><a href="https://currency-loss.netlify.app" target="_blank" rel="noopener">Currency Exchage Loss Calculator</a></dt>
<dd>
<p>It is a helpful application for travelers visiting currency exchange houses. Based on the rate they offer and the money you want ot change it calculates the amount of money that you are losing in that transaction.</p>
</dd>
<dt class="hdlist1"><a href="https://covid-stats-pwa.netlify.app" target="_blank" rel="noopener">COVID-19 Stats</a></dt>
<dd>
<p>It shows COVID-19 statistics by country and date.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>While creating those <a href="https://web.dev/progressive-web-apps" target="_blank" rel="noopener">PWA</a>s, developing experience with <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a>&amp;<a href="https://svelte.dev" target="_blank" rel="noopener">Svelte</a> was quite impressive.</p>
</div>
</div>
<div class="sect2">
<h3 id="_ux_final_result_of_blogs_in_sapper">UX: Final result of blogs in Sapper</h3>
<div class="paragraph">
<p>Lately I&#8217;ve stumbled upon with some blogs using <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> like the own <a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> blog, <a href="https://www.codingwithjesse.com/blog/statically-generating-a-blog-with-svelte-sapper/" target="_blank" rel="noopener">Coding with Jessie</a> or <a href="https://www.swyx.io/writing/svelte-static/" target="_blank" rel="noopener">swyx.io</a>. Check those blogs by yourself, IMHO user experience is pretty good in all of them.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
<a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> is inspired in <a href="https://nextjs.org/">Next.js</a>, here you can find <a href="https://sapper.svelte.dev/docs#Comparison_with_Next_js">a comparison with this better known JAMStack framework</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_asciidoctor"><a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>I don&#8217;t have a strong opinion about using <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> or <a href="https://en.wikipedia.org/wiki/ReStructuredText" target="_blank" rel="noopener">reStructuredText</a>, I am comfortable with both of them, but there is more support for <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> in other programming languages, like <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank" rel="noopener">JavaScript</a>. So basically I switched to <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> because I didn&#8217;t find a <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank" rel="noopener">JavaScript</a> library able to properly convert <a href="https://en.wikipedia.org/wiki/ReStructuredText" target="_blank" rel="noopener">reStructuredText</a> to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a>.</p>
</div>
<div class="paragraph">
<p>The main issue I found not using <a href="https://en.wikipedia.org/wiki/Markdown" target="_blank" rel="noopener">Markdown</a> was the lack of <a href="https://rollupjs.org" target="_blank" rel="noopener">Rollup</a> plugins to convert <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a>, so I just created one, <a href="https://github.com/carlosvin/rollup-plugin-asciidoc" target="_blank" rel="noopener">rollup-plugin-asciidoc</a>. Implementation was quite simple, the plugin is just using <a href="https://asciidoctor.org/docs/asciidoctor.js/" target="_blank" rel="noopener">Asciidoctor.js</a> <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank" rel="noopener">JavaScript</a> library to convert the <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> text input to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a>.</p>
</div>
<div class="sect2">
<h3 id="_rollup_plugin_asciidoc_to_the_rescue"><a href="https://github.com/carlosvin/rollup-plugin-asciidoc" target="_blank" rel="noopener">rollup-plugin-asciidoc</a> to the rescue</h3>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
With <a href="https://github.com/carlosvin/rollup-plugin-asciidoc" target="_blank" rel="noopener">rollup-plugin-asciidoc</a> we can import <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> files in our blog and <a href="https://rollupjs.org" target="_blank" rel="noopener">Rollup</a> will convert them to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a>.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_example">Example</h4>
<div class="listingblock">
<div class="title">a-blog-post.adoc</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-adoc" data-lang="adoc"><span class="hljs-section">= Post title</span>
<span class="hljs-meta">:date:</span> 2019-11-11

Such a post!</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">With <a href="https://github.com/carlosvin/rollup-plugin-asciidoc" target="_blank" rel="noopener">rollup-plugin-asciidoc</a> we can import <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> files one by one.</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript"><span class="hljs-keyword">import</span> doc <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./a-blog-post.adoc&#x27;</span>;

<span class="hljs-built_in">console</span>.log(doc);</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Output</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript">{
  <span class="hljs-attr">meta</span>: {
    <span class="hljs-attr">title</span>: <span class="hljs-string">&quot;Post title&quot;</span>,
    <span class="hljs-attr">date</span>: <span class="hljs-string">&quot;2019-11-11&quot;</span>
  },
  <span class="hljs-attr">html</span>: <span class="hljs-string">&quot;&lt;p&gt;Such a post!&lt;/p&gt;&quot;</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Importing files one by one is not really convenient for a blog where we have many files which we don&#8217;t want to import manually.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_rollup_plugin_glob_to_the_rescue"><a href="https://www.npmjs.com/package/rollup-plugin-glob" target="_blank" rel="noopener">rollup-plugin-glob</a> to the rescue</h3>
<div class="paragraph">
<p>With <a href="https://www.npmjs.com/package/rollup-plugin-glob" target="_blank" rel="noopener">rollup-plugin-glob</a> we can import all the files in a directory by extension, so now we have our index of posts automatically converted to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript"><span class="hljs-keyword">import</span> allAdoc <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;../posts/**/*.adoc&#x27;</span>;

allAdoc.forEach(<span class="hljs-function"><span class="hljs-params">post</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(post));</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Output: List of posts already converted to HTML</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript">{ <span class="hljs-attr">meta</span>: { <span class="hljs-attr">title</span>: <span class="hljs-string">&quot;Post title&quot;</span>, <span class="hljs-attr">date</span>: <span class="hljs-string">&quot;2019-11-11&quot;</span> },
  <span class="hljs-attr">html</span>: <span class="hljs-string">&quot;&lt;p&gt;Post 1.&lt;/p&gt;&quot;</span>
}
{ <span class="hljs-attr">meta</span>: { <span class="hljs-attr">title</span>: <span class="hljs-string">&quot;Post title&quot;</span>, <span class="hljs-attr">date</span>: <span class="hljs-string">&quot;2020-02-22&quot;</span> },
  <span class="hljs-attr">html</span>: <span class="hljs-string">&quot;&lt;h2&gt;Title post&lt;/h2&gt;&lt;p&gt;This is a sample post...&lt;/p&gt;&quot;</span>
}
<span class="hljs-comment">// ...</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_syntax_highlighting">Syntax highlighting</h2>
<div class="sectionbody">
<div class="paragraph">
<p>My blog is mainly about Software Engineering, so I have a strong requirement, code highlighting.</p>
</div>
<div class="paragraph">
<p>At the begging I started using <a href="https://highlightjs.org/usage/" target="_blank" rel="noopener">highlightjs library from a CDN</a> for source code highlighting. We use imported library to parse the source code and for styling the result we need to import also a CSS file.</p>
</div>
<div class="paragraph">
<p>Later I realized that we can do the parsing work when we compile <a href="https://asciidoctor.org/" target="_blank" rel="noopener">Asciidoctor</a> to <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noopener">HTML</a> in <a href="https://github.com/carlosvin/rollup-plugin-asciidoc" target="_blank" rel="noopener">rollup-plugin-asciidoc</a> implementation, so we don&#8217;t have to download the <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank" rel="noopener">JavaScript</a> file.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Doing code highlighting transformation during the site building phase we are improving application performance and reducing bundle size.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Code highlighting transformation during site build step bring 2 great benefits:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Reducing bundle size: we don&#8217;t need the 27KB of <a href="https://highlightjs.org/usage/">highlightjs javascript library</a>.</p>
</li>
<li>
<p>Improving performance: source code parsing is done only once while site is built.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_result">Result</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I still have some <a href="https://github.com/carlosvin/carlosvin.github.io/issues" target="_blank" rel="noopener">work to do</a>, but so far I have a blog with following features:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Automated generation of <a href="/sitemap.xml">Sitemap</a> and <a href="/rss">RSS feed</a>.</p>
</li>
<li>
<p>Multi-language support (I still have to translate some texts).</p>
</li>
<li>
<p>Syntax highlighting.</p>
</li>
<li>
<p>100 score in <a href="https://developers.google.com/web/tools/lighthouse" target="_blank" rel="noopener">Lighthouse audits</a>.</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="/images/lighthouse-results.webp" alt="lighthouse score" width="95%">
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_testing">Testing</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I am a big fan of automated testing, I don&#8217;t love writing them, but I think they are the best way to know if your software is behaving as expected.</p>
</div>
<div class="paragraph">
<p><a href="https://sapper.svelte.dev/" target="_blank" rel="noopener">Sapper</a> template brings a pre-configured simple end to end test. It is using <a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>, an E2E <sup class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnotedef_2" title="View footnote.">2</a>]</sup> testing framework which has a nicer developer experience than <a href="https://www.selenium.dev/" target="_blank" rel="noopener">Selenium</a>, although I think it is still far of being <a href="https://blog.logrocket.com/cypress-io-the-selenium-killer/" target="_blank" rel="noopener">the Selenium Killer</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Not yet a <a href="https://www.selenium.dev/" target="_blank" rel="noopener">Selenium</a> killer: The main reason is that <a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a> lacks of some features you might need, depending on the project, like cross-browser and cross-platform testing offered by <a href="https://www.selenium.dev/documentation/en/grid/components_of_a_grid/" target="_blank" rel="noopener">Selenium grid</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>I&#8217;ve added some tests for this blog (and I plan to add more), I&#8217;ve tested that post header information is correct, that redirection logic is working, main navigation works and metadata is correct, in a couple of hour and including bugfixes! That&#8217;s why I love writing tests with <a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>, the productivity.</p>
</div>
<div class="sect2">
<h3 id="_writing_a_test">Writing a test</h3>
<div class="paragraph">
<p>It works pretty much as Selenium.
. Opens a page
. Access to an element using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/id" target="_blank" rel="noopener">HTML identifier</a> (<code>#element-id</code>), <a href="https://en.wikipedia.org/wiki/XPath" target="_blank" rel="noopener">XPath</a> (<code>/a[@title='link title']</code>) or <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors" target="_blank" rel="noopener">CSS selector</a> (<code>div &gt; a.cssClass</code>).
. Interact with selected element on the page.
. Validate expectations.</p>
</div>
<div class="paragraph">
<p>You can find this blog tests at <a href="https://github.com/carlosvin/carlosvin.github.io/tree/site/cypress/integration">cypress/integration</a> folder.</p>
</div>
<div class="listingblock">
<div class="title">Simple test example</div>
<div class="content">
<pre tabindex="0" class="highlight"><code class="language-javascript" data-lang="javascript">it(<span class="hljs-string">&#x27;Header&#x27;</span>, <span class="hljs-function">() =&gt;</span> {
  cy.visit(<span class="hljs-string">&#x27;/posts/this-is-sapper/en&#x27;</span>) <b class="conum">(1)</b>
  cy.get(<span class="hljs-string">&#x27;.subtitle .date&#x27;</span>).contains(<span class="hljs-string">&#x27;28/08/2020&#x27;</span>) <b class="conum">(2)</b>
});</code></pre>
</div>
</div>
<div class="colist arabic">
<ol>
<li>
<p>It navigates to the post absolute path</p>
</li>
<li>
<p>It checks that date is correct in subtitle</p>
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_typescript">Typescript</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Finally <a href="https://svelte.dev/blog/svelte-and-typescript">Svelte support for Typescript is completed</a> and after quite few some work, I&#8217;ve migrated <a href="https://github.com/carlosvin/carlosvin.github.io">this Blog supported by Sapper to Typescript also</a>. Feel free to use it as template or example, there are still some caveats, like clarify wether keep using eslint or svelte-check or both.</p>
</div>
</div>
</div>
<div id="footnotes">
<hr>
<div class="footnote" id="_footnotedef_1">
<a href="#_footnoteref_1">1</a>. Progressive Web Application
</div>
<div class="footnote" id="_footnotedef_2">
<a href="#_footnoteref_2">2</a>. End to end
</div>
</div>]]></content>
            <category term="Sapper"/>
    <category term="Svelte"/>
    <category term="JAMStack"/>
    <category term="PWA"/>
    <category term="Static Site Generator"/>
            <author><name>Carlos Martin Sanchez</name></author>
        </entry>
        </feed>