<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrea Tarquini on Medium]]></title>
        <description><![CDATA[Stories by Andrea Tarquini on Medium]]></description>
        <link>https://medium.com/@h4t0n?source=rss-c73afd1fcef7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*08sicxqH1h0AkpofC3PCBQ.jpeg</url>
            <title>Stories by Andrea Tarquini on Medium</title>
            <link>https://medium.com/@h4t0n?source=rss-c73afd1fcef7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:09:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@h4t0n/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[REST APIs: how to identify a a Resource? Use UUID]]></title>
            <link>https://medium.com/@h4t0n/rest-apis-how-to-identify-a-a-resource-use-uuid-23cf8be46d82?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23cf8be46d82</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 07:53:14 GMT</pubDate>
            <atom:updated>2021-07-09T07:53:14.391Z</atom:updated>
            <content:encoded><![CDATA[<p>Suggestions and techniques to properly identify a REST resource</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*7h8NJ4E62AZOPbaf" /></figure><p>The fundamental concept in any RESTful API is the <em>resource</em>. But one of the main issue is to uniquely identify it. So let’s talk about the most commonly used techniques and patterns, finally I’ll give my favorite choice.</p><p><strong>TLDR</strong></p><ul><li><em>REST API may expose resources by using UUID identifier (to avoid enumeration).</em></li><li><em>If the resources have well defined logical keys, it is better to use the UUID-V3 generated starting from the logical key.</em></li><li><em>If a resource doesn’t have a logical key, you can ue a random UUID. Check the UUID-V4</em></li><li><em>Backend should use and store its immutable primary keys for its logics (maybe numerical auto-generated IDs)</em></li></ul><p><strong><em>If you want the read the full post and all the explanation about the previous statements you can continue with my blog:</em></strong></p><p><a href="https://www.at7.it/en/blog/rest_uuid_resource">REST APIs: use UUID to identify a Resource</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23cf8be46d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini Starter: Model Driven REST APIs in minutes]]></title>
            <link>https://medium.com/javarevisited/gemini-starter-model-driven-rest-apis-in-minutes-9576a4988ff?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9576a4988ff</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 17:37:42 GMT</pubDate>
            <atom:updated>2019-09-18T01:55:25.744Z</atom:updated>
            <content:encoded><![CDATA[<p>How to setup CRUD REST APIs starting from Data Model and without generating code by using the Gemini Framework (a Spring/Java platform)</p><blockquote><strong>Gemini</strong> is a <strong>Model Driven</strong> <strong>REST</strong> <strong>framework</strong> to automatically generate CRUD APIs. You can take a look at the official repository <a href="https://github.com/gemini-projects/gemini">here</a>.</blockquote><p>We are going to define entities and code to obtain the following CRUD APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IHN2Fuqn71gKCs3KhMxhzA.gif" /></figure><p>This article explains what is included in the <strong>Gemini Starter repository</strong> and how to start with a full Gemini Project.</p><p><a href="https://github.com/gemini-projects/gemini-psql-starter">gemini-projects/gemini-psql-starter</a></p><h3>1. Gemini Custom Module</h3><p>Gemini is made of a series of modules (core, auth, gui and so on..). When you start a project you can also provide your custom Module that is the container for your entities, code and APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I24k08rXG9Y6Bxl2rw3Cjw.png" /></figure><p>The previous code shows how to start with a <strong>Gemini Module</strong>. Gemini has two <a href="https://javarevisited.blogspot.com/2019/02/difference-between-contextconfiguration-and-springapplicationConfiguration-annotations-in-spring-boot-testing.html">Spring Context</a>: the root that loads entities and handles core features and the api context that starts the Web Application. So we use <strong>MyCustomModule</strong> to scan core components and events, while <strong>MyCustomModuleAPI</strong> is used to scan API module (that may be useful if you want to register totally custom Spring web/rest endpoints). But usually you don’t need them to start with Gemini basic <a href="https://javarevisited.blogspot.com/2016/05/what-are-idempotent-and-safe-methods-of-HTTP-and-REST.html#axzz5j9AEsxuT">REST features</a>.</p><p>The important thing is that the core bean must override the <strong>Module</strong> Gemini Interface.</p><h3>2. Gemini DSL and Entities</h3><p>Since the name of the custom module is CUSTOM_MODULE we can put the schema definition in the resources file <strong><em>schemas/CUSTOM_MODULE.at</em></strong></p><p>In the repository we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NhrIfvwy-KKrZYul3BtFw.png" /></figure><p>Note that Employee has two entity references: to Company and Gender.</p><p><strong>Gender</strong> is a special entity that implements a Domain (a Gemini built in interface that provides two fields: <strong>code</strong> and <strong>description</strong>).</p><h3>3.Immutable Entities</h3><p>Immutable Entities are entities that cannot be modified, so it is not permitted to add a record (<a href="https://javarevisited.blogspot.com/2016/10/difference-between-put-and-post-in-restful-web-service.html">POST</a>) or modify an existing one (<a href="https://www.java67.com/2016/09/when-to-use-put-or-post-in-restful-web-services.html">PUT</a>). But how can Gemini initialize them? It is simple, just add all the record inside the module record initialization file <strong><em>records/CUSTOM_MODULE.atr</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q9WfnQp5B7tl5TqvToDKg.png" /></figure><p>In the previous file we have defined:</p><ul><li>the domain values for the <strong>Gender</strong> Entity</li><li>and we made Gender Immutable specifying that is a <strong>closed domain</strong>.</li></ul><blockquote>NB: In Gemini each Entity has a lot of meta data associated with itself. All these meta are stored in the Entity called Entity. Yes it is, and you can query all the meta data with Swagger using the Entity endpoint.</blockquote><p>So after Gemini complete its startup you have already the Gender filled with the value initialized in the file.</p><p>And if you take a look at the Gender APIs you can see that you cannot <a href="https://javarevisited.blogspot.com/2016/04/what-is-purpose-of-http-request-types-in-RESTful-web-service.html">POST / PUT / DELETE</a> . It is a <strong>closed immutable domain</strong>. Just GET Gender records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1_sTqZFisc3jtWrF5tezQ.png" /></figure><h3>4. Calculated field using Gemini Events</h3><p>CRUD APIs are useful but sometimes you want to add some logic or custom behavior like validation or calculated field or records that automatically create other records as a dependency.</p><p>For example, let make the <strong><em>fullName</em></strong> a calculated field by the concatenation of <strong><em>firstName</em></strong> and <strong><em>lastName</em></strong>. We are working on the <strong>EMPLOYEE</strong> entity and we register the event before the record is inserted (create) the first time and also each time the records changes (update).</p><p>It is simple. You need the only a combination of Gemini annotations and the function to extract the fullName.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX4SkG0OtIsaMRnEAR5N8Q.png" /></figure><p>As you can see, if we <strong>POST</strong> a <strong>new Entity</strong> the fullName is automatically calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViYIYRz121Q5oFgO9KrUVQ.gif" /></figure><h3>Finally</h3><p>In this article, I show you how to easily start with Gemini. But a lot of improvements will be developed, so I suggest to follow me and the main repository to be updated about each release.</p><p>Other <strong>Useful Resources for learning Java </strong>you may like<br> <a href="https://javarevisited.blogspot.com/2017/12/10-things-java-programmers-should-learn.html#axzz5atl0BngO">10 Things Java Programmer Should Learn in 2019</a><br> <a href="http://www.java67.com/2018/08/top-10-free-java-courses-for-beginners-experienced-developers.html">10 Free Courses to Learn Java from Scratch</a><br> <a href="https://medium.freecodecamp.org/must-read-books-to-learn-java-programming-327a3768ea2f">10 Books to Learn Java in Depth</a><br> <a href="http://www.java67.com/2018/04/10-tools-java-developers-should-learn.html">10 Tools Every Java Developer Should Know</a><br> <a href="http://javarevisited.blogspot.sg/2013/04/10-reasons-to-learn-java-programming.html">10 Reasons to Learn Java Programming languages</a><br> <a href="http://javarevisited.blogspot.sg/2018/01/10-frameworks-java-and-web-developers-should-learn.html">10 Frameworks Java and Web Developer should learn in 2019</a><br> <a href="http://javarevisited.blogspot.sg/2018/05/10-tips-to-become-better-java-developer.html">10 Tips to become a better Java Developer in 2019</a><br> <a href="http://javarevisited.blogspot.sg/2018/04/top-5-java-frameworks-to-learn-in-2018_27.html">Top 5 Java Frameworks to Learn in 2019</a><br> <a href="https://javarevisited.blogspot.sg/2018/01/10-unit-testing-and-integration-tools-for-java-programmers.html">10 Testing Libraries Every Java Developer Should Know</a></p><p><a href="https://medium.com/javarevisited/10-free-courses-to-learn-java-in-2019-22d1f33a3915">11 Best Free Java Programming Courses to learn in 2023</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9576a4988ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/gemini-starter-model-driven-rest-apis-in-minutes-9576a4988ff">Gemini Starter: Model Driven REST APIs in minutes</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit and Integration Tests against a real database with Continuous Integration]]></title>
            <link>https://medium.com/javarevisited/unit-and-integration-tests-against-a-real-database-with-continuous-integration-a62d1be664f3?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62d1be664f3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Wed, 28 Aug 2019 20:58:04 GMT</pubDate>
            <atom:updated>2019-09-03T12:32:24.430Z</atom:updated>
            <content:encoded><![CDATA[<p>A real project example using Github, Travis CI, Java/Spring, and PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*hlKX1OTBZ61ALy-ZA0I3Gg.png" /></figure><p>I’m going to explain a very simple free solution that I really use with my ambitious project called <strong>Gemini </strong>that automatically generate backend <a href="https://javarevisited.blogspot.com/2018/02/top-5-restful-web-services-with-spring-courses-for-experienced-java-programmers.html">REST API</a> from scratch starting from a simple DSL model.</p><p>In Gemini I made a lot of opinionated actions to translate the abstract type I defined to real SQL statements and queries, sometimes using some database-specific features (such as domains in PostgreSQL).</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><p>I developed a lot of integration tests that use a real PostgreSQL database and each time a macro feature should be tested I completely erase the integration test database starting from a fresh one. I know this process may take some times to complete, but It is not important. I rarely run all the codebase tests while I’m programming. I run only sections that may be affected and Travis and <a href="https://www.java67.com/2019/04/top-5-courses-to-learn-git-and-github.html">Github</a> will notice me if something goes wrong at all.</p><p>So let’s go in deep but I don’t want to explain how I start Spring context or erase the database here you could contact me or navigate through the <a href="https://github.com/h4t0n/gemini">code of Gemini </a>if you need help with <a href="https://javarevisited.blogspot.com/2018/06/top-6-spring-framework-online-courses-Java-programmers.html">Spring</a>/Gradle/<a href="https://medium.com/javarevisited/10-free-courses-to-learn-java-in-2019-22d1f33a3915">Java</a>.</p><p>Instead, I want to explain how to set up and use a combination of Github and Travis to start the integration tests. In this way, if you don’t use <a href="https://javarevisited.blogspot.com/2018/05/top-5-java-courses-for-beginners-to-learn-online.html">Java</a> or <a href="https://javarevisited.blogspot.com/2016/12/top-5-spring-and-hibernate-training-courses-java-jee-programmers.html">Spring </a>you can set up the continuous integration process replacing the language/commands with yours.</p><p>First of all you need to enable the Travis Webhook inside your Github repository settings (so you need a Travis account).</p><p>Then simply provide a suitable <strong>.travis.yml </strong>in the root of your project. The following is mine for Gemini.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49dde2df97a062d76539afa2f1bbebdf/href">https://medium.com/media/49dde2df97a062d76539afa2f1bbebdf/href</a></iframe><p>It is really easy:</p><ol><li>Define the language you are using. In my case java and openjdk 10</li><li>Then install the required tools for testing and the database inside the <em>before_install </em>section. I need <strong>gradle</strong> and <strong>postgreslq11</strong></li><li><em>before_script</em> is to initialize services. I create the database that I’m using in my integration tests to connect with</li><li><em>script</em> is the section that starts the test flow. For example i clean all the gradle context and I run a gradle task <em>jacocoRootReport </em>that compile all and start tests for each submodulo of my Spring project</li></ol><p>That’s all. Github and Travis will do the rest. Take a look for example at the result of a pull request Merge…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RYQTGwYkbhEDUKeguALYA.png" /></figure><p>Other <strong>Programming Articles</strong> you may like<br> <a href="https://hackernoon.com/the-2019-web-developer-roadmap-ab89ac3c380e">The 2019 Web Developer RoadMap</a><br><a href="https://javarevisited.blogspot.com/2018/05/10-reasons-to-learn-python-programming.html">10 Reasons to Learn Python in 2019</a><br><a href="http://www.java67.com/2017/12/10-programming-languages-to-learn-in.html">10 Programming languages You can Learn in 2019</a><br><a href="http://www.java67.com/2018/04/10-tools-java-developers-should-learn.html">10 Tools Every Java Developer Should Know</a><br><a href="http://javarevisited.blogspot.sg/2013/04/10-reasons-to-learn-java-programming.html">10 Reasons to Learn Java Programming languages</a><br><a href="http://javarevisited.blogspot.sg/2018/01/10-frameworks-java-and-web-developers-should-learn.html">10 Frameworks Java and Web Developer should learn in 2019</a><br><a href="http://javarevisited.blogspot.sg/2018/05/10-tips-to-become-better-java-developer.html">10 Tips to become a better Java Developer in 2019</a><br><a href="http://javarevisited.blogspot.sg/2018/04/top-5-java-frameworks-to-learn-in-2018_27.html">Top 5 Java Frameworks to Learn in 2019</a><br><a href="https://medium.freecodecamp.org/these-are-the-top-testing-tools-libraries-and-frameworks-for-java-developers-8c0e3f9bc11d">10 Testing Libraries Every Java Developer Should Know</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62d1be664f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/unit-and-integration-tests-against-a-real-database-with-continuous-integration-a62d1be664f3">Unit and Integration Tests against a real database with Continuous Integration</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GEMINI: a Java framework that makes CRUD REST API development faster]]></title>
            <link>https://medium.com/@h4t0n/gemini-dsl-f85e205f1419?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85e205f1419</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Thu, 16 May 2019 20:32:16 GMT</pubDate>
            <atom:updated>2019-08-24T20:33:55.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tq8J5tre4iq_GKghK5M8Hw.png" /></figure><p>Create micro services, backend and MVPs in minutes with no code. Gemini uses Java and Spring, ready for agile enterprise environments.</p><p>For those impatient you can find it on Github</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><h3>Why Gemini?</h3><p>Develop REST API is easy. There are a lot of framework written in any language, from cutting edge technologies like <em>node</em> to enterprise platforms like <em>Java</em>. We can use micro framework to define each REST route (express for example), or we can use opinionated and structured framework such as Spring or Loopback.</p><p>Each technology (or framework) has its own advantages. I think that for small project or personal experiments its better to use a <strong>micro-framework</strong> for its flexibility. Especially when the project changes a lot, or there are poor requirements and specifications. But there are also disadvantages, for example when the project starts to grow and we realize that we are writing the same thing again and again. In this scenario probably is better to use a structured (or enterprise) framework that forces you to do things according to its philosophy, but all is homogeneous and maintainable.</p><p><strong>Having said that let’s start to think to another approach.. Gemini wants to merge the two words to have a well defined structured framework but flexible at the same time. Impossible ? Probably… but let’s try!</strong></p><p>In this article instead we start with the definition of the<strong> Gemini DSL</strong>, the <strong>schema</strong> of the <strong>REST APIs</strong> and <strong>Entities</strong>.</p><h3>Gemini DSL</h3><p>I’ve worked with a lot of framework that allow you to define the data model like <em>Spring Data Rest or Loopback. </em>They are powerful but when entities increase their complexity they become less manageable and you always need to adjust something (especially with relations or complex types).</p><p>The GOAL here is to find a way to define entities (REST resources) thinking about abstract data types, defining an entity as a real one data type. Before going into detail take a look at the following example where we define API for book order (very simplified data model).</p><pre># Entity Abstract Type Definition - Book Orders</pre><pre>INTERFACE Domain {<br>    TEXT          name *<br>    TEXT          description<br>}<br><br># Entity Abstract Type Definition - Book Orders<br><br>ENTITY CATEGORY  IMPLEMENTS Domain<br>ENTITY COUNTRY   IMPLEMENTS Domain<br><br>ENTITY Book {<br>    TEXT        isbn    *<br>    TEXT        name<br>    AUTHOR      author<br>    DECIMAL     price<br>    [TEXT]      tags<br>}<br><br>ENTITY Author {<br>    TEXT    name *<br>    COUNTRY country<br>    DATE    birthdate<br>}<br><br>ENTITY BookOrder {<br>    Book        book<br>    QUANTITY    quantity<br>    DECIMAL     finalPrice<br>    DATETIME    dateTime<br>}</pre><p>The DSL is very simple, no nesting or complex definition. It is linear and expressive, I love it. But let’s explain it better:</p><ul><li>every ENTITY is treated as a real <strong>Data Type </strong>(by its name)</li><li>entities are defined always with a<strong> single level of nesting </strong>(it looks like a relational table with special types)</li><li>gemini provides common primitive types (date, time, datetime, numbers and so on)</li><li>relations are expressed as simple fields with a reference to the entity data type. For example AUTHOR as a single reference, or [CATEGORY] as an array of references</li><li>each Entity can have a logical key (expressed with the symbol <strong>*</strong> ) that uniquely identify a Record. The logical key can be made of multiple fields</li><li>To avoid to replicate the definition of fields for common Entities it is possible to define interfaces. For example CATEGORY and COUNTRY implements the DOMAIN interface.</li></ul><p>It looks like so simple I know.. but It is all that we need… This simple entity definition is enough to completely express a REST resource (with its fields).</p><h4>Resources and Routes</h4><p>It’s clear that with the simple DSL defined earlier we need to have strong assumptions to auto-generate resources routes. But if for example we imagine to don’t have any other meta-data, we could have the following routes</p><pre># for each resource -&gt; POST (insert) GET (list)</pre><pre>/api/category<br>/api/country<br>/api/book<br>/api/author<br>/api/bookorder</pre><pre># for each resource -&gt; PUT GET DELETE<br># where lk is the logical key logical key)</pre><pre>/api/category/:lk<br>/api/country/:lk<br>/api/book/:lk<br>/api/author/:lk<br>/api/bookorder/:lk</pre><p>A request could be the following</p><pre># GET /api/book/978-0553808049</pre><pre>{  <br>   <strong>&quot;author&quot;</strong>:&quot;George R. R. Martin&quot;,<br>   <strong>&quot;isbn&quot;</strong>:&quot;978-0553808049&quot;,<br>   <strong>&quot;name&quot;</strong>:&quot;A Game of Thrones&quot;,<br>   <strong>&quot;price&quot;</strong>:37.4,<br>   <strong>&quot;tags&quot;</strong>:[]<br>}</pre><p>where:</p><ul><li>for references fields we use logical keys (or the full record)</li><li>we don’t have defined how to handle data in the Backend. We know resources, primitive types and custom types with theri logical key in the JSON notation</li><li>it is so clear that we need to define an opinionated way to handle complex data types, for example for dates or times we could use some standard format</li></ul><p>If you are curious to follow Gemini progress.. this is the repository… please give a star if you like</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><p>It is currently in development and I am working on it constantly</p><p>Let me know what you think about on twitter or Linkedin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85e205f1419" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini: un framework la generazione automatica di API REST]]></title>
            <link>https://medium.com/@h4t0n/gemini-dsl-4dcc6c2bade0?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dcc6c2bade0</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Thu, 09 May 2019 21:24:43 GMT</pubDate>
            <atom:updated>2019-05-17T21:46:30.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XJYCFeKby2uTyk4tXw3CQ.jpeg" /></figure><h3>Gemini: un framework per la generazione automatica di API REST</h3><p>Sviluppare API di tipo REST (o quasi) oramai è diventato piuttosto semplice, esistono una moltitudine di framework per ogni tipo di linguaggio (dai più moderni tipo <em>node</em> ai più maturi come <em>Java</em>). Possiamo utilizzare sia microframework per definire la logica ogni singola rotta (tipo express), che utilizzare dei framework più strutturati e che riescono ad astrarre anche nella memorizzazione dei dati (come Spring o Loopback).</p><p>Ogni framework (e filosofia) ha i suoi vantaggi e svantaggi. Per applicazioni personali o piccoli progetti sicuramente andare di <strong>micro-framework</strong> è una scelta sicuramente sensata. Il vantaggio si ha soprattutto quando il progetto muta in continuazionei: di solito quando i requisiti non sono definiti o si sta sperimentando. Lo svantaggio si ha quando le entità iniziano ad aumentare e ci si accorge che si sta riscrivendo sempre la stessa cosa (con qualche variazione). Utilizzare un <strong>framework strutturato</strong> è sicuramente più lento/complesso (soprattutto all’inizio se non lo si conosce), bisogna fare le cose come dice il framework e non è semplicissimo deviare dalla filosofia sottostante. Tuttavia per progetti enterprise e di una certa entità avere una filosofia e processo di sviluppo è fondamentale. Creare un applicazione enterprise in express vi assicuro che richiede persone di qualità notevole e ben organizzate affinché il tutto non degeneri in poco tempo.</p><h4>Detto ciò con Gemini proviamo ad unire i due mondi, per creare un framework strutturato, ma flessibile allo stesso tempo… Impossibile? Forse no…</h4><p>Se siete impazienti potete trovare il repository con le primissime versioni qui</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><p>In questo articolo invece partiamo con il definire il <strong>DSL </strong>di<strong> Gemini , </strong>ovvero lo <strong>schema</strong> delle <strong>entità/api REST</strong>.</p><h3>Un idea di DSL</h3><p>Ho lavorato con diversi framework che consentono di definire direttamente il modello dati (come <em>Spring Data Rest</em>) o magari estrapolare il modello dati direttamente dalle istanze (o dal JSON) come LoopBack. Sono potenti non c’è che dire ma quando le risorse aumentano di complessità (e annidamento) si sente la pesantezza e bisogna sempre mettere le mani qua e la (soprattutto con le relazioni).</p><p>L’obiettivo è quello di definire le entità (risorse REST) ragionando in modo astratto, definendo ogni entità come se fosse un vero e proprio tipo di dato. Prima di andare nel dettaglio ecco un esempio molto semplificato per le API che esprimono l’acquisto di libri.</p><pre># Entity Abstract Type Definition - Book Orders</pre><pre>INTERFACE Domain {<br>    TEXT          name *<br>    TEXT          description<br>}<br><br># Entity Abstract Type Definition - Book Orders<br><br>ENTITY CATEGORY  IMPLEMENTS Domain<br>ENTITY COUNTRY   IMPLEMENTS Domain<br><br>ENTITY Book {<br>    TEXT        isbn    *<br>    TEXT        name<br>    AUTHOR      author<br>    DECIMAL     price<br>    [TEXT]      tags<br>}<br><br>ENTITY Author {<br>    TEXT    name *<br>    COUNTRY country<br>    DATE    birthdate<br>}<br><br>ENTITY BookOrder {<br>    Book        book<br>    QUANTITY    quantity<br>    DECIMAL     finalPrice<br>    DATETIME    dateTime<br>}</pre><p>Non c’è bisogno di spiegare il senso, la definizione è veramente molto intuitiva. Ma più nel dettaglio</p><ul><li>ogni entità (definita come ENTITY) è trattata come un vero e proprio <strong>tipo </strong>(corrispondente al nome dell’ entità)</li><li>le entità sono definite sempre e solo con un <strong>unico livello di annidazione</strong> sui campi (in sostanza come se fossero campi di una tabella di tipo relazionale)</li><li>Esistono i più comuni tipi primitivi (date, time, datetime, number, double, text e così via) e array su questi tipi.</li><li>Le relazioni vengono espresse con campi di tipo riferimento ad entità. Ad esempio AUTHOR come riferimento singolo e [CATEGORY] come array di riferimenti nell’ entità BOOK</li><li>ogni entità può avere una chiave logica che identifica univocamente un record dell’ entità (espressa con il simbolo <strong>* </strong>). Le entità possono avere una chiave logica multipla.</li><li>Per evitare di replicare la definizione dei campi delle entità simili è possibile definire delle interfacce che le entità possono implementare. Ad esempio CATEGORY e COUNTRY le possiamo trattare come se fossero dei domini, dove ci serve il nome come chiave (e una descrizione).</li></ul><p>Sembra troppo semplice, ma vi assicuro che già così il DSL è sufficiente per esprimere al completo una risorsa REST (entità) e anche il formato corpo delle richieste/risposte JSON.</p><h4>Risorse e rotte</h4><p>E’ chiaro che con il semplice schema sopra debbano valere delle forti assunzioni per l’autogenerazione delle rotte e delle risorse. Ma supponendo di non avere altri metadati potremmo avere le seguenti risorse</p><pre># per ogni risorsa -&gt; POST (inserimento) GET (lista)</pre><pre>/api/category<br>/api/country<br>/api/book<br>/api/author<br>/api/bookorder</pre><pre># per ogni risorsa sul singolo id -&gt; PUT GET DELETE<br># dove lk sta per chiave logica (logical key)</pre><pre>/api/category/:lk<br>/api/country/:lk<br>/api/book/:lk<br>/api/author/:lk<br>/api/bookorder/:lk</pre><p>Un esempio di richiesta potrebbe essere la seguente</p><pre># GET /api/book/978-0553808049</pre><pre>{  <br>   <strong>&quot;author&quot;</strong>:&quot;George R. R. Martin&quot;,<br>   <strong>&quot;isbn&quot;</strong>:&quot;978-0553808049&quot;,<br>   <strong>&quot;name&quot;</strong>:&quot;A Game of Thrones&quot;,<br>   <strong>&quot;price&quot;</strong>:37.4,<br>   <strong>&quot;tags&quot;</strong>:[]<br>}</pre><p>dove:</p><ul><li>per i campi riferimento possiamo utilizzare le chiavi logiche o l’intero oggetto (decidibile magari con un header custom)</li><li>non abbiamo assolutamente fatto riferimento a come i dati vengono poi trattati nel backend. Esistono solamente chiavi logiche e campi primitivi in notazione JSON.</li><li>è chiaro che andrà definito un formalismo (e un interfaccia) per i tipi di dato più particolari, come le date o gli istanti temporali.</li></ul><p>Siete curiosi in merito agli avanzamenti ? Ecco il repository…</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><p>Fatemi sapere cosa ne pensate!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dcc6c2bade0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parser Top Down: come scrivere un semplice linguaggio (DSL) in Java]]></title>
            <link>https://medium.com/@h4t0n/gemini-top-down-parser-db0298ec1def?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/db0298ec1def</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[language]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Thu, 09 May 2019 21:12:49 GMT</pubDate>
            <atom:updated>2019-05-17T17:09:48.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWVBhqNjs_kdaCjlmBL-Gw.png" /></figure><blockquote>Dato che sto sviluppando <a href="https://github.com/h4t0n/gemini">Gemini</a>: un framework (basato su Spring Boot) per la creazione automatica di API REST, volevo condividere con voi qualche tecnica per definire un semplice parser a discesa ricorsiva. In questo caso il parser viene effettivamente usato per interpretare il DSL che definisce le entità ed API di <a href="https://github.com/h4t0n/gemini">Gemini</a>.</blockquote><p><a href="https://medium.com/@h4t0n/gemini-dsl-4dcc6c2bade0">Gemini: un framework la generazione automatica di API REST</a></p><p>Non voglio soffermarmi sulla teoria dei linguaggi o delle grammatiche, ci sarebbe troppo da dire. Lo scopo di questo articolo è mostrare quanto è semplice scrivere ed interpretare un semplice DSL (Domain Specific Language). Con semplice intendo un linguaggio definito da una grammatica di tipo LL(1), ovvero (in parole molto povere) una grammatica che necessità di un unico simbolo per capire a che punto si trova nel parsing. Il parser può essere quindi implementato come un vero e proprio programma, dove di solito i metodi (procedure) ricorsive sono ricavate direttamente dalle regole grammaticali.</p><p>Iniziamo…</p><p>Ecco un esempio scritto con il DSL utilizzato da <a href="https://github.com/h4t0n/gemini"><em>Gemini</em></a>:</p><pre>INTERFACE Domain {<br>    TEXT          name *<br>    TEXT          description<br>}<br><br># Entity Abstract Type Definition - Book Orders<br><br>ENTITY CATEGORY  IMPLEMENTS Domain<br>ENTITY COUNTRY   IMPLEMENTS Domain<br><br>ENTITY Book {<br>    TEXT        isbn    *<br>    TEXT        name<br>    AUTHOR      author<br>    DECIMAL     price<br>    [TEXT]      tags<br>}<br><br>ENTITY Author {<br>    TEXT    name *<br>    COUNTRY country<br>    DATE    birthdate<br>}<br><br>ENTITY BookOrder {<br>    Book        book<br>    QUANTITY    quantity<br>    DECIMAL     finalPrice<br>    DATETIME    dateTime<br>}</pre><h3>1. Tokenizer</h3><p>La prima cosa da fare è leggere in modo corretto il DSL, ovvero i simboli terminali che lo compongono.</p><p>Per fare questo possiamo usare un instanza di StreamTokenizer specificando quali sono i caratteri che compongono il linguaggio, i caratteri da trattare come spazi e i commenti (in stile C, C++ e anche inline).</p><p>Ad esempio il tokenizer seguente è quello realmente utilizzato da Gemini. In poche parole ignoriamo tutto quello racchiuso tra ommenti inline <em>//</em>, <em>#</em> e multi line <em>/* */. </em>L’EOL (end of line) viene trattato come un normale carattere di spaziatura, mentre tutto il resto da carattere <strong>!</strong> a <strong>~ </strong>va a comporre i token. Ad ogni nextToken() si avranno esclusivamente i simboli terminali.</p><pre>input = new StreamTokenizer(r);<br>input.resetSyntax();<br>input.wordChars(&#39;!&#39;, &#39;~&#39;);<br>input.ordinaryChar(&#39;/&#39;);<br>input.whitespaceChars(&#39;\u0000&#39;, &#39; &#39;);<br>input.slashSlashComments(true);<br>input.slashStarComments(true);<br>input.eolIsSignificant(false);<br>input.commentChar(&#39;#&#39;);</pre><h3>2. Lexer</h3><p>Spesso il Lexer e il Tokenizer coincidono, di fatto il loro compito è produrre i token del linguaggio. Vale la pena fare una distinzione quando il Lexer aggiunge delle informazioni extra ai token. Nel caso di Gemini il <em>Lexer</em> di fatto include il <em>Tokenizer</em>, e arricchisce i token prodotti con un pò di zucchero sintattico per permettere un utilizzo più comodo nel Parser.</p><p>Ecco il codice di una delle primissime versioni di Gemini.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/403d06114ac0dd44b43b0d13e43ab6eb/href">https://medium.com/media/403d06114ac0dd44b43b0d13e43ab6eb/href</a></iframe><p>In poche parole il Lexer incapsula il Tokenizer definendo degli enumerati per un insieme di simboli terminali prestabiliti.</p><h3>3. Parser</h3><p>Il parser top down ora è semplice da scrivere. Si scorrono i token prodotti dal Lexer e in base al valore del token corrente si riesce a capire come proseguire.</p><p><em>Ricordo che non ho voluto fare precisazioni o approfondimenti su grammatiche, linguaggi ecc… ma per convenzione e semplicità di solito si fa corrispondere una chiamata di procedura ad ogni simbolo non terminale della grammatica che definisce il linguaggio e si procede di conseguenza…</em></p><p>Il DSL si Gemini è veramente molto semplice, e sono sicuro che il codice seguente vi risulterà rapido da leggere e capire. Nel parsing vengono create le strutture dati che servono successivamente al framework per le sue azioni (sotto forma di Builder).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/973e6d993230140ff71c75f44071dbc0/href">https://medium.com/media/973e6d993230140ff71c75f44071dbc0/href</a></iframe><p>Questo è tutto… se dovete definire un piccolo linguaggio senza troppe preteste un parser a discesa ricorsiva è sicuramente la scelta giusta. Non sono necessarie librerie particolari e di fatto avete una libertà assoluta sulle strategie di implementazione del Lexer del Parser (basta un pò di buon senso).</p><p>Il codice di esempio dell’articolo viene utilizzato in <strong><em>Gemini</em></strong> per il caricamento delle entità che compongono l’applicativo.</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><p>Fatemi sapere cosa ne pensate…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db0298ec1def" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API: UUID-V3 is the right way]]></title>
            <link>https://medium.com/@h4t0n/rest-api-uuid-v3-is-the-right-way-3ca0695610dc?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca0695610dc</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Mon, 08 Apr 2019 21:25:45 GMT</pubDate>
            <atom:updated>2019-07-17T20:53:12.765Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>How to properly identify a Resource? Primary Keys? Logical Keys? UUID?</blockquote><blockquote>Let’s use them all!!!!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R99tA3ehTPO9BKvjYaTCuA.png" /></figure><p>The fundamental concept in any RESTful API is the <strong><em>resource</em></strong>. But one of the main issue is to uniquely identify it.</p><p>So let’s talk about the most commonly used techniques (and patter) and finally my favorite choice</p><blockquote><strong>TLDR<br>1. </strong>REST API should expose named UUID-V3 identifier. UUID should be generated from the resource logical key<br><strong>2.</strong> BACKEND should use/store numeric (ID) primary keys for its logics</blockquote><p>I use the UUID-V3 in my Gemini project</p><p><a href="https://github.com/h4t0n/gemini">h4t0n/gemini</a></p><h3>1. Database Auto Generated Primary Keys</h3><p>This is one of the most used type of identifier. Especially when you need to store the resource one-to-one inside a common database. It is the simplest way to identify the resource since DB engine guarantees uniqueness. You may find this kind of resources in legacy (monolithic) systems that have been exposed to the other services by using modern REST philosophy. For example an old app that need a fresh UI or some integrations.</p><p>So usually the resource is like</p><pre>https://music.app/song/1</pre><p>Usually resources (<em>song</em>) are one to one with stored tables, and in the previous example we are identifying the song with id 1.</p><p><em>Advantages</em></p><ul><li>Simple, you can autogenerate it using your DB</li><li>ID is mandatory and not editable. It doesn’t change.. and really.. it is a big tip</li></ul><p><em>Drawbacks</em></p><ul><li>Not suitable for distributed system</li><li>Very hard to synchronize environments… especially legacy environments… You always have a production or test environment that are not synchronized and overlaps are a very big problem (especially for your customer)</li><li>Security should always be taken into account. Enumeration of resources is easy… you only need to increment the ID counter…</li></ul><h3>2. Logical Key(s)</h3><p>Another used way is to identify the resource with a logical key. Usually it is used when resources can be treated as a domain. Imagine the day of a week, or a country name. So good resources can be</p><pre>https://my.app/weekday/monday<br>httos://my.app/country/italy</pre><p><em>Advantages</em></p><ul><li>Easily interpretable for users and for API developers. It is easy to understand the resource content by its identifier.</li><li>Easy to synchronize data across environments… No overlaps, customers are so happy of that…</li><li>If you use the logical key as a route (webapp for example) it is a lot expressive</li></ul><p><em>Drawbacks</em></p><ul><li>Need to guarantee uniqueness. Backend should be more sophisticated.</li><li>Not suitable for relational data and if you want to use it as a PK (and FK) you are mad.</li><li>Usually the logical key can be modified. Imagine if your resource is a name of company. Company name changes… It is not so so common but it could be possibile.. And when you change the logical key… you need to change all its references (FK)… <em>Blood…</em></li><li>When the resource can be identified only with a set of field… you need to craft the logical key (concatenation? another pattern?…)</li></ul><p><strong><em>So in the real life usually the logical key is exposed to the world but the app inside use a numeric primary key.</em></strong></p><h3><strong>3. The right way: expose UUID-V3 — store PK</strong></h3><p>This is the best choice I found to develop my APIs.</p><ol><li>Basically I use autogenerated serial primary keys (from DB) inside the backend. So references (FK) always use a numeric PK.</li><li>Then I decorate resources with a logical key. For example the <em>code</em> or the <em>name. </em>For domains the logical key is simple. For complex resources they may be a concatenation of fields.</li><li>All the exposed resources have a UUID-V3 starting from the logical key.</li></ol><p>UUID-V3 are Universally unique identifier generated from an MD5 hash of a namespace and name. Usually the namespace is the my appname (or endpoint) and the name is the entity + the logical key.</p><p>For example imagine that your app identifies the user by its username. You can expose your users both by logical key (the username) and the UUID-V3. For example:</p><pre>https://my.app/users/andrea<br>https://my.app/users/327cbd0f-3286–3a56-afd3-a984ed6de334</pre><pre>// NB. the UUID is always the same for the name andrea. I used the<br>// string andrea (as namespace + name)<br>// <a href="https://uuidonline.com/?version=3&amp;namespace=andrea">https://uuidonline.com/?version=3&amp;namespace=andrea</a></pre><p><em>Advantages</em></p><ul><li>Backend use PK serial numeric identifiers. I use the power of relational databases and foreign keys</li><li>UUID is the best choice for synchronization, especially when you have resources with composite logical keys… and you application should handle multiple fields logical keys properly and it is not so easy..</li><li>You can expose both UUID for complex resources and logical key for simple resources like a domain. You can switch to UUID/logical key accordingly to your needs. For example a GUI route can use the logical key</li></ul><p><em>Drowbacks</em></p><ul><li>Backend should be implemented well to understand and expose both logical key and UUID. Usually I expose also the logical key if the it is composed of a single field and I always expose UUID-V3</li><li>When you update the logical key (if permitted) you need also to update the UUID. But since the primary key of the app is always the same (auotogenerated by DB) this operation is not so expensive</li></ul><p><strong><em>So… What do you think about?</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca0695610dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Error Handling Pattern (with Spring)]]></title>
            <link>https://medium.com/@h4t0n/java-error-handling-pattern-f059d20ca5dc?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f059d20ca5dc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 21:09:04 GMT</pubDate>
            <atom:updated>2018-12-06T21:09:04.567Z</atom:updated>
            <content:encoded><![CDATA[<p>A Simple way to organize Errors and Exceptions and their related messages and logs: great for Backend, APIs &amp; FrontEnd.</p><p>One of the big problem you have when you are devoloping complex (and enterprise) applications is to correctly handle an manage a huge amount of errors and exceptions. Since I’m developing a simple API framework with Spring (for personal and learning purposes) I want to share some strategies and patterns I’m experimenting to better handle my Exceptions and their related informations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFmnN5zreJPoCVzIAUwaVw.png" /></figure><p>Usually developers categorize errors accordingly to their severity and type, and some times if you have an API or a User Interface you want to convert or manage the error differently: imagine logs, audit, API results or notifications for users (and developers). So, in the following article I explain the strategy I’m using to define and use Exceptions and why.</p><p>First of all lets define GeminiException (yes my framework is called Gemini). It is the SuperClass of all my checked exceptions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87366ccf629224243fe58dd44950be69/href">https://medium.com/media/87366ccf629224243fe58dd44950be69/href</a></iframe><p>The only interesting thing here is the <strong>erroCodeName</strong>. I’m assuming that all my Exception must have the error code… Why? Because I want to use it to uniquely identify all my Exceptions (we can see later how!!).</p><p><em>NB: You can do the same thing for RuntimeException and Error of course.</em></p><p>Ok.. Now let’s use it… I implemented in my API framework a dedicated EntityManager that handles all Entity operations.. so you can imagine all the Exception I need to define and manage…</p><p>Let’s see for example the EntityRecordException <br>It is a subclass of <strong>GeminiException</strong>, and of course it can have its related fields to better identify itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b69b4e670e7b3bfb4957df797e04b0b3/href">https://medium.com/media/b69b4e670e7b3bfb4957df797e04b0b3/href</a></iframe><p>For example in the <strong>EntityRecordException</strong> I need to know the Entity that raise the problem or the <em>logical key</em> FieldValue (maybe a set) of the EntityRecord. I decided to not subclass again the EntityRecordException instead I’m using the GeminiException errorCode to uniquely identify it and to understand what triggered the Exception.</p><p>In the constructor you can see that I’m using the Code enum that is inner in EntityRecordException. Pay attention to it because later in the article you’ll realize that I use enum Code in all of my GeminiException and with some Spring reflections feature I am sure about their uniqueness.</p><p>Static methods defined in EntityRecordException are useful in the code of my Entity Manager to avoid to directly use the constructor. For example I can use throw EntityRecordException.LK_NOTFOUND(entity,logicalKey); if I don’t find the logical key. It is so simple and easy to read and understand.</p><p>OK, now It’s time to use some Spring utilities to define the <strong>ErrorService</strong>, a bean that guarnatees exception codes uniqueness.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37dbbaf4f2cf1d5781567f8d82291f5/href">https://medium.com/media/a37dbbaf4f2cf1d5781567f8d82291f5/href</a></iframe><p>The <strong>ErrorService</strong> is executed when the Application starts. It uses some Spring features to load all GeminiExceptions from the gemini package trying to find the <strong>Code</strong> enumerator (for each exception class). Then it registers all the errorCodes to a inner list checking if there are some duplicates. Note that I used only the Enum name, but you can also categorize the error codes by package or by some other strategies (using a Map for example). My code is very simple for now, but I’m sure that I’ll touch the ErrorService a lot during the Gemini Development and the Exception uniqueness key may change.</p><p>For now my goal is to have a <strong>pattern</strong> to <strong>define</strong> all the <strong>Exceptions</strong>, and to separate the definition from the usage. Indeed all my subclass of <em>GeminiException</em> follow the same structure of <em>EntityRecordException</em>: they have a <em>Code</em> enumerator and they have static methods to better create the exception instance. Then with the ErrorService I am sure that I can uniquely identify them later in the project development.</p><h4>So, summing up:</h4><ul><li>I defined the <strong>SuperClass</strong> of my Exceptions: it is called GeminiException and has a <strong>code field</strong> to<strong> uniquely identify</strong> the Exception instance</li><li>I defined a <strong>simple</strong> and <strong>clean</strong> definition <strong>pattern</strong> that all my subclass of GeminiException should follow</li><li>I defined a Service to <strong>check</strong> the Exceptions</li></ul><h4>What you can do following my pattern? Some examples:</h4><ul><li>Throw the SuperClass (GeminiException) in your code instead of the single specific Exception if unwanted. You can also wrap common Exceptions (IOException for example) to your superclass exception (GeminiException). Your interfaces will be clean and solid.</li><li>Map each Exception Code to a set of messages: one for development log, one as user message, one for REST response message and so on.. Note that each exception has also a set of related fields that you can use in your messages…</li><li>You can add each feature you want to the Exception Code. For Example a Translation Service, or an Adapter.</li><li>If you use REST feature of Spring you can Map your Exception (and its realated translation/messages services) to an Error Handler: both with its superclass (default) and the subclass. For example I use a lot the pattern with the ControllerAdvice Spring feature.</li></ul><p>I hope my article can help you to better write clean and powerfull code. I think that my approach is very simple, but it gives you all the building block to improve it during the development. If used well you don’t need to change all the interfaces or the business logic of your code, instead you can incrementally extend the pattern writing for example support services as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f059d20ca5dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Display Instagram Posts on a Map]]></title>
            <link>https://medium.com/@h4t0n/show-instagram-post-on-googlemaps-cb30e34f9384?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb30e34f9384</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[jupyter]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 21:26:11 GMT</pubDate>
            <atom:updated>2018-03-03T22:26:54.418Z</atom:updated>
            <content:encoded><![CDATA[<p>Instagram GeoLocation analysis with Jupyter (Python) and Google Maps</p><p>This is a very simple Jupyter Notebook to extract and visualize some useful information from Instagram POST and display them on a Map (with Google Maps).</p><h4>Get data</h4><p>First of all you need to obtain datas about your posts. Since I want to analyze some posts about a single hashtag, I developed a simple scraper that downloads post from the instagram public API.</p><p>You can find also an article about Instagram data scraping, to see how I obtained my data.</p><p><a href="https://medium.com/@h4t0n/instagram-data-scraping-550c5f2fb6f1">Instagram Data Scraping from Public API</a></p><p>Once you have data you can play with the following tools to manipulate information as you need.</p><h4>Tools</h4><ul><li>Jupyter</li><li>Python</li><li>Pandas</li><li>Google Maps (gmpas Jupyter package)</li></ul><h4>My GOAL</h4><p>In my experiments I wanted to show some posts in Google Maps by theri location.</p><p>So this is the final result: an <strong>heatmap</strong> for about 4000 posts, and a map for the last day post with <strong>markers</strong> and <strong>interactive data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*QY-xKmPT0T0BHV5a7U0dsA.png" /><figcaption>Heat Map for analyzed hashtag</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*6LLQu7vFC-SWfVbLMzX-yQ.png" /><figcaption>Markers for the last day post</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*hICWtGQZul-cI2Ez-dCZ0g.png" /><figcaption>Each Market is interactive and shows the photo</figcaption></figure><p>This is the full code for <strong>jupyter</strong> notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3d4f319207c7188fbd5fbe5a8f5451/href">https://medium.com/media/8f3d4f319207c7188fbd5fbe5a8f5451/href</a></iframe><p>You can fine the repository with some other information here.</p><p><a href="https://github.com/h4t0n/instagram-data-analysis">h4t0n/instagram-data-analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb30e34f9384" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instagram Data Scraping from Public API]]></title>
            <link>https://medium.com/@h4t0n/instagram-data-scraping-550c5f2fb6f1?source=rss-c73afd1fcef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/550c5f2fb6f1</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[scrapy]]></category>
            <dc:creator><![CDATA[Andrea Tarquini]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 20:01:01 GMT</pubDate>
            <atom:updated>2018-04-18T21:14:57.124Z</atom:updated>
            <content:encoded><![CDATA[<p>With Python and Scrapy: NO access-token or Authentication required</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*r9yzOvtdArH1akAg3kowBA.png" /></figure><blockquote><strong>NB: Instagram changes its public APIs and probably my scripts need some reviews.. or no longer works…</strong></blockquote><h3>The endpoint</h3><p>Scrap data from Instagram is easy if you know the right endpoint.</p><p>For example take a look at the #italy hashtag: <a href="https://www.instagram.com/explore/tags/italy/">https://www.instagram.com/explore/tags/italy/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bns0CfvvNunzxN0uVjGjNA.png" /></figure><p>Try now to append the <strong>query string ?__a=1 </strong>and see what happens: <a href="https://www.instagram.com/explore/tags/italy/">https://www.instagram.com/explore/tags/italy</a>/?__a=1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G7G_2yhhYKnMDdjmQMPlA.png" /></figure><p><strong>YES.. </strong>It is a JSON with a lot of information that shows the first 30/40 post for the hashtag #italy.</p><p>And to <strong>go to the next posts</strong>?</p><p>You can use the end cursor that you can find from <strong>graphql</strong> -&gt; <strong>hashtag</strong> -&gt; <strong>edge_hashtag_to_media</strong> -&gt;<strong>page_info</strong> -&gt; <strong>end_cursor</strong></p><p>Making the following reques <a href="https://www.instagram.com/explore/tags/italy/">https://www.instagram.com/explore/tags/italy</a>/?__a=1&amp;<strong>max_id=</strong><em>endcursor</em></p><p>In my tests I’ve been able to scrap about 13000 posts from an hashtag, so probably you cannot go to the first post at all (if the number or post are hight)</p><p><strong>NB:</strong> The tricks <strong>__a=1</strong> and <strong>max_id=</strong><em>endcursor </em>are available also for the other endpoint (post, users and so on)</p><h3>The Scraper</h3><p>To automate the scraping I used <a href="https://scrapy.org/">Scrapy</a>, a powerful and fast crawler.</p><p>You can take a look at my github repository <a href="https://github.com/h4t0n/instagram-scraper">Insagram Scraper</a>.</p><p><a href="https://github.com/h4t0n/instagram-scraper">h4t0n/instagram-scraper</a></p><p>Feel free to fork and change its behaviour to fit your needs.</p><p>I haven’t scraped all the information, only some useful fr my purposes: caption, locations (latitude and longitude), owner, display_url and so on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550c5f2fb6f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>