<?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 Daniel Padua Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Daniel Padua Ferreira on Medium]]></description>
        <link>https://medium.com/@danielpadua?source=rss-c291e71ea152------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_GDlgv5xlt2Py85F-O4PbA.jpeg</url>
            <title>Stories by Daniel Padua Ferreira on Medium</title>
            <link>https://medium.com/@danielpadua?source=rss-c291e71ea152------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 00:59:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielpadua/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[Autorização de Infraestrutura como Código]]></title>
            <link>https://medium.com/danielpadua/autoriza%C3%A7%C3%A3o-de-infraestrutura-como-c%C3%B3digo-a342045468bf?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/a342045468bf</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[segurança-da-informação]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[open-policy-agent]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 20:06:00 GMT</pubDate>
            <atom:updated>2023-10-06T14:41:45.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioLaHso4xShDsnJXXeIQIQ.png" /></figure><blockquote>Entenda os problemas de não possuir um processo de autorização em pipelines de infraestrutra como código e veja uma solução com um bom custo-benefício para mitigar esses problemas</blockquote><h3>Introdução​</h3><p>Autorização é sempre um tema delicado, pois envolve a segurança de um software ou processo. Porém, quando falamos de infraestrutura como código, ter guardrails se torna ainda mais importante, pois é possível que um desenvolvedor cometa um erro e acabe expondo dados sensíveis ou até mesmo derrubando um ambiente inteiro.</p><p>Pensando em um ambiente corporativo dinâmico, o processo de gerenciamento de software moderno inclui a execução de pipelines de CI/CD para implantação de alterações, tanto de infraestrutura quanto de aplicação. Essas alterações podem ser feitas por desenvolvedores, engenheiros DevOps ou até mesmo por um usuário mal-intencionado.</p><p>Com o objetivo de mitigar esses riscos, é possível utilizar ferramentas de autorização que podem ser usadas para validar infraestrutura como código, como por exemplo o <a href="https://www.openpolicyagent.org/">Open Policy Agent</a>. O OPA é um motor de políticas open source, leve e de propósito geral, capaz de ser utilizado em diversos cenários como: autorização de APIs e microserviços, admission controller no kubernetes, autorização de tópicos e filas e também autorização de infraestrutura como código.</p><h3>O problema<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#o-problema">​</a></h3><p>Digamos que você possua em sua empresa um processo de build e deploy, automatizado e bem definido. Para fins demonstrativos, vamos supor que sua pipeline de CI/CD execute usando o <a href="https://docs.github.com/en/actions">Github Actions</a> e esse workflow específico seja responsável de realizar a criação de um bucket s3 em sua conta AWS utilizando <a href="https://www.terraform.io/">Terraform</a> como <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">IaC</a>. Considere <a href="https://github.com/danielpadua/iac-authz-example">este repositório</a> como referência e vamos analisar a estrutura do projeto:</p><pre>.<br>├── .github<br>│   └── workflows<br>│       └── deploy.yml<br>└── iac<br>    ├── .gitignore<br>    ├── backend.tf<br>    ├── main.tf<br>    ├── outputs.tf<br>    ├── provider.tf<br>    ├── terraform.tfvars<br>    └── variables.tf</pre><p>O diretório .github é responsável por abrigar os workflows de CI/CD, que contem o arquivo de workflow deploy.yml. O diretório iac é responsável por abrigar os arquivos de configuração do Terraform, que são os arquivos backend.tf, main.tf, outputs.tf, provider.tf, terraform.tfvars e variables.tf.</p><p>O arquivo deploy.yml é responsável por executar o deploy do bucket s3 na conta AWS. Este workflow é executado quando um push é realizado na branch main. Veja abaixo o conteúdo do arquivo deploy.yml:</p><pre>name: iac authz example workflow<br>on:<br>  push:<br>    branches:<br>      - main<br>    paths-ignore:<br>      - &quot;.gitignore&quot;<br>      - &quot;README.md&quot;<br>permissions:<br>  id-token: write<br>  contents: read<br>env:<br>  TF_BACKEND: iac-authz-example-tf<br>  AWS_REGION: ${{ secrets.AWS_REGION }}<br>defaults:<br>  run:<br>    shell: bash<br>jobs:<br>  terraform-backend:<br>    name: Ensure terraform backend<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Configure AWS Credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ secrets.AWS_ROLE }}<br>          aws-region: ${{ secrets.AWS_REGION }}<br>      - name: Create terraform backend<br>        run: |<br>          if [[ -z $(aws s3api list-buckets --query &#39;Buckets[?Name==`${{ env.TF_BACKEND }}`]&#39; --output text) ]]; then<br>            aws s3 mb s3://${{ env.TF_BACKEND }}<br>          fi<br>          aws s3api head-object --bucket bucket-name --key terraform.tfstate || NOT_EXIST=true<br>          if [ $NOT_EXIST ]; then<br>            aws s3api put-object --bucket ${{ env.TF_BACKEND }} --key terraform.tfstate            <br>          fi<br>  terraform:<br>    name: Deploy infrastructure<br>    needs: terraform-backend<br>    runs-on: ubuntu-latest<br>    defaults:<br>      run:<br>        working-directory: iac<br>    steps:<br>      - name: Checkout repo<br>        uses: actions/checkout@v3<br>      - name: Configure AWS Credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: ${{ secrets.AWS_ROLE }}<br>          aws-region: ${{ secrets.AWS_REGION }}<br>      - name: Setup terraform<br>        uses: hashicorp/setup-terraform@v2<br>        with:<br>          terraform_wrapper: false<br>      - name: Terraform fmt<br>        run: terraform fmt -check<br>      - name: Terraform init<br>        run: |<br>          terraform init -upgrade \<br>            -backend-config=&quot;bucket=${{ env.TF_BACKEND }}&quot; \<br>            -backend-config=&quot;key=terraform.tfstate&quot; \<br>            -backend-config=&quot;region=${{ secrets.AWS_REGION }}&quot;<br>      - name: Terraform validate<br>        run: terraform validate -no-color<br>      - name: Terraform plan<br>        run: terraform plan -no-color -var-file terraform.tfvars<br>      - name: Terraform apply<br>        run: terraform apply -auto-approve -var-file terraform.tfvars<br>      - name: Terraform outputs<br>        id: tf-outputs<br>        run: |<br>          echo &quot;bucket-arn=`terraform output -raw bucket_arn`&quot; &gt;&gt; $GITHUB_OUTPUT</pre><p>No arquivo deploy.yml, temos dois jobs, o primeiro é responsável por criar o bucket s3 que será utilizado como backend do Terraform, enquanto o segundo é responsável por executar o deploy do do terraform do projeto em si, neste caso o bucket s3.</p><p>Agora, vamos pensar em algumas regras básicas de segurança quando tratamos buckets s3 corporativamente:</p><ul><li>Necessidade de garantir que os buckets sejam privados</li><li>Necessidade de garantir que os buckets sejam criptografados</li><li>Necessidade de garantir que os buckets tenham versionamento habilitado</li></ul><p>Podemos denominar que estas regras em conjunto caracterizam uma baseline de segurança especificamente para o recurso s3 da AWS. Não possuir uma autorização na pipeline de infraestrutura que garanta que essas regras estejam sendo aplicadas pode resultar em arquivos sensíveis sendo expostos, perda de arquivos, danos de imagem, danos financeiros e entre outros.</p><h3>Aplicando autorização de IaC<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#aplicando-autoriza%C3%A7%C3%A3o-de-iac">​</a></h3><p>Com o entendimento da estrutura do projeto e o problema exposto, vamos partir para uma solução que mitiga estes riscos. A ideia é ter um step no workflow onde podemos validar o plano do terraform a ser executado e aplicar a baseline de segurança.</p><h3>Política de autorização<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#pol%C3%ADtica-de-autoriza%C3%A7%C3%A3o">​</a></h3><p>O primeiro passo aqui seria expressar a baseline de segurança do s3 que definimos acima em políticas na <a href="https://www.openpolicyagent.org/docs/latest/policy-language">linguagem rego</a>, por questões de simplicidade, iremos embutir as políticas de segurança no mesmo repositório do exemplo. Entretanto tenha em mente que em um ambiente corporativo, as políticas de segurança devem ser mantidas em um repositório separado, para que possam ser versionadas, auditadas e fora do alcance de alterações não autorizadas.</p><p>Vamos criar um diretório chamado policy e dentro dele um arquivo chamado main.rego com o seguinte conteúdo:</p><pre>package main<br><br>import data.baseline.aws.common<br>import data.baseline.aws.s3<br>import future.keywords.if<br><br>default allow := false<br><br>allow if {<br>    s3.baseline_valid<br>}<br><br>result[&quot;allowed&quot;] := allow<br>result[&quot;violations&quot;] := s3.violations</pre><p>E também vamos criar um diretório chamado baseline e dentro dele um diretório chamado aws e um arquivo chamado s3.rego que contem a baseline de segurança do s3, com o conteúdo a seguir:</p><pre>package baseline.aws.s3<br><br>import future.keywords.if<br>import input as tfplan<br><br>baseline_valid if {<br>    s3_bucket_public_access__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_public_access_block&quot;]<br>    s3_bucket_server_side_encryption_configuration__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_server_side_encryption_configuration&quot;]<br>    s3_bucket_versioning__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_versioning&quot;]<br>    s3__public_access_disabled(s3_bucket_public_access__changes)<br>    s3__bucket_cryptography_enabled(s3_bucket_server_side_encryption_configuration__changes)<br>    s3__bucket_versioning_enabled(s3_bucket_versioning__changes)<br>}<br><br>violations[&quot;S3 - Bucket should block all public access&quot;] {<br>    s3_bucket_public_access__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_public_access_block&quot;]<br>    not s3__public_access_disabled(s3_bucket_public_access__changes)<br>}<br><br>violations[&quot;S3 - Bucket should be encrypted&quot;] {<br>    s3_bucket_server_side_encryption_configuration__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_server_side_encryption_configuration&quot;]<br>    not s3__bucket_cryptography_enabled(s3_bucket_server_side_encryption_configuration__changes)<br>}<br><br>violations[&quot;S3 - Bucket should be versioned&quot;] {<br>    s3_bucket_versioning__changes := [r | r := tfplan.resource_changes[_]; r.type == &quot;aws_s3_bucket_versioning&quot;]<br>    not s3__bucket_versioning_enabled(s3_bucket_versioning__changes)<br>}<br><br>########################################################<br># Baseline: S3 - Bucket should block all public access #<br>########################################################<br>s3__public_access_disabled(s3_bucket_public_access__changes) if {<br>    s3_bucket_public_access__changes[_].change.after.block_public_acls == true<br>    s3_bucket_public_access__changes[_].change.after.block_public_policy == true<br>    s3_bucket_public_access__changes[_].change.after.ignore_public_acls == true<br>    s3_bucket_public_access__changes[_].change.after.restrict_public_buckets == true<br>}<br><br>#############################################<br># Baseline: S3 - Bucket should be encrypted #<br>#############################################<br>s3__bucket_cryptography_enabled(s3_bucket_server_side_encryption_configuration__changes) if {<br>    s3_bucket_server_side_encryption_configuration__changes[_].change.after.rule[_].apply_server_side_encryption_by_default[_].sse_algorithm == &quot;AES256&quot;<br>}<br><br>s3__bucket_cryptography_enabled(s3_bucket_server_side_encryption_configuration__changes) if {<br>    s3_bucket_server_side_encryption_configuration__changes[_].change.after.rule[_].apply_server_side_encryption_by_default[_].sse_algorithm == &quot;aws:kms&quot;<br>    s3_bucket_server_side_encryption_configuration__changes[_].change.after.rule[_].apply_server_side_encryption_by_default[_].kms_master_key_id != &quot;&quot;<br>}<br><br>s3__bucket_cryptography_enabled(s3_bucket_server_side_encryption_configuration__changes) if {<br>    s3_bucket_server_side_encryption_configuration__changes[_].change.after.rule[_].apply_server_side_encryption_by_default[_].sse_algorithm == &quot;aws:kms:dsse&quot;<br>    s3_bucket_server_side_encryption_configuration__changes[_].change.after.rule[_].apply_server_side_encryption_by_default[_].kms_master_key_id != &quot;&quot;<br>}<br><br>#############################################<br># Baseline: S3 - Bucket should be versioned #<br>#############################################<br>s3__bucket_versioning_enabled(s3_bucket_versioning__changes) if {<br>    lower(s3_bucket_versioning__changes[_].change.after.versioning_configuration[_].status) == &quot;enabled&quot;<br>}<br></pre><p>Com a política escrita, agora precisamos integrar ao workflow.</p><h3>Integração com o workflow<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#integra%C3%A7%C3%A3o-com-o-workflow">​</a></h3><p>O próximo passo é integrar as políticas criadas no passo anterior com o workflow do Github Actions e forçar a falha caso alguma das políticas não seja atendida. Para isso, precisamos primeiramente realizar a instalação do OPA no workflow, portanto, vamos utilizar o <a href="https://github.com/open-policy-agent/setup-opa">OPA Setup Github Action</a>, conforme abaixo:</p><pre>- name: Setup OPA<br>  uses: open-policy-agent/setup-opa@v2<br>  with:<br>    version: latest</pre><p>Em seguida a ideia é obter o resultado enviado pela política de autorização, interpretar e falhar a pipeline caso a política sinalize, conforme a seguir:</p><pre>- name: Terraform Authz<br>  run: |<br>    RESULT=`opa exec --decision main/result --bundle ../policy/ tfplan.json`<br>    ALLOWED=`echo $RESULT | jq -r &#39;.result[0].result.allowed&#39;`<br>    VIOLATIONS=`echo $RESULT | jq -r &#39;.result[0].result.violations&#39;`<br>    if [ &quot;$ALLOWED&quot; == &quot;true&quot; ]; then<br>      echo &quot;Terraform authz success&quot;          <br>    else<br>      echo &quot;Terraform authz failed&quot;<br>      echo &quot;Security violations: $VIOLATIONS&quot;<br>      exit 1<br>    fi</pre><h3>Validando a solução<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#validando-a-solu%C3%A7%C3%A3o">​</a></h3><p>Primeiramente, vamos realizar o teste quebrando alguma regra da baseline de segurança. Para isto iremos manipular o arquivo main.tf quebrando as regras a seguir:</p><ul><li>Necessidade de garantir que os buckets sejam privados</li><li>Necessidade de garantir que os buckets tenham versionamento habilitado</li></ul><p>Portanto o código ficaria desta maneira:</p><pre>resource &quot;aws_s3_bucket&quot; &quot;this&quot; {<br>  bucket = &quot;my-tf-test-bucket-${random_id.this.hex}&quot;<br>  tags = var.tags<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  versioning_configuration {<br>    status = &quot;Disabled&quot; # quebrando a baseline<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  block_public_acls       = false # quebrando a baseline<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  rule {<br>    apply_server_side_encryption_by_default {<br>      sse_algorithm = &quot;AES256&quot;<br>    }<br>  }<br>}<br><br>resource &quot;random_id&quot; &quot;this&quot; {<br>  byte_length = 8<br>}</pre><p>A execução da pipeline se dará desta maneira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMy3BpNRDnotZhGFwKYVSQ.png" /><figcaption>Imagem mostra uma execução de pipeline do github actions com falha no passo Terraform Authz devido as violações encontradas no terraform</figcaption></figure><p>Note que a policy executou, identificou problemas de autorização no plano do terraform e impediu que a esteira continuasse com a criação dos recursos. Caso os recursos de acesso público e versionamento não fossem declarados, a pipeline também iria falhar.</p><p>Por fim, vamos testar a autorização de IaC com sucesso, para isso, vamos corrigir os problemas de segurança no arquivo main.tf e executar a pipeline novamente:</p><pre>resource &quot;aws_s3_bucket&quot; &quot;this&quot; {<br>  bucket = &quot;my-tf-test-bucket-${random_id.this.hex}&quot;<br>  tags = var.tags<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  versioning_configuration {<br>    status = &quot;Enabled&quot; # corrigir problema de segurança<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  block_public_acls       = true # corrigir problema de segurança<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  rule {<br>    apply_server_side_encryption_by_default {<br>      sse_algorithm = &quot;AES256&quot;<br>    }<br>  }<br>}<br><br>resource &quot;random_id&quot; &quot;this&quot; {<br>  byte_length = 8<br>}</pre><p>A execução da pipeline se dará desta maneira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLCcM0R-Gb5ZPAGPwQ_7DQ.png" /><figcaption>A imagem mostra uma execução de pipeline no github actions com sucesso</figcaption></figure><h3>Conclusão<a href="http://127.0.0.1:3000/repoName/docs/produtividade/ferramentas/vscode/iac-authorization#conclus%C3%A3o">​</a></h3><p>Neste artigo foi apresentado como é possível autorizar infraestrutura como código utilizando o OPA e Github Actions. A solução abordada tem um investimento de tempo relativamente baixo, desta maneira, tem um ótimo custo-benefício para empresas que estão iniciando ou querem iniciar a jornada de autorização de infraestrutura como código.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a342045468bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/autoriza%C3%A7%C3%A3o-de-infraestrutura-como-c%C3%B3digo-a342045468bf">Autorização de Infraestrutura como Código</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hospedando site estático no Azure via portal]]></title>
            <link>https://medium.com/danielpadua/hospedando-site-est%C3%A1tico-no-azure-via-portal-8b30fe660477?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b30fe660477</guid>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[azure-storage]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 23:35:09 GMT</pubDate>
            <atom:updated>2021-07-11T23:57:36.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewzaX9Ht-UYuB1efeV8MWA.png" /></figure><blockquote>Neste artigo irei demonstrar o quão fácil é realizar o deploy de uma aplicação web estática (que não faz uso de processamento do lado do servidor) na infraestrutura do Azure utilizando o Azure Storage e fazendo a entrega usando o Visual Studio Code.</blockquote><h3>Introdução</h3><p>Muitas vezes quando temos requisitos onde não é necessário haver algum tipo de processamento do front-end do lado do servidor, podemos fazer uso de aplicações web estáticas (<a href="https://imasters.com.br/front-end/por-que-utilizamos-single-page-applications-spa">SPA, MPA</a>). Com o advento dos frameworks javascript (<a href="https://pt-br.reactjs.org/">react</a>, <a href="https://angular.io/">angular</a>, <a href="https://vuejs.org/">vue</a>, etc…) e os geradores de site estáticos (<a href="https://www.gatsbyjs.com/">gatsbyjs</a>, <a href="https://jekyllrb.com/">jekyll</a>, <a href="https://gohugo.io/">hugo</a> e etc…) os sites estáticos passaram a ficar cada vez melhores, além de performarem muito bem (desde que otimizados) e até muitas vezes atender a maioria dos requisitos de qualquer projeto.</p><p>Neste artigo introdutório, irei mostrar como realizar o deploy na infraestrutura do Azure, usando o Azure Storage utilizando o fonte de um website que oferece um jogo da velha.</p><h3>Requisitos</h3><ul><li><a href="https://code.visualstudio.com/download">Visual Studio Code</a></li><li><a href="https://azure.microsoft.com/pt-br/free">Conta Azure</a></li></ul><h3>Criando o Azure Storage</h3><p>O Azure Storage é a solução de armazenamento de objetos (estruturados e não-estruturados) da Microsoft para cloud. Ele engloba vários serviços, para diferentes fins:</p><ul><li><a href="https://docs.microsoft.com/pt-br/azure/storage/blobs/storage-blobs-introduction">Azure Blobs</a>: Uma object store massiva para guardar dados do tipo texto ou binário, suporta também analytics big data através do Data Lake Storage Gen2</li><li><a href="https://docs.microsoft.com/pt-br/azure/storage/files/storage-files-introduction">Azure Files</a>: Um compartilhamento de arquivos (file share) completamente gerenciado para uso cloud ou on-premises</li><li><a href="https://docs.microsoft.com/pt-br/azure/storage/queues/storage-queues-introduction">Azure Queues</a>: Uma área confiável para guardar dados de troca mensagens entre componentes de aplicações</li><li><a href="https://docs.microsoft.com/pt-br/azure/virtual-machines/managed-disks-overview">Azure Disks</a>: Um storage para guardar volumes para máquinas virtuais Azure (Azure VMs)</li></ul><p>Neste artigo iremos utilizar o serviço <strong>Azure Blobs</strong>, que irá armazenar os arquivos do nosso site estático.</p><p>Primeiramente, vamos criar um grupo de recursos — ou <em>resource group</em> (utilizado para agrupar recursos Azure), para separar os recursos deste guia do resto dos seus possível recursos. Acesse o <a href="https://portal.azure.com/">Portal do Microsoft Azure</a>, faça o login e clique em “Resource Groups” (ou Grupos de Recurso se estiver em português) no menu de favoritos (do lado esquerdo da tela), ou utilize a barra de pesquisa, em seguida clique no botão “Create”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDtJXMTPkVaamD4QKdjH0Q.png" /><figcaption>Criando um Resource Group no Portal da Azure</figcaption></figure><p>Escolha o nome do Resource Group e a localização do datacenter e clique em Create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z32Rlk4mu8rojPjg9HvraQ.png" /><figcaption>Preenchendo informações do Resource Group</figcaption></figure><p>Certifique-se de que está navegando dentro do Resource Group criado na etapa anterior e clique em Create &gt; Marketplace para adicionar um recurso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IN1s2HyhFUJXZMWfRSHrQ.png" /><figcaption>Adicionando um recurso</figcaption></figure><p>Pesquise por storage aperte enter e selecione “Storage Account” da Microsoft, clique em Create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnGbJqZ3ORwgUcyXB7Xc8w.png" /><figcaption>Pesquisando o Azure Storage</figcaption></figure><p>Preencha as informações necessárias conforme imagem, e clique em “Review + create”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVfCDigANawQmBkrPXl2YQ.png" /><figcaption>Preenchendo informações do storage</figcaption></figure><blockquote>Lembre-se que o nome do storage deve ser único globalmente (único entre todos os storages registrados no Azure), ter entre 3 e 24 caracteres e deve conter apenas letras minúsculas e números, sem caracteres especiais</blockquote><p>Deixe todas as informações com os valores padrão e clique em “Create”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7_c7DxgsxXgsZGqFCaLPA.png" /><figcaption>Adicionando o storage</figcaption></figure><p>O Azure irá iniciar o processo de criação do storage e quando estiver tudo pronto a tela a seguir será apresentada, clique no botão “Go to resource”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFP3Ox9__JvxtWtjapZTTA.png" /><figcaption>Storage criado com sucesso</figcaption></figure><p>Se realmente estiver tudo certo, a dashboard do seu storage será exibida conforme a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0A09aoH5SiZPSz_rtV7Fg.png" /><figcaption>Dashboard do Azure Storage</figcaption></figure><h3>Instalando a extensão Azure Storage</h3><p>Com a infraestrutura criada e pronta para abrigar seu site estático, é hora de garantir que seu Visual Studio Code tenha as extensões necessárias para poder publicar os arquivos do projeto no Azure Storage criado. Para isto, abra o vscode e no menu do lado esquerdo vá em Extensions ou aperte ctrl+shift+X e pesquise por azure storage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAcTUoDpp1IYnTnJqNx2Zg.png" /><figcaption>Pesquisando a extensão do azure storage</figcaption></figure><p>Ou simplesmente siga <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurestorage">este link</a> e clique em Install.</p><p>Esta extensão irá instalar automáticamente a extensão Azure Account onde irá criar o menu Azure no lado esquerdo da tela, no qual você irá realizar login utilizando seu e-mail e senha Azure. Siga os passos que a extensão irá lhe pedir e garanta que sua conta esteja logada e suas subscriptions apareçam conforme imagem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9bViX9DQ_akGxx9MJdOrg.png" /><figcaption>Extensão Azure Storage login com sucesso</figcaption></figure><h3>Clonando e publicando a aplicação</h3><p>Agora vamos preparar o site estático para o deploy no Azure, no Visual Studio Code abra o terminal (menu superior &gt; terminal &gt; new terminal ou ctrl+shift+` ou cmd+shift+` no mac) navegue e escolha o diretório que preferir para abrigar o projeto. Em seguida clone o projeto utilizando e navegue até ele com:</p><pre>git clone https://github.com/danielpadua/js-tic-tac-toe.git my-static-website<br>cd my-static-website</pre><p>Agora abra o diretório criado no Visual Studio Code: File &gt; Open Folder &gt; ...:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qWTY0tQs5hm1Rqy0RmHyw.png" /><figcaption>Estrutura do projeto</figcaption></figure><p>Para entregar o projeto no Azure Storage criado, é necessário simplesmente clicar no diretório que deseja entregar com o botão direito e em seguida escolher a opção Deploy to static Website via Azure Storage. Como queremos entregar todos os arquivos do diretório aberto, vamos clicar com o botão direito sobre o espaço vazio na raíz da árvore de arquivos conforme a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvNc3P3Y9B-oCerIXXIDYA.png" /><figcaption>Clique na opção indicada em vermelho para entregar todos os arquivos</figcaption></figure><p>Na sequência irão aparecer algumas opções para que você possa indicar à extensão em qual Azure Storage você quer entregar os arquivos, caso você tenha mais de uma subscription, você deverá selecionar a mesma que criou o Storage nos passos anteriores e em seguida selecione-o:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5EZ3Z3uohPD33ArOEKd2w.png" /><figcaption>Selecione o mesmo Storage criado nos passos anteriores</figcaption></figure><p>Ao selecionar, a extensão poderá te avisar que a opção de hospedar sites estáticos não está habilitada no Storage selecionado e irá perguntar se você deseja habilitar. Escolha a opção Enable website hosting.</p><p>Em seguida você será questionado sobre qual será o nome do arquivo html que deverá ser considerado o renderizado ao usuário atingir a URL raíz do website, deixe escrito index.html e aperte enter. Na sequência irá te perguntar sobre qual nome de arquivo considerar quando o usuário tentar acessar algum documento que não existe. No caso deste projeto não há tratamento então podemos seguir com o index.html sugerido, mas caso seu projeto tenha indique o nome do arquivo correto.</p><p>Pressione enter novamente e o deploy irá iniciar. Após o término com sucesso, a mensagem a seguir deverá aparecer no canto inferior direito de sua tela:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*rFTDzYYNPbD_C8WV9FyR7Q.png" /><figcaption>Deploy feito com sucesso</figcaption></figure><p>Navegue até o link indicado na mensagem e veja seu site!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H0AHK_oTG9NlMf_aPYGng.png" /><figcaption>Website Pronto!</figcaption></figure><h3>Conclusão</h3><p>Em apenas alguns minutos é possível entregar um site estático no Azure utilizando o Visual Studio Code. Mas não apenas fácil, é barato também. Na verdade acredito que o que torna este modelo mais atraente é o preço.</p><p>Neste momento eu mantenho 2 sites estáticos no Azure com poucos acessos e o custo gira em torno de R$13,00 ao mês, mas o cálculo de custo é feito com base por largura de banda (transferência de dados) e quantidade de storage usado (tamanho). O melhor jeito de ter uma noção de quanto irá gastar é ver na própria calculadora do Azure: <a href="https://azure.microsoft.com/en-us/pricing/calculator/?service=storage">https://azure.microsoft.com/en-us/pricing/calculator/?service=storage</a>.</p><p>Espero que este guia tenha sido útil para você, obrigado e até a próxima!</p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>Caso tenha achado que esse post foi útil e quiser me apoiar, você pode fazer isto me pagando um café usando o botão acima!</figcaption></figure><p><em>Publicado originalmente em </em><a href="https://blog.danielpadua.dev/pt/posts/hospedando-site-estatico-azure-portal"><em>https://blog.danielpadua.dev</em></a><em> 3 de Julho de 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b30fe660477" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/hospedando-site-est%C3%A1tico-no-azure-via-portal-8b30fe660477">Hospedando site estático no Azure via portal</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting a static website in Azure via Portal]]></title>
            <link>https://medium.com/danielpadua/hosting-a-static-website-in-azure-via-portal-707293eeaa2d?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/707293eeaa2d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[azure-storage]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 20:00:00 GMT</pubDate>
            <atom:updated>2021-07-11T23:51:12.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewzaX9Ht-UYuB1efeV8MWA.png" /></figure><blockquote>In this article I’ll show how easy is to host and deploy a static web application (that doesn’t require server-side processing) to Azure’s infraestructure making use of Azure Storage and delivering it with Visual Studio Code</blockquote><h3>Intro</h3><p>There are times when our front-end projects doesn’t require any kind of server-side processing. When that happens we can make use of completly static web applications such as <a href="https://merehead.com/blog/single-page-application-vs-multi-page-application">SPA and MPA</a>. With the advent of javascript frameworks such as <a href="https://pt-br.reactjs.org/">react</a>, <a href="https://angular.io/">angular</a>, <a href="https://vuejs.org/">vue</a>, etc… and the static website generators like <a href="https://www.gatsbyjs.com/">gatsbyjs</a>, <a href="https://jekyllrb.com/">jekyll</a>, <a href="https://gohugo.io/">hugo</a>, etc… static websites grown better, faster, cleaner and more able to meet most requirements of any project.</p><p>In this introductory article I’ll show how to deploy a simple tictactoe static website to Azure’s infraestructure using Azure Storage and Visual Studio Code. Let’s get to it.</p><h3>Requirements</h3><ul><li><a href="https://code.visualstudio.com/download">Visual Studio Code</a></li><li><a href="https://azure.microsoft.com/en-us/free">Azure Account</a></li></ul><h3>Creating a Azure Storage</h3><p>Azure Storage is Microsoft’s cloud solution to store objects (structured or non-structured). It encompasses several services, for different purposes:</p><ul><li><a href="https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction">Azure Blobs</a>: A massive object store used to retain any kind of text or binary data. It also supports analytics big data through Data Lake Storage Gen2</li><li><a href="https://docs.microsoft.com/en-us/azure/storage/files/storage-files-introduction">Azure Files</a>: A completely managed file share for cloud or on-premises environment</li><li><a href="https://docs.microsoft.com/en-us/azure/storage/queues/storage-queues-introduction">Azure Queues</a>: A reliable area to store data exchange messages between applications and components</li><li><a href="https://docs.microsoft.com/en-us/azure/virtual-machines/managed-disks-overview">Azure Disks</a>: A storage to retain volumes for Azure Virtual Machines (Azure VMs)</li></ul><p>In this article we’ll use <strong>Azure Blobs</strong> service, that will store all our static website files.</p><p>First of all, let’s create a resource group to separate this guide’s resources from all your possible other resources. Access <a href="https://portal.azure.com/">Microsoft Azure Portal</a>, log in and click Resource Groups in favorites menu (left side of the screen), or use the search bar. Next click Create button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDtJXMTPkVaamD4QKdjH0Q.png" /><figcaption>Creating a Resource Group in Azure’s Portal</figcaption></figure><p>Choose the Resource Group name and the datacenter location and click Create again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z32Rlk4mu8rojPjg9HvraQ.png" /><figcaption>Filling Resource Group information</figcaption></figure><p>Ensure that you are navigating inside the recently created Resource Group and click Create &gt; Marketplace to add a resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IN1s2HyhFUJXZMWfRSHrQ.png" /><figcaption>Adding a resource</figcaption></figure><p>Search for “storage” and hit enter, then select “Storage Account” from Microsoft and click Create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnGbJqZ3ORwgUcyXB7Xc8w.png" /><figcaption>Search for Azure Storage</figcaption></figure><p>Fill all the required fields as the following image and click Review + create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVfCDigANawQmBkrPXl2YQ.png" /><figcaption>Filling storage information</figcaption></figure><blockquote><em>Storage name must be globally unique (accross all storages registered in Azure), it must be 3 to 24 characters long and can contain only lowercase letters and numbers</em></blockquote><p>Leave all informations with default values and click Create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7_c7DxgsxXgsZGqFCaLPA.png" /><figcaption>Adding the storage</figcaption></figure><p>Azure will begin the creation of the storage and when it’s ready, the following screen will be presented. Click the button Go to resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFP3Ox9__JvxtWtjapZTTA.png" /><figcaption>Storage successfully created</figcaption></figure><p>If everything is ok, your storage dashboard will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0A09aoH5SiZPSz_rtV7Fg.png" /><figcaption>Storage’s dashboard</figcaption></figure><h3>Installing Azure Storage extension</h3><p>With the required infraestructure to store our static website ready, it’s time to ensure that your Visual Studio Code have the required extensions to publish your project files to the recently created Azure Storage. So, open your vscode, look for Extensions in the left side menu or simply press ctrl+shift+X and search for azure storage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAcTUoDpp1IYnTnJqNx2Zg.png" /><figcaption>Searching for azure storage extension</figcaption></figure><p>Or, you can click <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurestorage">this link</a> then click Install.</p><p>This extension will automatically install Azure Account extension, which will create Azure menu in screen&#39;s left side. Click it and log in using your Azure email and password, follow the steps the extension show you and make sure your account is logged in and your subscriptions are showing, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9bViX9DQ_akGxx9MJdOrg.png" /><figcaption>Azure Account logged in</figcaption></figure><h3>Cloning and deploying the app</h3><p>Now let’s get our tictactoe static website ready to deploy to Azure. In Visual Studio Code open the terminal ( superior menu &gt; terminal &gt; new terminal or ctrl+shift+` or cmd+shift+` in mac) navigate to a directory of your preference to store the project. Then clone the project and navigate to it with:</p><pre>git clone https://github.com/danielpadua/js-tic-tac-toe.git my-static-website<br>cd my-static-website</pre><p>Now open the created directory in Visual Studio Code via File &gt; Open Folder &gt; ...:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qWTY0tQs5hm1Rqy0RmHyw.png" /><figcaption>Project structure</figcaption></figure><p>To deploy the project to the recently created Azure Storage, you simply have to right-click in the directory you wish to deploy and choose the Deploy to static Website via Azure Storage option. In this project, we&#39;ll want to deliver all the opened files, so, let&#39;s right-click over the empty space in the root of the files tree as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvNc3P3Y9B-oCerIXXIDYA.png" /><figcaption>Click the highlighted option to deploy all files</figcaption></figure><p>Then some options will pop-up for you to tell the extension in which Azure Storage you want to deliver the files, if you have more than one subscription, you must select the same one that you created the Storage earlier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5EZ3Z3uohPD33ArOEKd2w.png" /><figcaption>Select the same Storage you created earlier</figcaption></figure><p>After selecting, the extension might warn you that the static website hosting is not enabled in the selected Storage and will ask you if you wish to enable. We do want that, so choose Enable website hosting option.</p><p>You will then be asked what will be the name of the html file that must be considered when your user hit the root URL of your website, leave it written index.html and hit enter. Next, you will be asked the name of the file to present when your user try to access a nonexistent document. In this project there is no page to present in this scenario so we can keep the suggested index.html, but if your project have one, fill the name correctly.</p><p>Press enter again and the deploy will begin. After it successfully ends, the following message will appear in your screen’s inferior right side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*rFTDzYYNPbD_C8WV9FyR7Q.png" /><figcaption>Successfully deployed</figcaption></figure><p>Navigate to the link written in the message and see your website running!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H0AHK_oTG9NlMf_aPYGng.png" /><figcaption>Website ready</figcaption></figure><h3>Conclusion</h3><p>In just a few minutes it’s possible to deploy a static website to Azure using Visual Studio Code. Not only easy, but also cheap. Actually I believe that the price is what’s more attractive in this hosting model.</p><p>At this moment I maintain 2 static websites in Azure with little access and I pay around $2,57/mo. But the better cost calculation is done considering bandwidth and storage size used. The best way to estimate is using Azure calculator: <a href="https://azure.microsoft.com/en-us/pricing/calculator/?service=storage">https://azure.microsoft.com/en-us/pricing/calculator/?service=storage</a>.</p><p>I hope this guide was useful to you, thanks and see you guys soon!</p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/hosting-a-static-website-in-azure-portal/"><em>https://blog.danielpadua.dev</em></a><em> on July 3, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707293eeaa2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/hosting-a-static-website-in-azure-via-portal-707293eeaa2d">Hosting a static website in Azure via Portal</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Protocol Buffers — protobuf]]></title>
            <link>https://medium.com/danielpadua/understanding-protocol-buffers-protobuf-a466d8943df8?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/a466d8943df8</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 03:04:45 GMT</pubDate>
            <atom:updated>2021-07-12T00:28:56.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Protocol Buffers — protobuf</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUG6wMZniIxMiuwJP5x60w.png" /></figure><h3>Intro</h3><p>Protocol Buffers (protobuf) is a method of serializing structured data which is particulary useful to communication between services or storing data. <br>It was designed by Google early 2001 (but only publicly released in 2008) to be smaller and faster than XML. Protobuf messages are serialized into a <a href="https://developers.google.com/protocol-buffers/docs/encoding">binary wire</a> format which is very compact and boosts performance.</p><h3>Details</h3><p>This protocol involves a specific <a href="https://en.wikipedia.org/wiki/Interface_description_language">interface description language</a> to describe the data structure defined in a <em>.proto</em> file. <br>A program from any language supported is able to generate source code from that description in order to create or parse a stream of bytes that represents the structured data.<br>Protocol buffers can serve as basis for a remote procedure call (RPC) which are widely used for inter-machine communication, most commonly used with <a href="https://grpc.io/">gRPC</a>. Protobuf is similar to <a href="https://thrift.apache.org/">Apache Thrift</a> used by Facebook, <a href="https://amzn.github.io/ion-docs/">Ion</a> by Amazon or <a href="https://microsoft.github.io/bond/manual/bond_cs.html">Microsoft Bonds Protocol</a>.</p><h3>Example</h3><p>In this example we will be creating two projects:</p><ul><li>A Java console application that will use the customer .proto specification to generate a file with a hard coded customer</li><li>A C# console application that will read the hard coded customer file generated by Java console application, and display the data in console</li></ul><h4>tl;dr</h4><p>If you just want to read some code and figure it out on your own, I&#39;ve setup these two applications repository. First follow instructions of the README file of the Java project repository:</p><p><a href="https://github.com/danielpadua/protobuf-example-java">danielpadua/protobuf-example-java</a></p><p>Then after generating the protobuf serialized file, follow the instructions of the README file of the C# project repository:</p><p><a href="https://github.com/danielpadua/protobuf-example-csharp">danielpadua/protobuf-example-csharp</a></p><h4>Protobuf Contract</h4><p>First of all, let&#39;s create a structure that will represent a customer. The data required for a customer are:</p><ul><li>Unique identification</li><li>Photo</li><li>Name</li><li>Birthdate</li><li>Creation timestamp</li><li>Last update timestamp</li></ul><p>So, we need to create a <em>.proto </em>file like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5678cfb94191d1d2c8aa4c96245060e6/href">https://medium.com/media/5678cfb94191d1d2c8aa4c96245060e6/href</a></iframe><p>Some notes about the code above:</p><ul><li><em>Timestamp</em> type is a &quot;<a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">Well Known Type</a>&quot; introduced in proto3, you can use these types by importing in the first lines of proto file</li><li><em>Date</em> and <em>Money</em> types are a &quot;Google Common Type&quot;, differently than &quot;Well Known Type&quot; you are not able to use it only by importing. You have to copy these types definitions file from <a href="https://github.com/googleapis/googleapis/tree/master/google/type">google repository</a> and paste it in your project whatever the language you are using.</li></ul><p>There are other scalar types, you can read the documentation <a href="https://developers.google.com/protocol-buffers/docs/proto3#scalar">here</a>. Well Known Types <a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">here</a> or Google Common Types <a href="https://github.com/googleapis/googleapis/tree/master/google/type">here</a>.</p><p>This <em>.proto</em> file will be a common resource in C# and Java but for simplicity sake, I&#39;ll recreate it in both projects repository. The ideal for big and complex projects is to have a separate repository as a neutral ground for projects.</p><h4>Java Console Application</h4><p>That said, let us start by creating the Java console application. For this example I&#39;ll be using OpenJDK 15, IntelliJ IDEA CE and Maven as build tool to do so.</p><ol><li>Open IntelliJ IDEA CE and choose to create a new project</li></ol><figure><img alt="An image of IntelliJ IDEA Community as soon as it starts, with new project option highlighted" src="https://cdn-images-1.medium.com/max/1024/1*17Em58qNICvk3KRcATN7Vg.png" /><figcaption>Creating a new project</figcaption></figure><p>2. Choose Maven in the left panel, select your Java JDK at top of right side. As said I&#39;ll be using OpenJDK 15 previously installed</p><figure><img alt="An image of the screen IntelliJ shows to choose the build tool, with Maven selected and the default archetype" src="https://cdn-images-1.medium.com/max/800/1*hcTI8rHKE-xUe0IwF5c6qg.png" /><figcaption>New project details</figcaption></figure><p>3. Fill the next fields as you wish, for example:</p><figure><img alt="An image of dialog containing the maven settings to be filled, like: project location, groupid, artifactid and version" src="https://cdn-images-1.medium.com/max/801/1*uqmuSBQm15XL0YxQ51DpfQ.png" /><figcaption>Project maven settings</figcaption></figure><p>Project created, let&#39;s start by adding project source encoding, telling maven compiler we are using JDK 15 and adding <a href="https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java">protobuf-java</a> dependency by Google. Add the following lines to <em>pom.xml</em> under &quot;project&quot; tag, right after &quot;version&quot; tag:</p><pre>&lt;properties&gt;<br>    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>    &lt;maven.compiler.source&gt;15&lt;/maven.compiler.source&gt;<br>    &lt;maven.compiler.target&gt;15&lt;/maven.compiler.target&gt;<br>&lt;/properties&gt;<br><br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt;<br>        &lt;artifactId&gt;protobuf-java&lt;/artifactId&gt;<br>        &lt;version&gt;3.13.0&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Now let&#39;s include the <em>.proto</em> files defined in the section above. But before create a <em>proto</em> directory in <em>src/main</em>:</p><figure><img alt="An image of the action of opening IntelliJ context menu to create a directory in src/main" src="https://cdn-images-1.medium.com/max/1024/1*CLWLk_uM2W7VIzXxzjR5tw.png" /><figcaption>Creating protobuf files directory</figcaption></figure><p>Then add a new file named: <em>customer.proto </em>to it and add the code mentioned in above section:</p><figure><img alt="An image showing the customer protobuf file with a compilation error" src="https://cdn-images-1.medium.com/max/1024/1*Y1QFo7b62foOWM9YTq4BoQ.png" /><figcaption>Error importing other protobuf files</figcaption></figure><p>The <em>money.proto</em> and <em>date.proto</em> imports will be pointing error, because we did not created it yet. You can create then repeating the process above and adding the of <a href="https://github.com/googleapis/googleapis/blob/master/google/type/money.proto">money.proto</a> and <a href="https://github.com/googleapis/googleapis/blob/master/google/type/date.proto">date.proto</a> from Google repository.</p><figure><img alt="An image showing customer.proto file without compilation errors" src="https://cdn-images-1.medium.com/max/1024/1*ssROPsHwq0OzGlNYdvT3DQ.png" /><figcaption>customer.proto without errors</figcaption></figure><p>Ok, protobuf contracts created, now, to generate code (java classes) from this contract, we need to use <em>protoc</em> executable to compile <em>.proto</em> files targeting the desired output language. There are two main ways of doing this:</p><ul><li>Manually, by downloading <em>protoc</em> in your machine and running it. If you wish to proceed with this method read <a href="https://grpc.io/docs/protoc-installation/">protoc installation guide here</a></li><li>Automatically, by adding <em>protoc</em> code generation to your maven project build. There are several maven plugins for this, but I will be using <a href="https://github.com/os72/protoc-jar-maven-plugin"><em>protoc-jar-maven-plugin</em></a>, that wraps <em>protoc</em> executable as a <em>jar</em> so it can run in any OS and compile your <em>.proto</em> files.</li></ul><p>You can use it by adding these lines to your <em>pom.xml </em>under &quot;project&quot; tag, right after &quot;dependencies&quot; tag:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;com.github.os72&lt;/groupId&gt;<br>            &lt;artifactId&gt;protoc-jar-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;3.11.4&lt;/version&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;id&gt;protoc.main&lt;/id&gt;<br>                    &lt;phase&gt;generate-sources&lt;/phase&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;run&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                    &lt;configuration&gt;<br>                        &lt;protocVersion&gt;3.13.0&lt;/protocVersion&gt;<br>                        &lt;addSources&gt;main&lt;/addSources&gt;<br>                        &lt;includeMavenTypes&gt;direct&lt;/includeMavenTypes&gt;<br>                        &lt;includeStdTypes&gt;true&lt;/includeStdTypes&gt;<br>                        &lt;includeDirectories&gt;<br>                            &lt;include&gt;src/main/proto&lt;/include&gt;<br>                        &lt;/includeDirectories&gt;<br>                        &lt;inputDirectories&gt;<br>                            &lt;include&gt;src/main/proto&lt;/include&gt;<br>                        &lt;/inputDirectories&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><blockquote>Always check for newer stable versions before adding dependencies or plugins to your <em>pom.xml</em></blockquote><p>We are also including the proto directory structure so the plugin can know where the <em>.proto</em> files are, and compile them.</p><p>At this point you might want to run protoc compiler to generate the java protobuf contract classes so, click maven tab and &quot;run maven goal&quot; button and run a mvn clean install</p><figure><img alt="An image showing integrated maven in IntelliJ ready to execute a clean install goal" src="https://cdn-images-1.medium.com/max/1024/1*ABjjiWb0KzvZrhF__BCsmg.png" /><figcaption>Running maven clean install</figcaption></figure><p>If is successfully compiled, this message will pop up:</p><figure><img alt="An image showing the project builded correctly" src="https://cdn-images-1.medium.com/max/1024/1*njc8VvjbVGwtW6rNQUf4OQ.png" /><figcaption>A build of success</figcaption></figure><p>Next, create a package &quot;dev.danielpadua.protobufexamplejava&quot; and put inside a main class for our console application:</p><figure><img alt="An image showing the Program class with the Java main method empty" src="https://cdn-images-1.medium.com/max/1024/1*9btxrsbY2A9GcbDc2abbfA.png" /><figcaption>Our main method</figcaption></figure><p>If you type &quot;Customer&quot; IntelliJ autocompletion will appear and suggest to import the class that was generated by <em>protoc</em> via plugin:</p><figure><img alt="An image showing the IntelliJ autocomplete successfully recognized autogenerated classes" src="https://cdn-images-1.medium.com/max/693/1*rvtMa_L3M41CFgb1P2Onfg.png" /><figcaption>Autocomplete success with autogenerated classes</figcaption></figure><p>So, it all went well. Now we can write the code to generate a hard coded customer and write it to a file in a directory you want (inside main method):</p><pre>Date birthdate = Utils.<em>toGoogleDate</em>(LocalDate.<em>of</em>(1990<strong>, </strong>4<strong>, </strong>30))<strong>;<br></strong>Money balance = Utils.<em>toGoogleMoney</em>(BigDecimal.<em>valueOf</em>(9000.53))<strong>;<br></strong>Timestamp createdUpdateAt = Utils.<em>toGoogleTimestampUTC</em>(LocalDateTime.<em>now</em>())<strong>;<br></strong>String fullPath = &quot;/Users/danielpadua/protobuf/protobuf-customer&quot;<strong>;<br><br></strong>try (FileOutputStream fos = new FileOutputStream(fullPath)) {<br>    Customer daniel = Customer.<em>newBuilder</em>()<br>            .setId(1)<br>            .setPhoto(ByteString.<em>EMPTY</em>)<br>            .setName(&quot;Daniel&quot;)<br>            .setBirthdate(birthdate)<br>            .setBalance(balance)<br>            .setCreatedAt(createdUpdateAt)<br>            .setUpdatedAt(createdUpdateAt)<br>            .build()<strong>;<br><br>    </strong>daniel.writeTo(fos)<strong>;<br>    </strong>System.<em>out</em>.println(&quot;protobuf-customer created successfully&quot;)<strong>;<br></strong>} catch (FileNotFoundException e) {<br>    System.<em>out</em>.println(<em>format</em>(&quot;could not find file {0}&quot;<strong>, </strong>fullPath))<strong>;<br></strong>} catch (IOException e) {<br>    System.<em>out</em>.println(<em>format</em>(&quot;error while reading file {0}. exception: {1}&quot;<strong>, </strong>fullPath<strong>, </strong>e.getMessage()))<strong>;<br></strong>}</pre><p>Note the code above uses a simple Utils class to convert between Java LocalDate and Google Date, Java BigDecimal and Google Money and Java LocalDateTime and Google Timestamp. You can add my Utils class to your project using the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a8a9bc00fc94795871f5e920e5b4d2/href">https://medium.com/media/33a8a9bc00fc94795871f5e920e5b4d2/href</a></iframe><p>If you have the following problem in IntelliJ, you can simply use the suggested solution &quot;Set language level to 8 — Lambdas, type annotations etc&quot;</p><figure><img alt="An image showing the language level error in IntelliJ IDEA Community" src="https://cdn-images-1.medium.com/max/1024/1*CPBWe-3HHvstfWDsrKRmSg.png" /><figcaption>Language level in IntelliJ IDEA</figcaption></figure><p>Now, let&#39;s run the application. Click &quot;Add Configuration&quot; button located at top right, right after build button. Click the plus icon and select &quot;Application&quot;:</p><figure><img alt="An image showing the dialog for create a run application configuration in IntelliJ IDEA" src="https://cdn-images-1.medium.com/max/1024/1*jlbb3QA6lm9Z8ivdaGUo0Q.png" /><figcaption>Creating run configuration</figcaption></figure><p>Then fill the configuration name and select the main class to run:</p><figure><img alt="An image showing the last fields to fill to create a run configuration before launching the project" src="https://cdn-images-1.medium.com/max/1024/1*cbmSFUW94OV3oWeUUtLRiA.png" /><figcaption>Last fields to fill before launch</figcaption></figure><p>After, just click run button or debug it if you want:</p><figure><img alt="An image showing the run configuration created, the run button and the debug button" src="https://cdn-images-1.medium.com/max/328/1*NNxfdVyLInIH0x3u0adpbw.png" /><figcaption>Let&#39;s run!</figcaption></figure><p>A successfully result should show the following message:</p><figure><img alt="An image showing the result after running the application with success generating the protobuf file" src="https://cdn-images-1.medium.com/max/1024/1*Bp8TSXQOJ5uzsAE_JsbrnQ.png" /><figcaption>Successfully created protobuf file</figcaption></figure><p>Now check the directory you defined for output file:</p><figure><img alt="An image showing the macOs finder with protobuf-customer file generated by the Java application" src="https://cdn-images-1.medium.com/max/772/1*fZluGGppS0iRv9-m9nByXQ.png" /><figcaption>Success!</figcaption></figure><p>We successfully implemented a simple Java console application that creates a protobuf message using the structure defined in a <em>.proto</em> file, using automated protobuf compilation with maven build tool. Now to prove it is useful to different languages communication, we&#39;ll create a C# console application to read this file and show in console.</p><h4>C# Console Application</h4><p>For the C# example I&#39;ll be using: .NET 5, Visual Studio Code and <a href="https://www.nuget.org/packages/Grpc.AspNetCore">Grpc.AspNetCore</a> package that has a built-in protobuf compiler that can be attached to dotnet build.</p><p>Open Visual Studio Code, open a new terminal, navigate to a directory you want to keep your project and execute the following commands one at a time:</p><pre>mkdir protobuf-example-csharp<br>cd protobuf-example-csharp<br>dotnet new console -o src/DanielPadua.ProtobufExampleCsharp<br>dotnet new xunit -o tests/DanielPadua.ProtobufExampleCsharp.Tests<br>dotnet new sln -n DanielPadua.ProtobufExampleCsharp<br>dotnet sln add src/DanielPadua.ProtobufExampleCsharp/DanielPadua.ProtobufExampleCsharp.csproj<br>dotnet sln add tests/DanielPadua.ProtobufExampleCsharp.Tests/DanielPadua.ProtobufExampleCsharp.Tests.csproj</pre><p>All set, project created, now let&#39;s open it in Visual Studio Code:</p><figure><img alt="An image showing Visual Studio Code open menu with the terminal opened" src="https://cdn-images-1.medium.com/max/1024/1*l09ZHKsGLo9lw3SNuvjlqw.png" /><figcaption>Select the root folder (the one you are at the terminal)</figcaption></figure><p>The project structure must look like this:</p><figure><img alt="An image showing Visual Studio Code question about auto creating build debug assets for the project" src="https://cdn-images-1.medium.com/max/1024/1*yTlZEfcg8hUgKH8hZ6xIgg.png" /><figcaption>Add the missing assets to build and debug</figcaption></figure><p>Click &quot;Yes&quot; in the message at bottom right, for <em>Omnisharp</em> create <em>.vscode</em> folder with assets to run/debug project. Select &quot;DanielPadua.ProtobufExampleCsharp&quot;:</p><figure><img alt="An image showing Visual Studio Code questioning which project to create the build debug assets" src="https://cdn-images-1.medium.com/max/1024/1*CVbp64avVU3Fm98iwJayCg.png" /><figcaption>Choose the project to generate the assets</figcaption></figure><p>Open terminal again at the <em>src/DanielPadua.ProtobufExampleCsharp</em> level, and run:</p><pre>dotnet add package Grpc.AspNetCore</pre><p>Now let&#39;s include <em>.proto</em> contracts. Create a directory under main project root named: &quot;Protos&quot; and create the <em>.proto </em>listed in above section:</p><figure><img alt="An image showing the project structure in Visual Studio Code and protobuf files correctly created" src="https://cdn-images-1.medium.com/max/1024/1*EyoXas9nfZ_a-08VmmASEA.png" /><figcaption>Protobuf files created</figcaption></figure><p>Add the <em>.proto</em> files in <em>.csproj </em>for <em>protoc</em> compile when dotnet build runs:</p><figure><img alt="An image showing the code of the csproj adding the path of the recently created protobuf files" src="https://cdn-images-1.medium.com/max/1024/1*Fe6p88-T-r6xo1glu50kTg.png" /><figcaption>Adding the protobuf files for the plugin to compile</figcaption></figure><p>Now let&#39;s build the project to generate C# compiled classes from <em>.proto </em>contracts. In terminal run:</p><pre>dotnet build</pre><p>A successful output message must look like this:</p><figure><img alt="An image showing Visual Studio Code integrated terminal with output indicating the build was successful" src="https://cdn-images-1.medium.com/max/1024/1*sHRAETo2_dmn2yasgBi5-Q.png" /><figcaption>Dotnet build ok</figcaption></figure><p>Next, replace the &quot;Hello World&quot; in Main method for the following lines:</p><pre>var fullpath = @&quot;/Users/danielpadua/protobuf/protobuf-customer&quot;;<br>using var inputStream = File.OpenRead(fullpath);<br><em>Customer</em> c = Customer.Parser.ParseFrom(inputStream);<br>Console.WriteLine(&quot;Customer from protobuf-example-java:&quot;);<br>Console.WriteLine(c.ToString());</pre><p>Now you will have to import Contracts namespace, press ctrl+. (windows, linux) or cmd+. (macOs) to open autocomplete, and the import option will appear:</p><figure><img alt="An image showing Visual Studio Code intellisense to import contracts working with protobuf generated classes" src="https://cdn-images-1.medium.com/max/1024/1*9fYewZBlCnYTURJqy_OB-w.png" /><figcaption>Intellisense and protobuf code generation working</figcaption></figure><p>If it does not appear, try to restart Omnisharp using: ctrl+shift+p (windows, linux) or cmd+shift+p (macOs), type: restart omnisharpand hit enter:</p><figure><img alt="An image showing the Visual Studio Code command palette with restart omnisharp option selected" src="https://cdn-images-1.medium.com/max/1024/1*u5J2RQwVv4n5ZPcPXpJilA.png" /><figcaption>Wait for a moment then try to import again.</figcaption></figure><p>Sadly the protobuf compiler and Omnisharp integration is not perfect, but it works.</p><p>Make sure you are reading the same directory and file that java generate the file, and then run the C# console application by hitting run button (if you configured run/debug assets correctly) or simply by running a: dotnet run being at main project root directory:</p><figure><img alt="An image showing Visual Studio Code integrated terminal with the dotnet run command indicating success" src="https://cdn-images-1.medium.com/max/1024/1*yAm8a9LM9dNDu_FFWxMubA.png" /><figcaption>Running from terminal</figcaption></figure><figure><img alt="An image showing Visual Studio Code run or debug tab indicating success" src="https://cdn-images-1.medium.com/max/1024/1*bozD_lrkfER-_aEzEomINA.png" /><figcaption>Running from Visual Studio Code</figcaption></figure><p>And we did it, received and interpreted a protobuf serialized message generated by a Java application in a C# application.</p><h3>Conclusion</h3><p>Protobuf was made to be faster, lighter hence better performing than other protocols. So, do a quick search like: &quot;protobuf vs json performance&quot; or other, there are tons of benchmarks and success cases.</p><p>In this article I hope to have given a dive in for those who, like me some time ago never even heard of protobuf and always sticked to JSON and XML.</p><p>See you soon!</p><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/Protocol_Buffers">Protocol Buffers - Wikipedia</a></li><li><a href="https://developers.google.com/protocol-buffers">Protocol Buffers</a></li></ul><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/understanding-protocol-buffers-protobuf"><em>https://blog.danielpadua.dev</em></a><em> on November 24, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a466d8943df8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/understanding-protocol-buffers-protobuf-a466d8943df8">Understanding Protocol Buffers — protobuf</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entendendo Protocol Buffers — Protobuf]]></title>
            <link>https://medium.com/danielpadua/entendendo-protocol-buffers-protobuf-7c9ad6ed0043?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c9ad6ed0043</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 03:04:31 GMT</pubDate>
            <atom:updated>2021-07-12T00:27:37.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>Entendendo Protocol Buffers — Protobuf</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUG6wMZniIxMiuwJP5x60w.png" /></figure><h3>Introdução</h3><p>Protocol Buffers (protobuf) é um método de serializar dados estruturados que é principalmente útil para comunicação entre serviços ou até mesmo para guardar dados. Ele foi desenhado pelo Google no começo de 2001 (mas apenas publicamente liberado em 2008) para ser menor e mais rápido que o XML. As mensagens protobuf são serializadas em um formato <a href="https://developers.google.com/protocol-buffers/docs/encoding"><em>binary wire</em></a> que é muito compacto, aumentando a performance.</p><h3>Detalhes</h3><p>Este protocolo envolve uma <a href="https://pt.wikipedia.org/wiki/Linguagem_de_descri%C3%A7%C3%A3o_de_interface">linguagem de descrição de interface</a> específica para modelar a estrutura de dados definido em um arquivo <em>.proto<br></em>Um programa de qualquer linguagem suportada consegue gerar através de um compilador código fonte nativo utilizando o contrato afim de criar ou interpretar <em>streams </em>de bytes que representam os dados estruturados.<br>Protocol buffers normalmente serve como base para <em>remote procedure call </em>(RPC) que é muito usada para comunicação de aplicações entre diferentes máquinas, o mais comumente utilizado é o <a href="https://grpc.io/">gRPC</a>. Protobuf é similar ao <a href="https://thrift.apache.org/">Apache Thrift</a> usado pelo Facebook, <a href="https://amzn.github.io/ion-docs/">Ion</a> criado pela Amazon ou o <a href="https://microsoft.github.io/bond/manual/bond_cs.html">Microsoft Bonds Protocol</a>.</p><h3>Exemplo</h3><p>Neste exemplo nós iremos criar dois projetos:</p><ul><li>Uma aplicação console Java que irá utilizar uma especificação .proto de um cliente (<em>customer.proto</em>) para gerar um arquivo com um cliente <em>hard coded</em></li><li>Uma aplicação console C# que irá ler o arquivo do cliente <em>hard coded</em> gerado pela aplicação java e exibir os dados no console</li></ul><h4>Resumo</h4><p>Caso você apenas queira ler o código e ir descobrindo e aprendendo por conta própria, disponibilizei repositório com estas duas aplicações. Primeiramente siga as instruções do arquivo README_pt.md do projeto Java no repositório:</p><p><a href="https://github.com/danielpadua/protobuf-example-java">danielpadua/protobuf-example-java</a></p><p>Após gerar o arquivo serializado com protobuf, siga as instruções do arquivo README_pt.md do projeto C# no repositório:</p><p><a href="https://github.com/danielpadua/protobuf-example-csharp">danielpadua/protobuf-example-csharp</a></p><h4>Contrato Protobuf</h4><p>Primeiro de tudo, vamos criar uma estrutura que irá representar um cliente. Os dados que precisamos representar são:</p><ul><li>Identificação única (ID)</li><li>Foto</li><li>Nome</li><li>Data de nascimento</li><li>Data/Hora de criação</li><li>Data/Hora da última atualização</li></ul><p>Portanto, será necessário criar um arquivo <em>.proto</em> como este:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5678cfb94191d1d2c8aa4c96245060e6/href">https://medium.com/media/5678cfb94191d1d2c8aa4c96245060e6/href</a></iframe><p>Alguns pontos sobre o código acima:</p><ul><li>O tipo <em>Timestamp </em>é um &quot;<a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">Well Known Type</a>&quot; que foi introduzido no proto3, você pode utilizar estes tipos apenas importando-os nas primeiras linhas do arquivo proto</li><li>Os tipos <em>Date</em> e <em>Money</em> são &quot;Google Common Type&quot;, diferentes do &quot;Well Known Type&quot; não é possível usá-los apenas realizando a importação. É necessário copiar o conteúdo destes arquivos do <a href="https://github.com/googleapis/googleapis/tree/master/google/type">repositório do google</a> e colar no seu projeto, qualquer que seja a linguagem que está utilizando.</li></ul><p>Existem outros tipos, você pode ler a documentação <a href="https://developers.google.com/protocol-buffers/docs/proto3#scalar">aqui</a>. Dos Well Known Types <a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">aqui</a> e do Google Common Types <a href="https://github.com/googleapis/googleapis/tree/master/google/type">aqui</a>.</p><p>Este arquivo <em>.proto</em> será um recurso em comum entre os projetos C# e Java, mas para simplificar o exemplo, irei recriá-lo nos repositórios de ambos projetos. O ideal para projetos grandes e complexos seria ter um repositório separado como um ponto único para os projetos que irão utilizá-lo.</p><h4>Aplicação Java Console</h4><p>Com isto explicado, vamos começar a criar uma aplicação Java console. Para este exemplo irei utilizar a OpenJDK 15, IntelliJ IDEA CE e o Maven como <em>build tool</em>.</p><ol><li>Abra o IntelliJ IDEA CE and escolha criar um novo projeto</li></ol><figure><img alt="Uma imagem que mostra a tela inicial do IntelliJ IDEA Community, com a opção de novo projeto destacada" src="https://cdn-images-1.medium.com/max/1024/1*17Em58qNICvk3KRcATN7Vg.png" /><figcaption>Criando um novo projeto</figcaption></figure><p>2. Escolha Maven no painel esquerdo, selecione sua Java JDK no canto superior direito. Como disse anteriormente, irei utilizar a OpenJDK 15 que havia instalado anteriormente</p><figure><img alt="Uma imagem da tela que o IntelliJ exibe para escolher a build tool, com Maven selecionado e o arquétipo padrão" src="https://cdn-images-1.medium.com/max/800/1*hcTI8rHKE-xUe0IwF5c6qg.png" /><figcaption>Detalhes do novo projeto</figcaption></figure><p>3. Preencha os próximos campos como desejar, por exemplo:</p><figure><img alt="Uma imagem exibindo as configurações do maven a preencher, como: localização do projeto, groupid, artifactid e versão" src="https://cdn-images-1.medium.com/max/801/1*uqmuSBQm15XL0YxQ51DpfQ.png" /><figcaption>Configurações maven do projeto</figcaption></figure><p>Projeto criado. Vamos começar adicionando o <em>encoding</em> do código fonte, informar ao compilador maven que estaremos utilizando a JDK 15 e adicionando a dependência <a href="https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java">protobuf-java</a> feita pelo Google. Adicione as linhas a seguir no arquivo <em>pom.xml</em> dentro da tag &quot;projeto&quot;, logo após a tag &quot;version&quot;:</p><pre>&lt;properties&gt;<br>    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>    &lt;maven.compiler.source&gt;15&lt;/maven.compiler.source&gt;<br>    &lt;maven.compiler.target&gt;15&lt;/maven.compiler.target&gt;<br>&lt;/properties&gt;</pre><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt;<br>        &lt;artifactId&gt;protobuf-java&lt;/artifactId&gt;<br>        &lt;version&gt;3.13.0&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Agora, vamos incluir os arquivos <em>.proto</em> definidos na seção acima. Mas antes crie um diretório &quot;proto&quot; dentro de <em>src/main</em>:</p><figure><img alt="Uma imagem da ação de abrir o menu de contexto do IntelliJ para criar o diretório dentro de src/main" src="https://cdn-images-1.medium.com/max/1024/1*CLWLk_uM2W7VIzXxzjR5tw.png" /><figcaption>Criando o diretório dos arquivos protobuf</figcaption></figure><p>Depois adicione um novo arquivo chamado: <em>customer.proto </em>e coloque o código mencionado na seção acima:</p><figure><img alt="Uma imagem mostrando o arquivo protobuf customer com um erro de compilação" src="https://cdn-images-1.medium.com/max/1024/1*Y1QFo7b62foOWM9YTq4BoQ.png" /><figcaption>Erro ao importar outros arquivos protobuf</figcaption></figure><p>Os imports do <em>money.proto</em> e <em>date.proto</em> irão mostrar erro porque ainda não os criamos. Você pode criá-los repetindo o procedimento acima adicionando o código do <a href="https://github.com/googleapis/googleapis/blob/master/google/type/money.proto">money.proto</a> e <a href="https://github.com/googleapis/googleapis/blob/master/google/type/date.proto">date.proto</a> diretamente do repositório do Google.</p><figure><img alt="Uma imagem exibindo o arquivo customer.proto sem erros de compilação" src="https://cdn-images-1.medium.com/max/1024/1*ssROPsHwq0OzGlNYdvT3DQ.png" /><figcaption>customer.proto sem erros</figcaption></figure><p>Ok, contratos protobuf criados. Agora, para gerarmos o código fonte nativo (classes java) a partir do contrato, nós precisamos usar o executável <em>protoc </em>para compilar os arquivos <em>.proto</em> apontando a linguagem desejada de saída. Existem duas maneiras principais de fazer isto:</p><ul><li>Manualmente, baixando o <em>protoc</em> na sua máquina e executando-o. Caso você deseje ir por este caminho, leia o guia de instalação do protoc <a href="https://grpc.io/docs/protoc-installation/">aqui</a></li><li>Automaticamente, adicionando geração de código via <em>protoc</em> no build do seu projeto maven. Existem alguns plugins maven para isto, mas irei utilizar o <a href="https://github.com/os72/protoc-jar-maven-plugin"><em>protoc-jar-maven-plugin</em></a>, que envolve o executável do <em>protoc</em> como um <em>jar</em> assim ele pode ser executado em qualquer SO e então compilar seus arquivos <em>.proto</em>.</li></ul><p>Você pode começar a utilizá-lo apenas adicionando as linhas abaixo no seu <em>pom.xml </em>abaixo da tag &quot;project&quot;, logo após a tag &quot;dependencies&quot;:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;com.github.os72&lt;/groupId&gt;<br>            &lt;artifactId&gt;protoc-jar-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;3.11.4&lt;/version&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;id&gt;protoc.main&lt;/id&gt;<br>                    &lt;phase&gt;generate-sources&lt;/phase&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;run&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                    &lt;configuration&gt;<br>                        &lt;protocVersion&gt;3.13.0&lt;/protocVersion&gt;<br>                        &lt;addSources&gt;main&lt;/addSources&gt;<br>                        &lt;includeMavenTypes&gt;direct&lt;/includeMavenTypes&gt;<br>                        &lt;includeStdTypes&gt;true&lt;/includeStdTypes&gt;<br>                        &lt;includeDirectories&gt;<br>                            &lt;include&gt;src/main/proto&lt;/include&gt;<br>                        &lt;/includeDirectories&gt;<br>                        &lt;inputDirectories&gt;<br>                            &lt;include&gt;src/main/proto&lt;/include&gt;<br>                        &lt;/inputDirectories&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><blockquote>Sempre verifique se existem novas versões estáveis antes de adicionar dependências ou plugins em seu pom.xml</blockquote><p>Nós estamos adicionando a estrutura de diretório onde estamos armazenando os arquivo <em>.proto</em>, assim o plugin saberá onde eles estão para compilá-los.</p><p>Neste ponto é provável que você queira executar o compilador <em>protoc </em>para gerar as classes java que representam os contratos protobuf, então, clique na tab maven e depois no botão &quot;run maven goal&quot; e escreva: mvn clean install</p><figure><img alt="Uma imagem mostrando o maven integrado ao IntelliJ pronto para executar o goal clean install" src="https://cdn-images-1.medium.com/max/1024/1*ABjjiWb0KzvZrhF__BCsmg.png" /><figcaption>Executando maven clean install</figcaption></figure><p>Caso a compilação tenha sucesso, a mensagem a seguir irá ser exibida:</p><figure><img alt="Uma imagem mostrando que o projeto foi compilado corretamente" src="https://cdn-images-1.medium.com/max/1024/1*njc8VvjbVGwtW6rNQUf4OQ.png" /><figcaption>Um build de sucesso</figcaption></figure><p>Próximo passo é criar um pacote &quot;dev.danielpadua.protobufexamplejava&quot; e dentro do mesmo uma classe principal para nossa aplicação console:</p><figure><img alt="Uma imagem mostrando a classe Program com o método main vazio" src="https://cdn-images-1.medium.com/max/1024/1*9btxrsbY2A9GcbDc2abbfA.png" /><figcaption>Nosso método main</figcaption></figure><p>Caso você digite “Customer”, o autocomplete do IntelliJ irá aparecer e te sugerir importar a classe gerada pelo <em>protoc</em> via plugin:</p><figure><img alt="Uma imagem mostrando o autocomplete do IntelliJ reconhecendo com sucesso as classes auto-geradas" src="https://cdn-images-1.medium.com/max/693/1*rvtMa_L3M41CFgb1P2Onfg.png" /><figcaption>Sucesso ao auto-completar classes geradas</figcaption></figure><p>Então, deu tudo certo. Agora nós podemos escrever o código para gerar o cliente <em>hard coded </em>e gravá-lo no diretório que você desejar (dentro do método main):</p><pre>Date birthdate = Utils.<em>toGoogleDate</em>(LocalDate.<em>of</em>(1990<strong>, </strong>4<strong>, </strong>30))<strong>;<br></strong>Money balance = Utils.<em>toGoogleMoney</em>(BigDecimal.<em>valueOf</em>(9000.53))<strong>;<br></strong>Timestamp createdUpdateAt = Utils.<em>toGoogleTimestampUTC</em>(LocalDateTime.<em>now</em>())<strong>;<br></strong>String fullPath = &quot;/Users/danielpadua/protobuf/protobuf-customer&quot;<strong>;</strong></pre><pre>try (FileOutputStream fos = new FileOutputStream(fullPath)) {<br>    Customer daniel = Customer.<em>newBuilder</em>()<br>            .setId(1)<br>            .setPhoto(ByteString.<em>EMPTY</em>)<br>            .setName(&quot;Daniel&quot;)<br>            .setBirthdate(birthdate)<br>            .setBalance(balance)<br>            .setCreatedAt(createdUpdateAt)<br>            .setUpdatedAt(createdUpdateAt)<br>            .build()<strong>;</strong></pre><pre><strong>    </strong>daniel.writeTo(fos)<strong>;<br>    </strong>System.<em>out</em>.println(&quot;protobuf-customer created successfully&quot;)<strong>;<br></strong>} catch (FileNotFoundException e) {<br>    System.<em>out</em>.println(<em>format</em>(&quot;could not find file {0}&quot;<strong>, </strong>fullPath))<strong>;<br></strong>} catch (IOException e) {<br>    System.<em>out</em>.println(<em>format</em>(&quot;error while reading file {0}. exception: {1}&quot;<strong>, </strong>fullPath<strong>, </strong>e.getMessage()))<strong>;<br></strong>}</pre><p>Note que o código acima faz uso de uma classe Utils para converter os tipos: Java LocalDate para Google Date, Java BigDecimal para Google Money e Java LocalDateTime para Google Timestamp. Você pode incluir minha classe Utils no seu projeto copiando o código a seguir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a8a9bc00fc94795871f5e920e5b4d2/href">https://medium.com/media/33a8a9bc00fc94795871f5e920e5b4d2/href</a></iframe><p>Caso você tenha o problema a seguir no IntelliJ, você pode simplesmente utilizar a sugestão sugerida: “Set language level to 8 — Lambdas, type annotations etc”:</p><figure><img alt="Uma image mostrando o erro de language level no IntelliJ IDEA Community" src="https://cdn-images-1.medium.com/max/1024/1*CPBWe-3HHvstfWDsrKRmSg.png" /><figcaption>Language level no IntelliJ IDEA</figcaption></figure><p>Agora podemos executar a aplicação. Clique no botão “Add Configuration” localizado no canto superior direito, ao lado do botão de build. Clique no botão com o sinal de soma e selecione “Application”:</p><figure><img alt="Uma imagem mostrando o popup para criação de uma run configuration para rodar a aplicação no IntelliJ IDEA" src="https://cdn-images-1.medium.com/max/1024/1*jlbb3QA6lm9Z8ivdaGUo0Q.png" /><figcaption>Criando uma run configuration</figcaption></figure><p>Então preencha o nome da configuração e selecione a classe principal a ser executada:</p><figure><img alt="Uma imagem mostrando os últimos campos a serem preenchidos para criar uma configuração de execução" src="https://cdn-images-1.medium.com/max/1024/1*cbmSFUW94OV3oWeUUtLRiA.png" /><figcaption>Últimos campos para preencher antes de executar</figcaption></figure><p>Depois, clique no botão executar ou debugar caso você queira:</p><figure><img alt="Uma imagem exibindo a configuração criada, e os botões de executar e debugar" src="https://cdn-images-1.medium.com/max/328/1*NNxfdVyLInIH0x3u0adpbw.png" /><figcaption>Vamos rodar!</figcaption></figure><p>Um resultado de sucesso deve exibir a mensagem a seguir:</p><figure><img alt="Uma imagem mostrando o resultado depois de executar a aplicação com sucesso gerando o arquivo protobuf" src="https://cdn-images-1.medium.com/max/1024/1*Bp8TSXQOJ5uzsAE_JsbrnQ.png" /><figcaption>Arquivo protobuf criado com sucesso</figcaption></figure><p>Agora verifique o diretório que você definiu como saída para o arquivo:</p><figure><img alt="Uma imagem mostrando o finder do macOs com o arquivo protobuf-customer gerado pela aplicação java" src="https://cdn-images-1.medium.com/max/772/1*fZluGGppS0iRv9-m9nByXQ.png" /><figcaption>Sucesso!</figcaption></figure><p>Nós implementamos com sucesso uma simples aplicação console Java que cria uma mensagem protobuf utilizando uma estrutura definida em um arquivo <em>.proto</em>, através de um processo de compilação automatizado e integrado ao build maven. Agora para provar que é útil para comunicação entre projetos de diferentes linguagens, iremos criar uma aplicação console C# para ler este arquivo e mostrar os dados no console.</p><h4>Aplicação Console C#</h4><p>Para o examplo do C# irei utilizar: .NET 5, Visual Studio Code e o pacote <a href="https://www.nuget.org/packages/Grpc.AspNetCore">Grpc.AspNetCore</a> que contém um compilador de protobuf é embutido ao dotnet build.</p><p>Abra o Visual Studio Code, abra o terminal integrado, navegue até o diretório onde você deseja guardar o projeto e execute os comandos a seguir, linha a linha:</p><pre>mkdir protobuf-example-csharp<br>cd protobuf-example-csharp<br>dotnet new console -o src/DanielPadua.ProtobufExampleCsharp<br>dotnet new xunit -o tests/DanielPadua.ProtobufExampleCsharp.Tests<br>dotnet new sln -n DanielPadua.ProtobufExampleCsharp<br>dotnet sln add src/DanielPadua.ProtobufExampleCsharp/DanielPadua.ProtobufExampleCsharp.csproj<br>dotnet sln add tests/DanielPadua.ProtobufExampleCsharp.Tests/DanielPadua.ProtobufExampleCsharp.Tests.csproj</pre><p>Feito, projeto criado, agora vamos abri-lo no Visual Studio Code:</p><figure><img alt="Uma imagem mostrando o Visual Studio Code com o menu Open e o terminal abertos" src="https://cdn-images-1.medium.com/max/1024/1*l09ZHKsGLo9lw3SNuvjlqw.png" /><figcaption>Selecione a pasta raíz (a mesma que você está no terminal)</figcaption></figure><p>A estrutura do projeto deve ser como esta:</p><figure><img alt="Uma iamgem mostrando o questionamento do Visual Studio Code sobre auto gerar os assets de build debug para o projeto" src="https://cdn-images-1.medium.com/max/1024/1*yTlZEfcg8hUgKH8hZ6xIgg.png" /><figcaption>Adicione os assets para fazer build e debug</figcaption></figure><p>Clique no “Yes” na mensagem no canto inferior direito, para que o <em>Omnisharp</em> crie a pasta <em>.vscode</em> com os assets para executar/debugar o projeto. Selecione “DanielPadua.ProtobufExampleCsharp”:</p><figure><img alt="Uma imagem mostrando o Visual Studio Code questionando sobre qual projeto ele deve criar os assets de build debug" src="https://cdn-images-1.medium.com/max/1024/1*CVbp64avVU3Fm98iwJayCg.png" /><figcaption>Escolha o projeto para gerar os assets</figcaption></figure><p>Abra o terminal novamente no nível <em>src/DanielPadua.ProtobufExampleCsharp </em>e execute:</p><pre>dotnet add package Grpc.AspNetCore</pre><p>Agora vamos incluir os contratos <em>.proto</em>. Crie um diretório abaixo da raíz do projeto principal e nomeie-o como: “Protos” e crie os arquivos <em>.proto </em>listados na seção acima:</p><figure><img alt="Uma imagem mostrando a estrutura do projeto no Visual Studio Code e os arquivos protobuf criados corretamente" src="https://cdn-images-1.medium.com/max/1024/1*EyoXas9nfZ_a-08VmmASEA.png" /><figcaption>Arquivos protobuf criados</figcaption></figure><p>Adicione os arquivos <em>.proto</em> no <em>.csproj </em>para que o <em>protoc</em> compile quando o dotnet build rodar:</p><figure><img alt="Uma imagem mostrando o código do csproj adicionando o caminho dos arquivos protobuf recém criados" src="https://cdn-images-1.medium.com/max/1024/1*Fe6p88-T-r6xo1glu50kTg.png" /><figcaption>Adicionando o caminho dos arquivos protobuf para o plugin compilar</figcaption></figure><p>Agora vamos compilar o projeto para gerar as classes C# a partir dos contratos <em>.proto</em>. No terminal, execute:</p><pre>dotnet build</pre><p>A mensagem de um build de sucesso deve ser algo como isto:</p><figure><img alt="Uma imagem mostrando o terminal integrado ao Visual Studio Code com a saída indicando que o build obteve sucesso" src="https://cdn-images-1.medium.com/max/1024/1*sHRAETo2_dmn2yasgBi5-Q.png" /><figcaption>Dotnet build ok</figcaption></figure><p>Próximo passo é substituir o “Hello World” no método Main pelas linhas a seguir:</p><pre>var fullpath = @&quot;/Users/danielpadua/protobuf/protobuf-customer&quot;;<br>using var inputStream = File.OpenRead(fullpath);<br><em>Customer</em> c = Customer.Parser.ParseFrom(inputStream);<br>Console.WriteLine(&quot;Customer from protobuf-example-java:&quot;);<br>Console.WriteLine(c.ToString());</pre><p>Agora você deve tentar importar o namespace &quot;Contracts&quot;, pressione ctrl+. (windows, linux) or cmd+. (macOs) para abrir o autocomplete, e então a opção de importar irá aparecer:</p><figure><img alt="Uma imagem mostrando o intellisense do Visual Studio Code importando os contratos protobuf com sucesso" src="https://cdn-images-1.medium.com/max/1024/1*9fYewZBlCnYTURJqy_OB-w.png" /><figcaption>Intellisense e a geração de código protobuf funcionando</figcaption></figure><p>Caso a opção de importar não aparece, tente reiniciar o Omnisharp usando: ctrl+shift+p (windows, linux) or cmd+shift+p (macOs), digite: restart omnisharpe aperte o enter:</p><figure><img alt="Uma imagem mostrando o command palette do Visual Studio Code com a opção de reiniciar o omnisharp selecionada" src="https://cdn-images-1.medium.com/max/1024/1*u5J2RQwVv4n5ZPcPXpJilA.png" /><figcaption>Espere por um momento antes de tentar importar novamente</figcaption></figure><p>Infelizmente a integração do Omnisharp com o compilador de protobuf não é perfeita, mas funciona.</p><p>Garanta que você está lendo o mesmo diretório e arquivo que o projeto Java gerou, e então rode sua aplicação console C# apertando o botão de executar do Visual Studio Code (caso você tenha configurado os assets de execução/debug corretamente) ou simplesmente rodando a linha de comando: dotnet run estando no diretório raíz do projeto principal:</p><figure><img alt="Uma imagem mostrando o terminal integrado do Visual Studio Code com o comando dotnet run indicando sucesso" src="https://cdn-images-1.medium.com/max/1024/1*yAm8a9LM9dNDu_FFWxMubA.png" /><figcaption>Executando do terminal</figcaption></figure><figure><img alt="Uma imagem mostrando a aba de executar ou debugar do Visual Studio Code, indicando sucesso" src="https://cdn-images-1.medium.com/max/1024/1*bozD_lrkfER-_aEzEomINA.png" /><figcaption>Executando do Visual Studio Code</figcaption></figure><p>E, nós conseguimos. Recebemos e interpretamos uma mensagem serializada em protobuf gerada por uma aplicação Java, dentro de uma aplicação C#.</p><h3>Conclusão</h3><p>Protobuf foi feito para ser mais rápido, mais leve e consequentemente mais performático do que outros protocolos. Então, te convido a fazer uma breve pesquisa como: &quot;protobuf vs json performance&quot; ou alguma outra, para ver benchmarks e outros cases de sucesso mundo afora.</p><p>Neste artigo espero ter dado um bom mergulho para aqueles que, como eu há um tempo atrás, não haviam nem ouvido falar sobre protobuf e sempre utilizaram JSON ou XML para serialização.</p><p>Até a próxima!</p><h3>Referencias</h3><ul><li><a href="https://en.wikipedia.org/wiki/Protocol_Buffers">Protocol Buffers - Wikipedia</a></li><li><a href="https://developers.google.com/protocol-buffers">Protocol Buffers</a></li></ul><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>Caso tenha achado que esse post foi útil e quiser me apoiar, você pode fazer isto me pagando um café usando o botão acima!</figcaption></figure><p><em>Publicado originalmente em </em><a href="https://blog.danielpadua.dev/pt/posts/entendendo-protocol-buffers-protobuf"><em>https://blog.danielpadua.dev</em></a><em> 24 de Novembro de 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c9ad6ed0043" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/entendendo-protocol-buffers-protobuf-7c9ad6ed0043">Entendendo Protocol Buffers — Protobuf</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Azure Functions + Vscode]]></title>
            <link>https://medium.com/danielpadua/introduction-to-azure-functions-vscode-e86614c04db3?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86614c04db3</guid>
            <category><![CDATA[english]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[azure-functions]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 17:57:40 GMT</pubDate>
            <atom:updated>2021-07-12T00:26:22.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Azure Functions logo with a plus sign and Visual Studio Code logo" src="https://cdn-images-1.medium.com/max/1024/1*e0_KX-4Q6x7HPfKeO0w9Pw.png" /></figure><h3>Intro</h3><p>As a developer I was able to notice some significant transformation in the IT market, for instance:</p><ul><li>A big migration movement from structured to object oriented programming paradigm.</li><li>More emphasis in web development instead of desktop.</li><li>Creation and vertiginous rise of mobile apps development.</li><li>More people switching from vertical scalability to horizontal with the appearance of cloud computing.</li><li>Microservices architecture adoption instead of monolithic architecture.</li></ul><p>And recently, actually in a while, I have noticed there is a huge adoption of <a href="https://en.wikipedia.org/wiki/Serverless_computing"><em>serverless</em></a><em> </em>architecture to new and modern applications, in many cases even replacing microservices.</p><p>Serverless is capable of providing more easiness, flexibility, automatic scalability and even other benefits similar to microservices. However, the biggest differences between them in my opinion are the easiness and cost reduction.</p><p>With serverless you don&#39;t have to worry to configure and manage a server to your app, even less worrying about how to scale it. You just have to focus in your core problem solving with the code you write, this speeds up a lot releasing new features or products. And in most cloud providers, you just have to pay for what you use, so this provides a significant cost reduction compared to an instance that is always on, even if there is no load to process.</p><p>In this introductory article I will approach in how to begin serverless development in Microsoft Azure plataform, using vscode as code editor to develop and deploy a simple function that will return a &quot;Hello World&quot; after a HTTP action with GET or POST verb.</p><h3>Requirerements</h3><ul><li><a href="https://code.visualstudio.com/download">Visual Studio Code</a></li><li><a href="https://azure.microsoft.com/en-us/free/">Azure account</a></li></ul><h3>Setup the development environment</h3><p>To effectively work with functions it is minimally required to setup a local development environment which we can write, run and debug. Use the sections below according to you operating system.</p><h4>Windows</h4><p><strong>1. Install NodeJs</strong></p><p>In this article, we will work with Azure Function version 3.x, <strong>so we must install NodeJs versions 10.x.x or 12.x.x</strong>. If there for any reason you want to use version 2.x then use NodeJs 8.x.x.</p><blockquote>There is an incompatibility in Windows with NodeJs version ≥ 13.x.x and Core Tools 3.x, so for now, use the versions listed above. (<a href="https://github.com/Azure/azure-functions-core-tools/issues/1804">https://github.com/Azure/azure-functions-core-tools/issues/1804</a>)</blockquote><p>There are several ways of doing this:</p><ul><li><a href="https://nodejs.org/dist/">Direct installing from NodeJs website</a>: choose from the list one of the versions specified above and look for an installer with the suffix &quot;<strong>win-x64</strong>&quot;, if this point in 2020 the architecture of the machine you are on is not 64 bits, then look for suffix &quot;<strong>win-x86</strong>&quot; for 32 bits architectures.</li><li>Installing NVM via package manager: <a href="https://github.com/nvm-sh/nvm">NVM</a> is a command line program that has a feature of managing more easily multiple NodeJs versions at the same time. Using for example: <a href="https://medium.com/danielpadua/using-chocolatey-for-windows-878290cfb58d">Chocolatey for Windows</a> we can install nvm through command line: <strong>choco install nvm</strong>, and after install one of the versions above with: <strong>nvm install &lt;version&gt;</strong> then you can link it in use with: <strong>nvm use &lt;version&gt;</strong>.</li></ul><p><strong>2. Install Azure Core Tools</strong></p><p>It is this guy that allow us to create a local execution environment for your function so you can run them via command line. It is even capable of communicating with real Azure resources, which it is not recommended, because completely separate the environments are more correct, but it works.</p><p>The installation in Windows is through NodeJs, running the following command line in PowerShell or cmd:</p><pre>npm install -g azure-functions-core-tools@3</pre><p>If you want to install version 2.x, you would have to run this instead:</p><pre>npm install -g azure-functions-core-tools</pre><p>After installing, try the installation only by running:</p><pre>func --version</pre><p>If it displayed an error similar to this:</p><figure><img alt="A PowerShell terminal with &#39;func&#39; command being executed and about_Execution_Policies error being displayed" src="https://cdn-images-1.medium.com/max/856/1*foMuyEpCKtQrpmqQb_oPRw.png" /><figcaption>NodeJs Scripts execution permission error</figcaption></figure><p>Run the following command line in PowerShell as administrator, so the scripts that are installed via NodeJs can be executed:</p><pre>Set-ExecutionPolicy RemoteSigned</pre><p>If there is an error similar to: &quot;<strong>Unhandled &#39;error&#39; event</strong>&quot;, it is likely that there is an incompatibility between Core Tools and NodeJs. Redo the step above.</p><h4>MacOs</h4><p><strong>1. Install NodeJs</strong></p><p>In this article, we will work with Azure Function version 3.x, <strong>so we must install NodeJs versions 10.x.x or 12.x.x</strong>. If there for any reason you want to use version 2.x then use NodeJs 8.x.x.</p><p>There are several ways of doing this:</p><ul><li><a href="https://nodejs.org/dist/">Direct installing from NodeJs website</a>: choose from the list one of the versions specified above and look for an installer with the extension name “<strong>.pkg</strong>” and do <strong>NNF</strong> installation (next, next, finish).</li><li>Installing NVM via package manager: <a href="https://github.com/nvm-sh/nvm">NVM</a> is a command line program that has a feature of managing more easily multiple NodeJs versions at the same time. Using for example: <a href="https://medium.com/danielpadua/using-homebrew-for-macos-aa34b2e0c90c">Homebrew for MacOs</a> we can install nvm through command line: <strong>brew install nvm</strong>, and after install one of the versions above with: <strong>nvm install &lt;version&gt;</strong> then you can link it in use with: <strong>nvm use &lt;version&gt;.</strong></li></ul><p><strong>2. Install Azure Core Tools</strong></p><p>It is this guy that allow us to create a local execution environment for your function so you can run them via command line. It is even capable of communicating with real Azure resources, which it is not recommended, because completely separate the environments are more correct, but it works.</p><p>Install version 3.x using Homebrew with the command lines:</p><pre>brew tap azure/functions<br>brew install azure-functions-core-tools@3<br># run the line below if you are upgrading version 2.x to 3.x in your machine<br>brew link --overwrite azure-functions-core-tools@3</pre><p>For version 2.x use the command lines:</p><pre>brew tap azure/functions<br>brew install azure-functions-core-tools</pre><p>Finally, test it with the command line:</p><pre>func --version</pre><h4>Linux</h4><p><strong>1. Install NodeJs</strong></p><p>In this article, we will work with Azure Function version 3.x, <strong>so we must install NodeJs versions 10.x.x or 12.x.x</strong>. If there for any reason you want to use version 2.x then use NodeJs 8.x.x.</p><p>There are several ways of doing this:</p><ul><li><a href="https://nodejs.org/dist/">Direct installing from NodeJs website</a>: choose from the list one of the versions specified above and look for an installer with the suffix “<strong>.linux-x64.tar.gz</strong>”, download it, extract in an easy access directory and create a symbolic link to file: &quot;<strong>/bin/node&quot;.</strong></li><li>Installing NVM via package manager: <a href="https://github.com/nvm-sh/nvm">NVM</a> is a command line program that has a feature of managing more easily multiple NodeJs versions at the same time. Use your distro package manager to install NVM and then install one of the versions above with: <strong>nvm install &lt;version&gt;</strong>, and link it in use with: <strong>nvm use &lt;version&gt;</strong>.</li></ul><p><strong>2. Install Azure Core Tools</strong></p><p>It is this guy that allow us to create a local execution environment for your function so you can run them via command line. It is even capable of communicating with real Azure resources, which it is not recommended, because completely separate the environments are more correct, but it works.</p><p>If your distro is Debian based, you can use this <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=linux#v2">Microsoft guide</a> to install Core Tools. If is another distro, check <a href="https://github.com/Azure/azure-functions-core-tools/blob/master/README.md#linux">Core Tools README</a> to install.</p><p>Finally, test Core Tools with the command line:</p><pre>func --version</pre><h4>Install Azure Functions plugin in vscode</h4><p>Open <strong>Extensions</strong> and look for: <strong>Azure Functions </strong>or <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions">use this link</a>.</p><figure><img alt="Visual Studio Code extension installation  window with Azure Functions about to be installed" src="https://cdn-images-1.medium.com/max/1024/1*lglDm88O_1WdufH1Hz_mkw.png" /><figcaption>Installing Azure Functions plugin in vscode</figcaption></figure><p>After the installation, restart vscode and confirm that a Azure Account plugin was installed alongside Azure Functions plugin. Sign in to your Azure Account as the image below:</p><figure><img alt="Azure toolbox being displayed in Visual Studio Code and a arrow pointing to “Sign in to Azure” button" src="https://cdn-images-1.medium.com/max/564/1*75E7rKBDG76yEUHtaOPa_Q.png" /><figcaption>Signing in Azure Account</figcaption></figure><p>You should be redirected to Microsoft login page in your default browser. After that, return to vscode and your Azure resources will be displayed in the editor.</p><h3>Creating and debugging locally a function</h3><p>Now, the development environment is ready, lets create our simple Hello World function. To do this, in vscode initial screen, use the keys combination: Ctrl+Shift+P (Windows or Linux) or Cmd+Shift+P (MacOs). The command palette should open. Start typing: <strong>functions create new project</strong>:</p><figure><img alt="Azure Functions command palette with searchbox containing: &quot;function create new project&quot;" src="https://cdn-images-1.medium.com/max/1024/1*evNxZLOqrJRcFsG0XwYesA.png" /><figcaption>Creating a functions project</figcaption></figure><p>One function project is capable of nesting N different types functions triggered by: Http, time, queue and others.</p><p>If you are not with an open directory in vscode, you will be asked to open one. Create a directory where we will keep our project source and select it. After, you will be asked in what language you would like to develop, for this example we will stick with <strong>Javascript</strong>:</p><figure><img alt="Azure Functions create project window with searchbox containing: &quot;Javascript&quot;" src="https://cdn-images-1.medium.com/max/1024/1*hYcBkYDA50beItKnUUQZNw.png" /><figcaption>Choose a development language to your function</figcaption></figure><p>Your next question is: Would I be using a function template according to the trigger type that will fire it? Again, to our example, we will stick to a Http trigger:</p><figure><img alt="Azure Functions create project window with searchbox containing: “Http Trigger”" src="https://cdn-images-1.medium.com/max/1024/1*cIaaLv-DqQ9Zi8mcUpDBjw.png" /><figcaption>Http Trigger function template</figcaption></figure><p>The next step consists only about giving a name to our function, I tend to use the nomenclature: <strong>name_TriggerType</strong>, for me to know the trigger type immediately. But you can use whatever pattern you are more comfortable with.</p><p>Now, select the authorization level of the function. There are 3 authorization types:</p><ul><li><strong>Function</strong>: There is an access key created by default in Azure Portal when you deploy a function, that can be used to authenticate calls to your endpoints. You can pass it though Query String or Header parameter of your Http request. If this parameter is not filled or it is incorrect, the function will automatically return Http status 401 — Unauthorized.</li><li><strong>Anonymous</strong>: As the name itself, no authorization, your endpoints are exposed and can be called without any kind of authentication/authorization.</li><li><strong>Admin</strong>: As there is key with function level, there is a key called <strong>host key</strong>, also created by Azure. Only with this key your access to the endpoint will work, if the parameter it is not informed or incorrect this method will also return Http status 401 — Unauthorized.</li></ul><p>Lastly, select the project in the same window, if you are not already with a directory opened.</p><p>Your project after the creation must look like this:</p><figure><img alt="Index.js file contents being displayed in Visual Studio Code window" src="https://cdn-images-1.medium.com/max/1024/1*TUjoaCaksCE-YDfvOl4a3Q.png" /><figcaption>Directory structure of a javascript function project</figcaption></figure><p>For javascript the functions are always separated in directories with 3 files:</p><ul><li><strong>functions.json</strong></li></ul><figure><img alt="Function.json file contents being displayed in Visual Studio Code window" src="https://cdn-images-1.medium.com/max/806/1*5jfPpdg8r04RziFQ6-842w.png" /><figcaption>function.json</figcaption></figure><p>This file is responsible of telling Azure which bindings we will use. Bindings are a way of connecting with an Azure resource, like a queue, topic, database, http action and others with a function, and this binding may have a direction (input or output).</p><p>For example, the first object consist in a specific configuration for a http triggered function where the direction is <strong>in</strong>, which means, it is coming to your function via verbs: <strong>get </strong>or <strong>post</strong> through a parameter named <strong>req</strong>. And the second object is the return &quot;<strong>out</strong>&quot; of the http type, that can be accessed through parameter <strong>res</strong>.</p><ul><li><strong>index.js</strong></li></ul><figure><img alt="Index.js code being displayed in Visual Studio Code window" src="https://cdn-images-1.medium.com/max/1024/1*X0LdPDqu7ww08G8Gnz_ktw.png" /><figcaption>index.js</figcaption></figure><p>It is this file that will contain the logic of your function, where you will be able to develop freely. According to the configuration in <strong>function.json</strong>, the binding parameters named: <strong>req</strong> and <strong>res</strong>, are defined in the template. Notice in how they are used to get the parameters (<strong>req</strong>) sent to the endpoint and send the response to the caller (<strong>res</strong>).</p><ul><li><strong>sample.dat</strong></li></ul><figure><img alt="Sample.dat file content being displayed in Visual Studio Code window" src="https://cdn-images-1.medium.com/max/440/1*pBtwOeBbl1AE7LcAtTXSKg.png" /><figcaption>sample.dat</figcaption></figure><p>This file is only used to populate a test call to the API when you are using Azure Portal interface:</p><figure><img alt="Azure Portal test function window being displayed with no parameters" src="https://cdn-images-1.medium.com/max/555/0*zieYHizZpS0dio6R.png" /><figcaption>This is where sample.dat is used</figcaption></figure><p>Last but not least, the file <strong>local.setting.json</strong> is where we call configure local &quot;environment variables&quot;. The keys in this file are usually meant to keep non sensible configurations, <strong>so is not a good idea to keep the password of your database user here</strong>. A better idea would be <a href="https://medium.com/statuscode/getting-key-vault-secrets-in-azure-functions-37620fd20a0b">point a reference to extract the secret from <strong>Azure Key Vault</strong>, for example</a>.</p><p>Finally, put a breakpoint in line 4 (first if) and run the project:</p><figure><img alt="Index.js code with a breakpoint set to line 4 and the run button in debug toolbox highlighted" src="https://cdn-images-1.medium.com/max/1024/1*78Kj1gsDNP6b_R3PtTg_4w.png" /><figcaption>The beginning of our serverless saga</figcaption></figure><p>Wait until the messages below are displayed in your integrated terminal:</p><figure><img alt="Function&#39;s execution output with its URL being highlighted in terminal" src="https://cdn-images-1.medium.com/max/1024/1*Glcp3EkhW7dPB8h2TQgDWw.png" /><figcaption>Function up, running and debuggable!</figcaption></figure><blockquote>If you ran into any problem, again, review the steps above. There is a high probability that there is a version incompatibility between Core Tools and NodeJs!</blockquote><p>The function gets up a little before the debugger can attach to the process, so, if you call the endpoint faster than this attachment, the breakpoint won&#39;t hit.</p><p>Try to call in your browser the endpoint highlighted in the image above. Firstly, your breakpoint will be triggered, changing the focus to vscode:</p><figure><img alt="Index.js file code with line 4 breakpoint being hit by Visual Studio Code debugger" src="https://cdn-images-1.medium.com/max/1024/1*tKDqQYG2EHL3cGLUIn2gOA.png" /><figcaption>Debugging a Azure Function locally</figcaption></figure><p>Select the &quot;resume&quot; button to release the debugger, go back to the browser and the result should be this:</p><figure><img alt="Browser open with function URL and the message: please pass a name on the query string or in the request body" src="https://cdn-images-1.medium.com/max/1024/1*9lsZ2bJJYDedb4DPKSFyRg.png" /><figcaption>Hello need a parameter</figcaption></figure><p>The Hello World template function expects a parameter named: &quot;<strong>name</strong>&quot; via query string or request body, with your name so it can give you a Hello. Take some time to understand how the code works and the passing of parameters through object <strong>req</strong>. After, make a call using query string, as the following image:</p><figure><img alt="Browser open with function URL with &quot;World&quot; as query string parameter and the message: Hello World" src="https://cdn-images-1.medium.com/max/1024/1*HggOQ3BGQckyRrMprnyvBQ.png" /><figcaption>Fully functional Hello World!</figcaption></figure><p>Our tests until here were only via verb: <strong>get</strong>. Lets do one using verb: <strong>post</strong>. To do so, you will need any tool of your preference, from <a href="https://curl.haxx.se/">curl</a> to <a href="https://www.postman.com/">Postman</a>. For this example, we will use Postman:</p><figure><img alt="Postman screenshot executing a POST method to function&#39;s URL and the JSON parameter: “World”, and the output: Hello World" src="https://cdn-images-1.medium.com/max/1024/1*PMFbEW7QLGoRRzCOcI4gMQ.png" /><figcaption>POST call with JSON parameter example</figcaption></figure><h3>Deploying to Azure Account</h3><p>Now that we have setup the development environment, created the function and locally tested it, let&#39;s upload it to Azure to call it through Internet. The are several ways to do this, for example: create a function via Portal and upload it manually, create a automated CI/CD process (highly recommended) or deploy via vscode (actually the plugin uses Azure CLI behind the scenes), the latter is what I will approach in this article for simplicity sake.</p><p>Stop the function debug if you haven&#39;t did it already, open the command palette (Ctrl+Shift+P in Windows/Linux or Cmd+Shift+P in MacOs) and start typing: <strong>azure functions deploy</strong> and select &quot;Azure Functions: Deploy to Function app…&quot;:</p><figure><img alt="Azure Functions command palette searchbox containing: &quot;azure functions deploy&quot;" src="https://cdn-images-1.medium.com/max/1024/1*EszP9i2jHs_wQcmGx3vWmQ.png" /><figcaption>Starting the deploy</figcaption></figure><p>Select your subscription, if you already have any functions created, it will be displayed. Select &quot;Create new Function App in Azure… Advanced&quot;:</p><figure><img alt="Azure Functions command palette searchbox containing: “Create new Function App in Azure Advanced”" src="https://cdn-images-1.medium.com/max/1024/1*EqTZi6GfvmNU9Zy9oumULQ.png" /><figcaption>Create a function in Azure</figcaption></figure><p>Choose a name for your function. This name must be globally unique, so in all Azure, a duplicated named function cannot exist. After that, select the target operating system to deploy, in this example I will be using <strong>Linux</strong>.</p><p>You will be asked about the &quot;hosting plan&quot; — this is how you will pay for this resource (function). There are three plans:</p><figure><img alt="Azure Functions command palette with options: Consumption, Premium and App Service Plan" src="https://cdn-images-1.medium.com/max/1024/1*vaSMSzkr7umspSQ6-yXWjg.png" /><figcaption>Hosting plans</figcaption></figure><ul><li><strong>Consumption</strong></li></ul><p>In this plan, instances of your function are dynamically allocated or deallocated according with the incoming load, ensuring your function will scale without you have to worry about it. Also, you are charged only during your function execution, this means, you do not have to pay anything if your function is completely idle.</p><p>Currently, there is a monthly free grant of 1 million free requests, which makes serverless very cost effective and financially attractive. <a href="https://azure.microsoft.com/en-us/pricing/details/functions/">You can find more pricing information here</a>.</p><p>However there is cost of this automatic scalability, a problem called: <a href="https://azure.microsoft.com/en-us/blog/understanding-serverless-cold-start/">cold start</a>. If your function become idle for a while, Azure might put it into a cold state which will take a little longer to warm if your function is triggered. Subsequent requests are faster.</p><p>There is also a function total duration timeout (configurable), so functions are not meant for heavy processing.</p><ul><li><strong>Premium</strong></li></ul><p>Very similar to Consumption, however, it has some advantages like: there is no cold start — instances are always warm, VNet connectivity, unlimited duration timeout, and others. The billing is also different, so it can be substantially higher than Consumption due to extra benefits.</p><ul><li><strong>App Service Plan</strong></li></ul><p>With this plan your functions can run in the same traditional App Services VMs. This scenario might useful when you have an underused instance, so your cost benefit will raise. As your instance is always on, the function will always be warm too, and you will be charged the same way of your App Service, no other costs.</p><p>We will choose Consumption in this example: choose it, and after choose the runtime of the function: <strong>Node.js 12.x</strong> (If you chose Core Tools v3):</p><figure><img alt="Azure Functions command palette searchbox containing: &quot;Node.js 12.x”" src="https://cdn-images-1.medium.com/max/1024/1*xjiUPC0KA9HgsV1m3OWsPA.png" /><figcaption>Runtime choices</figcaption></figure><p>Select or create a resource group to nest your function and then also a Storage Account. This last one is necessary to store your function bundled code and the runtime parameters and your functions parameters too.</p><p>In step 9/10 you will be able to choose an Application Insight. This is a very interesting Azure resource which is used to extract logs and other important information about your functions health. As we are just doing a &quot;Hello World&quot;, we can proceed without it by choosing: &quot;Skip for now&quot;.</p><p>Lastly, select a supported region you want Azure to deploy your function, select your favorite, and your function will be created and our &quot;Hello World&quot; code will be packed and delivered. After that, click on the &quot;Output&quot; tab and at the bottom you can copy your function&#39;s link which is running now under Azure infrastructure, as below:</p><figure><img alt="Deploy&#39;s output screen indicating success and public function URL" src="https://cdn-images-1.medium.com/max/1024/1*UPzi6IPhV--YjddEW8BohA.png" /><figcaption>Function deployed with success!</figcaption></figure><p>Quickly test it in your browser and you will see the same as in our local tests:</p><figure><img alt="Browser open with public function URL and the message: please pass a name on the query string or in the request body" src="https://cdn-images-1.medium.com/max/1024/1*5wtX0J2SStN8qN0khVjH4g.png" /><figcaption>&quot;Production&quot; running function</figcaption></figure><h3>Conclusion</h3><p>I believe that serverless came to stay and will be more adopted with time, specially for the development speed and cost reduction benefits. Nonetheless, breaking our code in perhaps even more &quot;micro&quot; than microservices can make automatic integrated tests harder when you have so many pieces and their communication are variated.</p><p>I hope this helped at least a little about the understanding of serverless and Azure Functions. See you soon!</p><h3>References</h3><p><a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-vs-code?tabs=csharp">Develop Azure Functions by using Visual Studio Code</a></p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/introduction-to-azure-functions-vscode"><em>https://blog.danielpadua.dev</em></a><em> on February 24, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86614c04db3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/introduction-to-azure-functions-vscode-e86614c04db3">Introduction to Azure Functions + Vscode</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introdução Azure Functions + Vscode]]></title>
            <link>https://medium.com/danielpadua/introducao-azure-functions-vscode-45717d7c6f71?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/45717d7c6f71</guid>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 17:57:27 GMT</pubDate>
            <atom:updated>2021-07-12T00:25:20.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Logo do Azure Function com um sinal de adição e o logo do Visual Studio Code" src="https://cdn-images-1.medium.com/max/1024/1*e0_KX-4Q6x7HPfKeO0w9Pw.png" /></figure><h3>Introdução</h3><p>Como desenvolvedor fui capaz de presenciar algumas transformações significativas no mercado ao longo do tempo, como por exemplo:</p><ul><li>Um grande movimento de migração do paradigma de programação estruturada para o orientado a objetos.</li><li>Maior foco em desenvolvimento web ao invés de desktop.</li><li>Criação e aumento vertiginoso de desenvolvimento de apps para mobile.</li><li>Troca da escalabilidade vertical para escalabilidade horizontal com surgimento de cloud computing.</li><li>Adoção de micro-serviços ao invés de monólitos.</li></ul><p>E, recentemente, na verdade já há algum tempo, venho notando que há um grande movimento de adoção de <a href="https://en.wikipedia.org/wiki/Serverless_computing"><em>serverless</em></a> para aplicações novas e modernas, substituindo em muitos casos até mesmo os micro-serviços.</p><p>A arquitetura serverless é capaz de prover muita facilidade, flexibilidade, escalabilidade automática e outros benefícios, até mesmo parecido com os de micro-serviços, no entanto, as maiores diferenças entre eles na minha opinião é a facilidade e a redução de custos.</p><p>Com serverless você não precisa se preocupar em alocar um servidor para seu app, muito menos, preocupar-se em como escalá-lo. Você precisa se importar, apenas, com a resolução de seu problema de negócio por meio de código, o que dá uma grande velocidade para lançamento de novas features ou produtos. E, na maioria dos provedores cloud, você paga apenas o que usa, trazendo redução de custos significativos se comparado a uma instância que está sempre executando, mesmo que esteja sem carga.</p><p>Neste artigo introdutório, abordarei como iniciar o desenvolvimento serverless na plataforma Microsoft Azure, utilizando o vscode como editor de código para o desenvolvimento e deploy de uma função que retornará um &quot;Hello World&quot; após uma chamada GET ou POST de HTTP.</p><h3>Pré-requisitos</h3><ul><li><a href="https://code.visualstudio.com/download">Visual Studio Code</a></li><li><a href="https://azure.microsoft.com/pt-br/free">Conta Azure</a></li></ul><h3>Instalação e configuração do ambiente de desenvolvimento</h3><p>Para que possamos trabalhar com functions de uma maneira eficiente é necessário, minimamente, montar um ambiente de desenvolvimento local no qual possamos escrever código, rodar e debugar. Utilize as seções abaixo de acordo com seu sistema operacional.</p><h4>Windows</h4><p><strong>1. Instalar o NodeJs</strong></p><p>Neste guia, trabalharemos com Azure Functions versão 3.x, portanto <strong>devemos instalar as versões 10.x.x ou 12.x.x do NodeJs</strong>. Se por alguma razão você queira utilizar a versão 2.x utilize o NodeJs 8.x.x.</p><blockquote>Existe uma incompatibilidade no Windows com versões de NodeJs ≥ 13.x.x e Core Tools 3.x, portanto, por ora, utilize as versões explicitadas acima: (<a href="https://github.com/Azure/azure-functions-core-tools/issues/1804">https://github.com/Azure/azure-functions-core-tools/issues/1804</a>)</blockquote><p>Há diferentes formas de se fazer isso:</p><ul><li>Instalar diretamente por <a href="https://nodejs.org/dist/">download do site do NodeJs</a>: escolha na lista uma das versões especificadas acima e procure o instalador com sufixo &quot;<strong>win-x64</strong>&quot;, se a esta altura de 2020 a arquitetura da máquina em que você está não for 64 bits, procure pelo sufixo &quot;<strong>win-x86</strong>&quot; para arquiteturas 32 bits.</li><li>Instalar via gerenciador de pacotes com NVM: O <a href="https://github.com/nvm-sh/nvm">NVM</a> é um programa de linha de comando que possui a função de gerenciar mais facilmente múltiplas instalações de versões do NodeJs. Utilizando por exemplo: <a href="https://medium.com/danielpadua/utilizando-chocolatey-para-windows-2b51c0ba9b31">Chocolatey para Windows</a> podemos instalar o nvm através da linha: <strong>choco install nvm</strong>, e depois instale uma das versões acima com: <strong>nvm install &lt;versão&gt;</strong> e depois vincule-a em uso com: <strong>nvm use &lt;versão&gt;</strong>.</li></ul><p><strong>2. Instalar Azure Core Tools</strong></p><p>É este cara que permite a criação de um ambiente de execução local de suas funções e as rode via linha de comando, podendo até se comunicar com recursos da Azure, o que não é recomendável, pois o mais correto seria apartar os ambientes completamente, mas funciona.</p><p>A instalação dele no Windows é feita via NodeJs, através da linha de comando no PowerShell ou cmd:</p><pre>npm install -g azure-functions-core-tools@3</pre><p>Caso queira instalar a versão 2.x seria:</p><pre>npm install -g azure-functions-core-tools</pre><p>Após instalação, teste a instalação mandando apenas um:</p><pre>func --version</pre><p>Caso você veja um erro parecido com este:</p><figure><img alt="Um terminal PowerShell executando o comando func e o retorno é o erro de about_Execution_Policies" src="https://cdn-images-1.medium.com/max/856/1*foMuyEpCKtQrpmqQb_oPRw.png" /><figcaption>Erro de permissão de execução de scripts NodeJs</figcaption></figure><p>Rode o comando a seguir no PowerShell como administrador para dar permissão para que os scripts instalados pelo NodeJs sejam executados:</p><pre>Set-ExecutionPolicy RemoteSigned</pre><p>Caso haja algum erro envolvendo &quot;<strong>Unhandled ‘error’ event</strong>&quot;, é bem provável que seja incompatibilidade entre as versões do Core Tools com o NodeJs, refaça o passo acima.</p><h4>MacOs</h4><p><strong>1. Instalar o NodeJs</strong></p><p>Neste guia, iremos trabalhar com Azure Functions versão 3.x, portanto <strong>devemos instalar versões ≥ 10.x.x do NodeJs</strong>. Se por alguma razão você queira utilizar a versão 2.x utilize o NodeJs 8.x.x.</p><p>Há diferentes formas de se fazer isto:</p><ul><li>Instalar diretamente por <a href="https://nodejs.org/dist/">download do site do NodeJs</a>: escolha uma das versões especificadas acima, procure o instalador com extensão &quot;<strong>.pkg</strong>&quot; e faça o instalação <strong>NNF </strong>(next, next, finish).</li><li>Instalar via gerenciador de pacotes com NVM: o <a href="https://github.com/nvm-sh/nvm">NVM</a> é um programa de linha de comando que possui a função de gerenciar mais facilmente múltiplas instalações de versões do NodeJs. Utilizando por exemplo: <a href="https://medium.com/danielpadua/utilizando-o-homebrew-no-macos-4bd20ce4d093">Homebrew para MacOs</a> para instalar o nvm através da linha: <strong>brew install nvm </strong>e depois instale uma das versões acima com: <strong>nvm install &lt;versão&gt;</strong> e depois vincule-a em uso com: <strong>nvm use &lt;versão&gt;</strong>.</li></ul><p><strong>2. Instalar Azure Core Tools</strong></p><p>É este cara que permite a criação de um ambiente de execução local de suas funções e as execute via linha de comando, podendo até se comunicar com recursos da Azure, o que não é recomendável, pois o mais correto seria apartar os ambientes completamente, mas funciona.</p><p>Instale a versão 3.x utilizando o Homebrew, com as linhas:</p><pre>brew tap azure/functions<br>brew install azure-functions-core-tools@3<br># executar linha abaixo caso você esteja fazendo upgrade da versão 2.x para a 3.x na sua máquina<br>brew link --overwrite azure-functions-core-tools@3</pre><p>Para instalar a versão 2.x utilize as linhas:</p><pre>brew tap azure/functions<br>brew install azure-functions-core-tools</pre><p>Por fim, teste o funcionamento com a linha:</p><pre>func --version</pre><h4>Linux</h4><p><strong>1. Instalar o NodeJs</strong></p><p>Neste guia, trabalharemos com Azure Functions versão 3.x, portanto <strong>devemos instalar versões ≥ 10.x.x do NodeJs</strong>. Se por alguma razão você queira utilizar a versão 2.x utilize o NodeJs 8.x.x.</p><p>Há diferentes formas de se fazer isso:</p><ul><li>Instalar diretamente por <a href="https://nodejs.org/dist/">download do site do NodeJs</a>: escolha uma das versões especificadas acima e procure o instalador com o sufixo “<strong>.linux-x64.tar.gz</strong>”, baixe, extrai-o, coloque-o em um diretório de fácil acesso e crie um link simbólico para o arquivo: &quot;<strong>/bin/node</strong>&quot;.</li><li>Instalar via gerenciador de pacotes com NVM: O <a href="https://github.com/nvm-sh/nvm">NVM</a> é um programa de linha de comando que possui a função de gerenciar mais facilmente múltiplas instalações de versões do NodeJs. Utilizando o gerenciador de pacotes de distribuição linux que você faz uso, instale o NVM, e depois instale uma das versões acima com: <strong>nvm install &lt;versão&gt;</strong>, posteriormente, vincule-a em uso com: <strong>nvm use &lt;versão&gt;</strong>.</li></ul><p><strong>2. Instalar Azure Core Tools</strong></p><p>É este cara que permite que você crie um ambiente de execução local de suas funções e as execute via linha de comando. Podendo até se comunicar com recursos da Azure, o que não é recomendável, pois o mais correto seria apartar os ambientes completamente, mas funciona.</p><p>Caso sua distribuição for baseada em Debian, você pode utilizar este <a href="https://docs.microsoft.com/pt-br/azure/azure-functions/functions-run-local?tabs=linux#v2">guia da Microsoft</a> para instalar o Core Tools. Caso seja outra distribuição, verifique o <a href="https://github.com/Azure/azure-functions-core-tools/blob/master/README.md#linux">README do Core Tools</a>.</p><p>Teste o funcionamento do Core Tools com a linha:</p><pre>func --version</pre><h4><strong>Instalar o plugin Azure Functions no vscode</strong></h4><p>Abra <strong>Extensões </strong>e procure por: <strong>Azure Functions </strong>ou <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions">use este link</a>.</p><figure><img alt="Janela de instalação de plugins do Visual Studio Code com a página do Azure Functions prestes a ser instalado" src="https://cdn-images-1.medium.com/max/1024/1*lglDm88O_1WdufH1Hz_mkw.png" /><figcaption>Instalação do plugin Azure Functions no vscode</figcaption></figure><p>Depois de instalado, reinicie o vscode e confirme que juntamente ao plugin Azure Functions foi instalado o Azure Account. Faça login conforme a imagem abaixo:</p><figure><img alt="A toolbox do Azure sendo exibida no Visual Studio Code e um indicativo para o botão &quot;Sign in to Azure&quot;" src="https://cdn-images-1.medium.com/max/564/1*75E7rKBDG76yEUHtaOPa_Q.png" /><figcaption>Realizando login na sua conta Azure</figcaption></figure><p>Você deve ser redirecionado a realizar login Microsoft no seu browser padrão, após isso, retorne ao vscode e seus recursos Azure serão exibidos.</p><h3>Criando e debugando uma function localmente</h3><p>Agora, com o ambiente de desenvolvimento pronto, vamos criar uma function simples de Hello World. Para isso, na tela inicial do vscode, utilize a combinação de teclas: Ctrl+Shift+P (Windows ou Linux) ou Cmd+Shift+P (MacOs). A paleta de comandos deve abrir e comece a digitar: <strong>functions create new project</strong>:</p><figure><img alt="Lançador de comandos do Azure Functions com a caixa de texto preenchida com a pesquisa: &quot;function create new project&quot;" src="https://cdn-images-1.medium.com/max/1024/1*evNxZLOqrJRcFsG0XwYesA.png" /><figcaption>Criar projeto de functions</figcaption></figure><p>Um projeto de functions é capaz de armazenar N funções de diferentes tipos, acionadas por Http, por tempo, estimulo de fila e etc.</p><p>Caso você não esteja com algum diretório aberto no vscode, ele pedirá para abrir um. Crie um diretório onde guardaremos os fontes do nosso projeto e selecione-o. Após esta etapa, você será questionado em qual linguagem deseja desenvolver, para este exemplo, usaremos <strong>Javascript</strong>:</p><figure><img alt="Janela de criação de projeto de funções com a caixa de pesquisa contendo: “Javascript”" src="https://cdn-images-1.medium.com/max/1024/1*hYcBkYDA50beItKnUUQZNw.png" /><figcaption>Escolha sua linguagem para desenvolvimento de functions</figcaption></figure><p>Seu próximo questionamento é: desejo utilizar algum template de function pré-pronto de acordo com o tipo de trigger que irei dispará-la? Novamente, para nosso exemplo, iremos selecionar uma trigger http:</p><figure><img alt="Janela de criação de projeto de funções com a caixa de pesquisa contendo: “Http Trigger”" src="https://cdn-images-1.medium.com/max/1024/1*cIaaLv-DqQ9Zi8mcUpDBjw.png" /><figcaption>Template de function Http Trigger</figcaption></figure><p>O passo seguinte consiste apenas em dar um nome para a function, eu costumo utilizar a nomenclatura: <strong>nome_TipoTrigger, </strong>para quando bater o olho no diretório da function, já saber o que a dispara, no entanto, você pode usar a nomenclatura que preferir.</p><p>Agora, selecione qual o nível de autorização da function. Existem 3 tipos de autorização padrão de functions:</p><ul><li><strong>Function</strong>: há uma chave de acesso no nível da função que é criada no portal do Azure, a ser utilizada para autenticar chamadas em seus endpoints, passando na request via Query String ou parâmetro no Header da solicitação Http. Caso este parâmetro não seja preenchido ou esteja incorreto, a função devolverá o status Http 401 — Não autorizado.</li><li><strong>Anonymous</strong>: como o próprio nome já diz, sem autorização, seus endpoints podem ser atingidos por todos sem qualquer tipo de autorização.</li><li><strong>Admin</strong>: assim como existe uma chave de acesso no nível da função, existe uma chave de admin chamada <strong>host key, </strong>também criada no Azure, que somente ela liberará acesso na function, caso esta autorização seja selecionada. Caso não informado ou estiver incorreto, a função devolverá o status Http 401 — Não autorizado.</li></ul><p>Por último, selecione para abrir o projeto na mesma janela, caso você já não tivesse com uma pasta aberta.</p><p>Seu projeto criado deverá estar como na imagem abaixo:</p><figure><img alt="Conteúdo do arquivo index.js sendo exibido na janela do Visual Studio Code" src="https://cdn-images-1.medium.com/max/1024/1*TUjoaCaksCE-YDfvOl4a3Q.png" /><figcaption>Estrutura de diretórios de projeto function javascript</figcaption></figure><p>Para javascript as functions são separadas em pastas sempre contendo 3 arquivos:</p><ul><li><strong>function.json</strong></li></ul><figure><img alt="Conteúdo do arquivo function.json sendo exibido na janela do Visual Studio Code" src="https://cdn-images-1.medium.com/max/806/1*5jfPpdg8r04RziFQ6-842w.png" /><figcaption>function.json</figcaption></figure><p>É responsável por dizer ao Azure quais bindings vamos utilizar. Bindings é uma maneira de conectar um recurso Azure como uma fila, tópico, banco de dados, ação http e etc. com a function, podendo ele ter uma direção (input ou output).</p><p>Por exemplo, o primeiro objeto consiste em uma configuração específica de função acionada por trigger Http onde a direção é <strong>in,</strong> ou seja, chegando para sua função pelos verbos: <strong>get </strong>e <strong>post </strong>através do parâmetro de nome <strong>req</strong>. E o segundo objeto é a saída &quot;<strong>out</strong>&quot; do tipo http podendo ser acessado através do parâmetro <strong>res</strong>.</p><ul><li><strong>index.js</strong></li></ul><figure><img alt="Conteúdo do arquivo index.js sendo exibido na janela do Visual Studio Code" src="https://cdn-images-1.medium.com/max/1024/1*X0LdPDqu7ww08G8Gnz_ktw.png" /><figcaption>index.js</figcaption></figure><p>Este é o arquivo onde ficará a lógica de sua função, onde você poderá programar livremente. Conforme configurado no <strong>function.json, </strong>os parâmetros de binding de nome: <strong>req</strong> e <strong>res,</strong> estão definidos no template padrão. Repare como eles são utilizados para pegar parâmetros enviados (<strong>req</strong>) para o endpoint e para enviar a resposta ao chamador (<strong>res).</strong></p><ul><li><strong>sample.dat</strong></li></ul><figure><img alt="Conteúdo do arquivo sample.dat sendo exibido na janela do Visual Studio Code" src="https://cdn-images-1.medium.com/max/440/1*pBtwOeBbl1AE7LcAtTXSKg.png" /><figcaption>sample.dat</figcaption></figure><p>Esse arquivo serve apenas para popular uma chamada teste para API quando utilizada a interface de testes da própria da Azure:</p><figure><img alt="Janela de teste de funções do Portal Azure sendo exibido sem parâmetros preenchidos" src="https://cdn-images-1.medium.com/max/555/0*zieYHizZpS0dio6R.png" /><figcaption>Onde o sample.dat é utilizado</figcaption></figure><p>Por fim, e não menos importante, o arquivo <strong>local.settings.json</strong> é onde podemos configurar &quot;variáveis de ambiente&quot; locais. As chaves neste arquivo são, geralmente, utilizadas para guardar configurações não sensíveis, portanto, <strong>não é uma boa ideia guardar senha de usuário de bancos de dados aqui</strong>. Uma ideia bem melhor seria <a href="https://medium.com/statuscode/getting-key-vault-secrets-in-azure-functions-37620fd20a0b">apontar uma referência para extrair o valor do <strong>Azure Key Vault,</strong> por exemplo</a>.</p><p>Finalmente, coloque um breakpoint na linha 4 (no primeiro if) e executemos o projeto:</p><figure><img alt="Código do arquivo index.js com um breakpoint na linha 4 e o botão executar da toolbox de debug destacado" src="https://cdn-images-1.medium.com/max/1024/1*78Kj1gsDNP6b_R3PtTg_4w.png" /><figcaption>Iniciando nossa saga serverless</figcaption></figure><p>Aguarde um tempo até que as mensagens a seguir apareçam em seu terminal integrado:</p><figure><img alt="Output de execução com a URL da função destacada no terminal" src="https://cdn-images-1.medium.com/max/1024/1*Glcp3EkhW7dPB8h2TQgDWw.png" /><figcaption>Subiu e está ‘debugável’</figcaption></figure><blockquote>Caso tenha ocorrido algum problema, novamente, reveja os passos acima. A probabilidade de que tenha ocorrido algum problema de incompatibilidade de versões entre o NodeJs e o Core Tools é grande!</blockquote><p>A função sobe um pouco antes do debugger conseguir se vincular ao processo, então, caso você chame o endpoint mais rápido que o vínculo, o breakpoint não será acionado.</p><p>Experimente chamar no seu browser o endpoint indicado na imagem acima. Primeiramente, seu breakpoint será acionado, mudando o foco para o vscode:</p><figure><img alt="Código do arquivo index.js com o breakpoint da linha 4 sendo acionado pelo debugger do Visual Studio Code" src="https://cdn-images-1.medium.com/max/1024/1*tKDqQYG2EHL3cGLUIn2gOA.png" /><figcaption>Debugando uma Azure Function localmente</figcaption></figure><p>Selecione o botão de &quot;resume&quot; para soltar o debugger, volte ao browser e o resultado deverá ser este:</p><figure><img alt="Imagem do browser aberto na URL da função e a mensagem na tela: please pass a name on the query string or in the request body" src="https://cdn-images-1.medium.com/max/1024/1*9lsZ2bJJYDedb4DPKSFyRg.png" /><figcaption>Hello exigindo um parâmetro</figcaption></figure><p>O template de function de Hello World espera que seja passado um parâmetro de nome: &quot;<strong>name</strong>&quot; via query string ou no request body, com o seu nome para que ele possa te dar o Hello. Aproveite um pouco do tempo para entender no código como funciona a dinâmica de passagem de parâmetros através do objeto <strong>req. </strong>Depois, faça uma chamada usando query string, como na imagem seguinte:</p><figure><img alt="Browser aberto na  URL da função com o parâmetro query string “World” e a mensagem: &quot;Hello World&quot;" src="https://cdn-images-1.medium.com/max/1024/1*HggOQ3BGQckyRrMprnyvBQ.png" /><figcaption>Hello World funcional!</figcaption></figure><p>Os testes que fizemos até agora foram apenas via verbo: <strong>get</strong>. Vamos fazer agora um pelo verbo: <strong>post</strong>. Para isso, você pode usar qualquer ferramenta de sua preferência, desde <a href="https://curl.haxx.se/">curl</a> até o <a href="https://www.postman.com/">Postman</a>. Para este exemplo, vamos de Postman:</p><figure><img alt="Tela do Postman executando um método POST para a URL da função e o parâmetro JSON: &quot;World&quot;, e o resultado: Hello World" src="https://cdn-images-1.medium.com/max/1024/1*PMFbEW7QLGoRRzCOcI4gMQ.png" /><figcaption>Exemplo de chamada POST com parâmetro JSON</figcaption></figure><h3>Realizando deploy para sua conta Azure</h3><p>Agora que montamos todo o ambiente de desenvolvimento, criamos a function e a testamos localmente, vamos subi-la para Azure para chamá-la através da Internet. Existem muitas maneiras de se fazer este processo, a saber: criar uma function via Portal e fazer upload manualmente, criar uma esteira de entregas contínuas (altamente recomendável) ou realizar deploy via vscode (na realidade ele utiliza a Azure CLI por trás dos panos), que é o que irei abordar neste guia por conta da simplicidade.</p><p>Pare seu debug da function, caso não o tenha feito ainda, e suba a paleta de comandos (Ctrl+Shift+P no Windows/Linux ou Cmd+Shift+P no MacOs), comece a digitar: <strong>azure functions deploy</strong> e selecione &quot;Azure Functions: Deploy to Function App…&quot;:</p><figure><img alt="Pesquisa do comando Azure Functions preenchida com a pesquisa: “azure functions deploy”" src="https://cdn-images-1.medium.com/max/1024/1*EszP9i2jHs_wQcmGx3vWmQ.png" /><figcaption>Iniciando o deploy</figcaption></figure><p>Selecione sua subscription ativa e na sequência aparecerá alguma function, caso você já a tenha criado. Selecione &quot;Create new Function App in Azure… Advanced&quot;:</p><figure><img alt="Pesquisa do comando Azure Functions preenchida com a pesquisa: &quot;Create new Function App in Azure Advanced”" src="https://cdn-images-1.medium.com/max/1024/1*EqTZi6GfvmNU9Zy9oumULQ.png" /><figcaption>Criar uma função na Azure</figcaption></figure><p>Escolha um nome para a função. Este nome deve ser globalmente único, portanto, ninguém no Azure pode ter functions com nomes iguais. Após isso, selecione o sistema operacional para realizar deploy, eu irei utilizar neste exemplo, o <strong>Linux</strong>.</p><p>Você será questionado também sobre o &quot;hosting plan&quot;, que será a forma de pagamento deste recurso (function). Existem três planos:</p><figure><img alt="Comando Azure Functions exibindo as opções: Consumption, Premium e App Service Plan" src="https://cdn-images-1.medium.com/max/1024/1*vaSMSzkr7umspSQ6-yXWjg.png" /><figcaption>Planos de pagamento</figcaption></figure><ul><li><strong>Consumption</strong></li></ul><p>Neste plano, as instâncias de sua function são dinamicamente alocadas e desalocadas de acordo com a carga dos eventos de trigger, garantindo escalabilidade sem preocupação com a implementação da mesma e você também só é cobrado durante a execução da função, ou seja, caso não haja execuções, não existe cobrança.</p><p>Atualmente, existe uma concessão de 1 milhão de chamadas gratuitas, o que torna o serverless muito atrativo financeiramente. <a href="https://azure.microsoft.com/pt-br/pricing/details/functions/">Maiores informações de cobrança aqui</a>.</p><p>Porém o custo dessa escalabilidade é um problema chamado: <a href="https://azure.microsoft.com/pt-br/blog/understanding-serverless-cold-start/">cold start</a> ou partida a frio. Caso sua função fique sem ser chamada por um período de tempo, a Azure a coloca em um modo frio no qual a chamada seguinte terá uma demora maior até a Azure levantar e a deixar quente. As chamadas subsequentes são mais rápidas.</p><p>Também existe um limitador de tempo de duração da função (configurável até um certo limite) que retorna timeout ao chamador caso o ultrapasse.</p><ul><li><strong>Premium</strong></li></ul><p>Basicamente, igual ao Consumption, no entanto, possui algumas vantagens como: não existe cold start, as instâncias de funções são sempre quentes, conectividade com VNet, tempo de duração ilimitado, entre outros. A forma de cobrança é diferente, podendo, provavelmente, o pagamento ser maior do que o Consumption, devido aos benefícios extras.</p><ul><li><strong>App Service Plan</strong></li></ul><p>Neste plano, suas funções podem rodar nas mesmas VMs que as tradicionais da App Services. Este cenário pode fazer sentido para você caso possua uma instância sub-utilizada, por exemplo, otimizando o uso x cobrança. Como a instância está sempre ligada, a function estará sempre quente também. Você continuará sendo cobrado pelo método do seu App Service.</p><p>Iremos de Consumption no exemplo a seguir: selecione-o e, na sequência, vamos escolher a runtime da function: <strong>Node.js 12.x </strong>(Caso Core Tools v3):</p><figure><img alt="Pesquisa do comando Azure Functions preenchida com a pesquisa: “Node.js 12.x”" src="https://cdn-images-1.medium.com/max/1024/1*xjiUPC0KA9HgsV1m3OWsPA.png" /><figcaption>Escolha da runtime</figcaption></figure><p>Selecione ou crie um grupo de recursos para aninhar sua função e depois uma Storage Account. Este último é necessário para armazenar o bundle de código da sua function e também para a parametrizações de versão da runtime da Azure Functions em si.</p><p>No passo 9/10 você poderá selecionar um Application Insight. Este é um recurso interessantíssimo da Azure que é utilizado para extrair de logs informações importantes de saúde ou funcionamento da sua function. Como estamos apenas num Hello World, podemos seguir sem ele selecionando a opção: &quot;Skip for now&quot;.</p><p>Por último selecione em qual região suportada pela Azure você deseja que a function esteja, selecione sua preferida, assim sua function será criada e o código do Hello World local será entregue. Depois de concluído, clique na aba &quot;Output&quot; e, ao final, você poderá pegar o link para sua função que já está rodando na infraestrutura da Azure, conforme abaixo:</p><figure><img alt="Output do deploy indicando sucesso e a URL da internet sendo exibida" src="https://cdn-images-1.medium.com/max/1024/1*UPzi6IPhV--YjddEW8BohA.png" /><figcaption>Função entregue com sucesso!</figcaption></figure><p>Com um teste rápido no seu browser você verá o mesmo dos testes locais:</p><figure><img alt="Browser aberto na URL pública da função e a mensagem na tela: please pass a name on the query string or in the request body" src="https://cdn-images-1.medium.com/max/1024/1*5wtX0J2SStN8qN0khVjH4g.png" /><figcaption>Rodando em &quot;produção&quot;</figcaption></figure><h3>Conclusão</h3><p>Eu acredito que o serverless veio pra ficar e será cada vez mais adotado com o passar do tempo, principalmente pelas vantagens de velocidade de desenvolvimento e redução de custos. No entanto, quebrar nosso código talvez num nível mais &quot;micro&quot; do que micro-serviços pode tornar a tarefa de um teste integrado automatizado um tanto quanto difícil quando existem tantas peças e comunicações tão variadas entre elas.</p><p>Espero ter ajudado a dar uma clareada em serverless e Azure Functions. Até a próxima!</p><h3>Referências</h3><p><a href="https://docs.microsoft.com/pt-br/azure/azure-functions/functions-develop-vs-code?tabs=csharp">Desenvolver o Azure Functions usando o Visual Studio Code</a></p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>Caso tenha achado que esse post foi útil e quiser me apoiar, você pode fazer isto me pagando um café usando o botão acima!</figcaption></figure><p><em>Publicado originalmente em </em><a href="https://blog.danielpadua.dev/pt/posts/introducao-azure-functions-vscode"><em>https://blog.danielpadua.dev</em></a><em> 24 de Fevereiro de 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45717d7c6f71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/introducao-azure-functions-vscode-45717d7c6f71">Introdução Azure Functions + Vscode</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java + Lombok]]></title>
            <link>https://medium.com/danielpadua/java-lombok-2984afff3e0a?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/2984afff3e0a</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[project-lombok]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 19:01:51 GMT</pubDate>
            <atom:updated>2021-07-12T00:23:48.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwdZDdT5gdVzIXDOxR9HTw.png" /></figure><h3>Intro</h3><p>I always heard comments from other developers things like: “Java is a very verbose language”, or Hello World line count comparison between Java vs Other X Language. And I also think that this is true, when you develop pure Java (without extensions, libs and plugins) compared to other modern languages, the developer ends up writing more to reach the goal. However, since some time ago, we have a lib called <a href="https://projectlombok.org/">lombok</a> that helps you simplify (a lot) the life of those who develop with java.</p><h3>Features</h3><p><em>Lombok</em> is a lib that provides a collection of annotations that eases some repetitive java tasks (such as, getters and setters creation). Besides of being dependency of your project, it connects in your IDE making it understand the annotations, so it requires a certain configuration. In this guide I’ll show how to configure it on <a href="https://www.eclipse.org/">eclipse</a>, <a href="https://www.jetbrains.com/idea/">intellij idea </a>and also <a href="https://code.visualstudio.com/">vscode</a>. If you don’t know how to work with java with <em>vscode</em> take a look at: <a href="https://medium.com/daniel-padua-pt/java-spring-boot-vscode-9ef9b8a263cd">https://medium.com/daniel-padua/java-spring-boot-vscode-9ef9b8a263cd</a>.</p><p>The github repository with the sample classes can be found at: <a href="https://github.com/danielpadua/lombok-examples">https://github.com/danielpadua/lombok-examples</a></p><h3>Requirements</h3><ul><li>Java JDK 8 or higher</li><li>Eclipse or IntelliJ IDEA or vscode</li></ul><h3>IDE configuration</h3><p>Use the sections below according to the IDE you are using:</p><h4>Eclipse</h4><p>Download latest <em>lombok.jar</em> at: <a href="https://projectlombok.org/download">https://projectlombok.org/download</a>, store this file in some directory of your choice (e.g.: your user’s home folder). From this moment on, there are two ways of configuring eclipse:</p><ol><li>Run the <em>lombok.jar </em>jar. It will open a window that will search in all folders of your machine looking for IDEs and if it finds eclipse it will display a checkbox to enable. So, click install and it will be done, as the image below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb_Ynmq29AOYvgM1ZuOWyw.png" /><figcaption>Lombok’s eclipse installation via jar</figcaption></figure><p>2. If method 1 didn’t work or didn’t found any IDE, we will do the same work jar does under the hood but manually. Open the <em>eclipse.ini</em> file located under the configuration directory of the eclipse that you use, and edit it as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPEzihwC-dUoQSQgaoxxng.png" /><figcaption>Configuring lombok in eclipse manually</figcaption></figure><pre>-javaagent:&lt;caminho_completo&gt;/lombok.jar</pre><p>We are just adding the full path of lombok’s jar as eclipse’s initialisation argument, and this will make it understands lombok. Lombok’s jar does exactly the same thing, but it copies the jar inside of eclipse installation folder and writes <em>eclipse.ini </em>automatically.</p><h4>IntelliJ IDEA</h4><p>It’s really simple enable Lombok support in IntelliJ IDEA, to do so, open plugin installation section and install the highlighted plugin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e26L6qaIwFSZIrCKUJ4HZw.png" /><figcaption>Lombok Plugin for IntelliJ IDEA</figcaption></figure><p>Restart IntelliJ IDEA and Lombok support will be enabled.</p><h4>vscode</h4><p>Search for lombok at the extensions tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAuSsrbhx9Qzp0anzmRoow.png" /><figcaption>Searching for lombok plugin in vscode</figcaption></figure><p>Install the Gabriel Basilio Brito’s extension, which is recommended by lombok: <a href="https://projectlombok.org/setup/vscode">https://projectlombok.org/setup/vscode</a>. Restart vscode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htHKdQQthq0Lxq2lHIKpzw.png" /><figcaption>Lombok working in vscode</figcaption></figure><h3>Project</h3><p>First we need to create a java spring-boot project, so:</p><ul><li>To create a java spring-boot in eclipse follow this guide: <a href="https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670">https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670</a></li><li>To create a java spring-boot in intellij idea follow this guide: <a href="https://medium.com/danielpadua/java-spring-boot-intellij-idea-b919b0097a0">https://medium.com/danielpadua/java-spring-boot-intellij-idea-b919b0097a0</a></li><li>To create a java spring-boot in vscode follow this guide: <a href="https://medium.com/danielpadua/java-spring-boot-vscode-f86562244fe1">https://medium.com/danielpadua/java-spring-boot-vscode-f86562244fe1</a></li></ul><p>After creating the project, use the sections below depending on the build-tool that you are using:</p><h4>Maven</h4><p>Add lombok’s dependency in <em>pom.xml</em>:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>    &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>    &lt;version&gt;1.18.6&lt;/version&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p><em>You may need to force maven import update on your IDE</em>.</p><h4>Gradle</h4><p>Add lombok’s depedency in <em>build.gradle</em> file:</p><pre>repositories {<br> mavenCentral()<br>}</pre><pre>dependencies {<br> compileOnly ‘org.projectlombok:lombok:1.18.6’<br> annotationProcessor ‘org.projectlombok:lombok:1.18.6’<br>}</pre><h3>Usage</h3><p>Now let’s explore what <em>lombok </em>has to offer for us to reduce <a href="https://en.wikipedia.org/wiki/Boilerplate_code">boilerplate code</a>:</p><h4>Getters, Setters, Constructors, ToString, Equals e HashCode</h4><p>To enable getter in all fields of your class, annotate above your class name: <strong>@Getter</strong>.</p><p>To enable setter in all fields of your class, annotate above your class name: <strong>@Setter</strong>.</p><p>To create a constructor with all fields as input parameter, annotate above your class name: <strong>@AllArgsConstructor</strong>, without parameters: <strong>@NoArgsConstrutor</strong>, with required fields (or non-null): <strong>@RequiredArgsConstructor</strong></p><p>To implement default toString() use: <strong>@ToString</strong>,</p><p>To implement default equals() and hashCode() use: <strong>@EqualsAndHashCode</strong></p><p>The <strong>@Data</strong> annotation above class is a shortcut to: <strong>@ToString</strong>, <strong>@EqualsAndHashCode</strong>, <strong>@Getter</strong>, <strong>@Setter</strong> and <strong>@RequiredArgsConstructor</strong> together.</p><p>Without lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58251621557d31582158e472b68cfef6/href">https://medium.com/media/58251621557d31582158e472b68cfef6/href</a></iframe><p>With lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5feb68892a917b214cfccd544cc703a3/href">https://medium.com/media/5feb68892a917b214cfccd544cc703a3/href</a></iframe><h4><a href="https://stackoverflow.com/questions/3162665/immutable-class">Immutable classes</a></h4><p>Use the annotation: @Value above the class, to make it immutable</p><p>Without lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b085bb3350a9f74941342d3cc3392d4/href">https://medium.com/media/1b085bb3350a9f74941342d3cc3392d4/href</a></iframe><p>With lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6abcb190cbd617ac15e465f89418f9/href">https://medium.com/media/8b6abcb190cbd617ac15e465f89418f9/href</a></iframe><h4><a href="https://en.wikipedia.org/wiki/Builder_pattern">Builder pattern</a></h4><p>Use the annotation: @Builder above the class to create the builder pattern</p><p>Without lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4afc62f61377d8deab72bf4f99775627/href">https://medium.com/media/4afc62f61377d8deab72bf4f99775627/href</a></iframe><p>With lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dced3d746320eb28fa9ae232d7dc9a17/href">https://medium.com/media/dced3d746320eb28fa9ae232d7dc9a17/href</a></iframe><h4>Logging</h4><p>Slf4j is one of the supported logs, take a look at: <a href="https://projectlombok.org/features/log">https://projectlombok.org/features/log</a> to see all the supported</p><p>Without lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896c73a480f619baafe5106902bd43fc/href">https://medium.com/media/896c73a480f619baafe5106902bd43fc/href</a></iframe><p>With lombok:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d373f0cf3bead5b55ceaa077e530ef6f/href">https://medium.com/media/d373f0cf3bead5b55ceaa077e530ef6f/href</a></iframe><h3>Conclusion</h3><p>Despite the setup and configuration time spent, lombok was developed aimed to boost productivity of java developers. I’ve been using this lib for some time and I’m not thinking of stopping using it!</p><p>See you soon!</p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/java-lombok"><em>https://blog.danielpadua.dev</em></a><em> on May 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2984afff3e0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/java-lombok-2984afff3e0a">Java + Lombok</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Spring Boot + Eclipse]]></title>
            <link>https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/744454468670</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[eclipse]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 18:59:12 GMT</pubDate>
            <atom:updated>2021-07-12T00:22:27.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPPZ-cyAIh5K295S8RqFxQ.png" /></figure><h3>Intro</h3><p>To those who develop in java nowadays, it’s almost impossible to miss <a href="https://spring.io/">Spring </a>framework and more specifically <a href="https://spring.io/projects/spring-boot">Spring Boot</a>. Using this <a href="https://en.wikipedia.org/wiki/Solution_stack">development stack</a>, we gain more productivity and agility from small to large sized java projects. In this guide I’ll demonstrate how to install, configure eclipse and create a simple Hello-World using java, eclipse and spring boot.</p><p>The github repository of the example project of this post, can be found at: <a href="https://github.com/danielpadua/java-spring-eclipse-example">https://github.com/danielpadua/java-spring-eclipse-example</a></p><h3>Requirements</h3><ul><li>Java JDK 8 or higher</li></ul><h3>Installing Eclipse</h3><p><em>It’s also worth to mention that installing </em><a href="https://spring.io/tools"><em>Spring Tool Suite (STS)</em></a><em> instead of pure eclipse, is highly valid. STS is basically eclipse configured with </em><a href="https://marketplace.eclipse.org/content/spring-tools-4-spring-boot-aka-spring-tool-suite-4"><em>spring tools</em></a><em> plugin, optimized for spring framework development</em></p><p>Use the following sections based in which operational system you’ll be using:</p><h4>Windows</h4><p>In Windows we have 2 options:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.eclipse.org/downloads/packages">eclipse download page,</a> select the latest version (on the writing date of this guide is the <a href="https://www.eclipse.org/downloads/packages/release/2019-03/r/eclipse-ide-enterprise-java-developers"><strong>4.10</strong></a>) and install it using NNF (next, next, next and finish).</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> (Chocolatey)</li></ul><p>If you don’t know <em>Chocolatey</em>, take a look at this post: <a href="https://medium.com/danielpadua/using-chocolatey-for-windows-878290cfb58d">https://medium.com/danielpadua/using-chocolatey-for-windows-878290cfb58d</a>.</p><p>Open <em>powershell</em> and install eclipse using the following command line:</p><pre>choco install eclipse</pre><h4>Linux</h4><p>In Linux we also have 2 options:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.eclipse.org/downloads/packages">eclipse download page,</a> select the latest version (on the writing date of this guide is the <a href="https://www.eclipse.org/downloads/packages/release/2019-03/r/eclipse-ide-enterprise-java-developers"><strong>4.10</strong></a>), extract the <em>.tar.gz</em> file and execute the <em>eclipse</em> file.</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a></li></ul><p>Depending in which Linux distro you are using, you’ll use a different package manager. For instance, <a href="https://en.wikipedia.org/wiki/Category:Debian-based_distributions">debian based distros</a>, like the popular <a href="https://www.ubuntu.com/">ubuntu</a>, use <a href="https://www.debian.org/doc/manuals/apt-howto/ch-apt-get.pt-br.html">apt-get</a>. For <a href="https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux_derivatives">Red Hat (or RHEL) based distros</a> use <a href="https://pt.wikipedia.org/wiki/Yellowdog_Updater,_Modified">yum</a> or <a href="https://en.wikipedia.org/wiki/DNF_(software)">dnf</a>. Search the best way to install eclipse using your package manager.</p><h4>macOS</h4><p>In macOS we have 2 options again:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.eclipse.org/downloads/packages">eclipse download page,</a> select the latest version (on the writing date of this guide is the <a href="https://www.eclipse.org/downloads/packages/release/2019-03/r/eclipse-ide-enterprise-java-developers"><strong>4.10</strong></a>) and install it as usual, dragging the app from the <em>.dmg</em> file to the apps folder of your mac.</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> (<a href="https://brew.sh/">Homebrew</a>)</li></ul><p>If you don’t know <em>Homebrew, </em>take a look at this post: <a href="https://medium.com/danielpadua/using-homebrew-for-macos-aa34b2e0c90c">https://medium.com/danielpadua/using-homebrew-for-macos-aa34b2e0c90c</a></p><p>Open your favorite terminal and install eclipse using the following command line:</p><pre>brew cask install eclipse-ide</pre><h4>Configuring eclipse</h4><p>With eclipse installed, I suggest you to open it and start getting used with the <a href="https://en.wikipedia.org/wiki/Graphical_user_interface">GUI</a> and also the <a href="https://www.vogella.com/tutorials/EclipseShortcuts/article.html">shortcut keys</a>.</p><blockquote><em>If you installed Spring Tool Suite, it’s not necessary to follow the installation of Spring Tools below</em></blockquote><h4>Spring Tools</h4><p>In order to have a better development experience with Spring, I recommend you to install the eclipse plugin: <em>Spring Tools</em>. Go to menu <em>Help &gt; Eclipse Marketplace… </em>and search for spring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8F3ISORsmudfGyec1IhEQ.png" /><figcaption>Installing Spring Tools</figcaption></figure><p>Install the latest version of <em>Spring Tools (</em>on the writing date of this guide it is the 4.2.1) and restart eclipse.</p><h3>Creating the project</h3><p>With everything correctly configured, it’s time to create our project. Go to menu: <em>File &gt; New &gt; Project…</em> and select the option <em>Spring starter Project </em>which is located below <em>Spring Boot</em> menu, as the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCPIBoDVPIKh4eVRtUZYQQ.png" /><figcaption>Starting the project</figcaption></figure><p>For this example, I’ll be using <a href="https://maven.apache.org/">Maven</a>as <a href="https://en.wikipedia.org/wiki/Build_automation"><em>build-tool</em></a><em>.</em></p><p>Fill the fields with the name of your artifact and groupId, and select the <em>Type</em> field as <em>Maven</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pc6iF4iWAJffFed54hqJTg.png" /><figcaption>Starting the project using Maven</figcaption></figure><p>After clicking next, we’ll have to especify which version of <em>Spring </em>we will be using. Select the latest stable version (on the writing date of this guide it’s the 2.1.4). As dependency, only select the <em>Web</em> and click <em>Finish</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TlOH1WwoJtCyiSN89tIKA.png" /><figcaption>Select Spring version and dependencies</figcaption></figure><p>Project created, now it’s time to create a <em>Controller</em> with a endpoint that will return a fixed String with the value: “Hello-World”. Right click the main package and select <em>New &gt; Class</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGg3dJBNJBjB90QQwedudA.png" /><figcaption>Creating a class</figcaption></figure><p>And create a class named “ExampleController” and fill the suffix of the package with “.controllers”, so a package named <em>controllers</em> will be created and nest your class, and it will group other controllers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNfgzHaYXMtUArHGDTSNBw.png" /><figcaption>Creating ExampleController</figcaption></figure><p>Use the code below to create the endpoint that will return “Hello-World!”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ac1d4e455b51d3f01321e10e417234/href">https://medium.com/media/18ac1d4e455b51d3f01321e10e417234/href</a></iframe><p>Run the project by clicking the button “Boot Dashboard” and then the tab “Boot Dashboard” at the bottom of the screen. Select the name of your project and click the run button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoABAnXB0IQtc7bE4URgdg.png" /><figcaption>Running the project</figcaption></figure><p>After clicking run button, you will see the output log of spring initialisation in console tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NSyRVMyq_YB_bWSfiJ6fQ.png" /><figcaption>Spring initialisation log</figcaption></figure><p>To test the project, you only have to open your favorite browser and access: <a href="http://localhost:8080/api/example/hello-world">http://localhost:8080/api/example/hello-world</a> and you should be seeing the <em>Hello World </em>message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*r0JE5y_X8kOM9u8Jv609sA.png" /><figcaption>Voilá</figcaption></figure><h3>Conclusion</h3><p>Eclipse and Spring Tool Suite (STS) are greate IDEs for developing robust java and spring based applications, and due to the stability of the tool, it ends up being super easy the ‘start’ of a simple project.</p><p>See you soon!</p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/java-spring-boot-eclipse"><em>https://blog.danielpadua.dev</em></a><em> on May 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744454468670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670">Java Spring Boot + Eclipse</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Spring Boot + IntelliJ IDEA]]></title>
            <link>https://medium.com/danielpadua/java-spring-boot-intellij-idea-b919b0097a0?source=rss-c291e71ea152------2</link>
            <guid isPermaLink="false">https://medium.com/p/b919b0097a0</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[intellij-idea]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Daniel Padua Ferreira]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 18:57:16 GMT</pubDate>
            <atom:updated>2021-07-12T00:21:24.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PahZ_GNmlc3C05JpNJ1vqA.png" /></figure><h3>Intro</h3><p>To those who develop in java nowadays, it’s almost impossible to miss <a href="https://spring.io/">Spring </a>framework and more specifically <a href="https://spring.io/projects/spring-boot">Spring Boot</a>. Using this <a href="https://en.wikipedia.org/wiki/Solution_stack">development stack</a>, we gain more productivity and agility from small to large sized java projects. In this guide I’ll demonstrate how to install, configure IntelliJ IDEA and create a simple Hello-World using java, IntelliJ IDEA and spring boot.</p><p>The github repository of the example project of this post, can be found at: <a href="https://github.com/danielpadua/java-spring-idea-example">https://github.com/danielpadua/java-spring-idea-example</a></p><h3>Requirements</h3><ul><li>Java JDK 8 or higher</li></ul><h3>Installing IntelliJ IDEA</h3><p>Use the following sections based in which operational system you’ll be using:</p><h4>Windows</h4><p>In Windows we have 2 options:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.jetbrains.com/idea/download/#section=windows">jetbrains download page</a>, select the latest version (on the writing date of this guide is the <strong>2019.1.1</strong>) and install it using NNF (next, next, next and finish).</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> (Chocolatey)</li></ul><p>If you don’t know <em>Chocolatey</em>, take a look at this post: <a href="https://medium.com/danielpadua/using-chocolatey-for-windows-878290cfb58d">https://medium.com/danielpadua/using-chocolatey-for-windows-878290cfb58d</a>.</p><p>Open <em>powershell</em> and install IntelliJ IDEA using the following command line:</p><pre>choco install intellijidea-community</pre><h4>Linux</h4><p>In Linux we also have 2 options:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.jetbrains.com/idea/download/#section=linux">jetbrains download page</a>, select the latest version (on the writing date of this guide is the <strong>2019.1.1</strong>), extract the <em>.tar.gz</em> file and execute the <em>/bin/idea.sh</em> file.</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a></li></ul><p>Depending in which Linux distro you are using, you’ll use a different package manager. For instance, <a href="https://en.wikipedia.org/wiki/Category:Debian-based_distributions">debian based distros</a>, like the popular <a href="https://www.ubuntu.com/">ubuntu</a>, use <a href="https://www.debian.org/doc/manuals/apt-howto/ch-apt-get.pt-br.html">apt-get</a>. For <a href="https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux_derivatives">Red Hat (or RHEL) based distros</a> use <a href="https://pt.wikipedia.org/wiki/Yellowdog_Updater,_Modified">yum</a> or <a href="https://en.wikipedia.org/wiki/DNF_(software)">dnf</a>. Search the best way to install IntelliJ IDEA using your package manager.</p><h4>macOS</h4><p>In macOS we have 2 options again:</p><ul><li>Direct download</li></ul><p>Go to <a href="https://www.jetbrains.com/idea/download/#section=mac">jetbrains download page</a>, select the latest version (on the writing date of this guide is the <strong>2019.1.1</strong>) and install it as usual, dragging the app from the <em>.dmg</em> file to the apps folder of your mac.</p><ul><li>Using a <a href="https://en.wikipedia.org/wiki/Package_manager">package manager</a> (<a href="https://brew.sh/">Homebrew</a>)</li></ul><p>If you don’t know <em>Homebrew, </em>take a look at this post: <a href="https://medium.com/danielpadua/using-homebrew-for-macos-aa34b2e0c90c">https://medium.com/danielpadua/using-homebrew-for-macos-aa34b2e0c90c</a></p><p>Open your favorite terminal and install IntelliJ IDEA using the following command line:</p><pre>brew cask install intellij-idea-ce</pre><h3>Configuring IntelliJ IDEA</h3><p>With IntelliJ IDEA installed, the configuration is pretty simple. When you execute IDEA you will be questioned about some configurations like: theme color, shortcut key mapping and plugins. Let’s leave default config and begin.</p><h3>Creating the project</h3><p>As soon as it starts, you’ll see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qipxdBKisBJll4R8vkbT6g.png" /><figcaption>IntelliJ IDEA initial screen</figcaption></figure><p>For this example, we’ll be using <a href="https://maven.apache.org/">Maven</a> as <a href="https://en.wikipedia.org/wiki/Build_automation"><em>build-tool</em></a><em>.</em></p><p>Unfortunately using IntelliJ IDEA Community, <a href="https://www.jetbrains.com/help/idea/spring-boot.html">according to the documentation</a>, there’s no support to create Spring Boot projects using Spring Initializr through the IDE in Community version, only in the Ultimate Edition. So, we have two choices that we can explore:</p><h4>Use Spring Initializr Web</h4><p>Access: <a href="https://start.spring.io/">https://start.spring.io</a>, and fill the fields like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY7Kc3Mt2XQE6u3-Zp897w.png" /><figcaption>Configuring project creation in Spring Initializr</figcaption></figure><p>Don’t forget to select <em>Web</em> as dependency. Click <em>Generate Project</em> to download the project <em>zip </em>file. Extract it to a directory of your choice, go back to IntelliJ IDEA and select <em>Import Project</em>. Navigate to project’s directory and select the <em>pom.xml</em> file. You’ll see a window that is responsible for importing the Maven project, leave the defaults configs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ddBVW8_xXpcvkmh8dYP-g.png" /><figcaption>Import Spring Initializr project</figcaption></figure><p>Select the project to import and click <em>next</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r6a4dfvfWWyYQTpt8W9-A.png" /><figcaption>Select the project</figcaption></figure><p>In the next screen, set the JDK version that you installed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQPui0d0aEDBrNP0qgJNlw.png" /><figcaption>Select the JDK version for the project</figcaption></figure><p>In the next screen confirm the project name and click <em>finish</em>.</p><h4>Creating a Maven project and add Spring manually</h4><p>In IntelliJ IDEA’s initial screen, select <em>Create New Project</em>, located on the left side tab and select <em>Maven</em>, on the right side, select the JDK version and click <em>next</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlnmHj8EWO3jEj2CkLCMhg.png" /><figcaption>Creating a Maven project</figcaption></figure><p>When selecting the archetype, IntelliJ IDEA will assume that you will use Quickstart archetype, which is ok for our goal.</p><p>In the next screen specify the GroupId, ArtifactId and the Version and click <em>next</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xNwew2mr25W4hcEMFBVqA.png" /><figcaption>Maven configuration</figcaption></figure><p>After you just have to name your project and click <em>finish</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GkDcxZaaFW4ZVd6G2AdtQ.png" /><figcaption>Naming the project</figcaption></figure><p>With the project created, configure <em>pom.xml</em> according to the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72958266f37e3c5ac329ed04f011ff00/href">https://medium.com/media/72958266f37e3c5ac329ed04f011ff00/href</a></iframe><p>After you update <em>pom.xml</em> a notification will pop-up at the inferior right side of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*EC51-L7yodep9xig7v-z-Q.png" /><figcaption>Import pom.xml changes</figcaption></figure><p>Click <em>Import Changes </em>for <em>Maven</em> refresh all project dependencies.</p><p>Now we’ll create a class that will contain the main function of the project. Remember that creating a class in default package is not a good java practice, so, click in source folder main/java and create a package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u11F0x1ikDtkoO3OfOTquA.png" /><figcaption>Creating a package</figcaption></figure><p>Write the name of the package, in my example was: <em>br.com.danielpadua.java_spring_idea_example</em>, and create a class inside this package named <em>ExampleApplication.java, </em>and write the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaae14921e0a79be80f4c5efdc31aaa1/href">https://medium.com/media/eaae14921e0a79be80f4c5efdc31aaa1/href</a></iframe><p>Don’t forget the unit tests main class too, repeat package creation step and create a class named: <em>ExampleApplicationTests.java </em>and write the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04538f80170c5db855c9e17618eadc58/href">https://medium.com/media/04538f80170c5db855c9e17618eadc58/href</a></iframe><p>At this moment we’ll have basically the same project structure that is generated by <em>Spring Initializr</em> at the section above.</p><h3>Completing the project</h3><p>With the basic project skeleton created, we just have to create a package to nest the controller that will contain Hello World endpoint. Right click the root package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uT9fFzmHGskcRhwjXbWPJQ.png" /><figcaption>Creating a package for the controllers</figcaption></figure><p>Write: <em>controllers</em> and confirm. Inside the generated package, create a class named: <em>ExampleController.java</em> and write the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2e057267b1b8d7948d2e76ee225b5a5/href">https://medium.com/media/c2e057267b1b8d7948d2e76ee225b5a5/href</a></iframe><p>Run the project by right clicking over the main class <em>Application.java</em> and select the option <em>Run ‘Application.main()’</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bOiALu-neYgPFFGbc5GNQ.png" /><figcaption>Running the app</figcaption></figure><p>After clicking run, you should see the output in the <em>Run</em> tab located at screen’s bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyjSnhGR31A4xHmjsRX9YA.png" /><figcaption>Spring initialisation log</figcaption></figure><p>To test the app, you only have to open your favorite browser and access: <a href="http://localhost:8080/api/example/hello-world">http://localhost:8080/api/example/hello-world</a>, and you should see the <em>Hello World </em>message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*GWbYhbp8yfaKTO0M1TMlZw.png" /><figcaption>Voilá</figcaption></figure><h3>Conclusion</h3><p>IntelliJ IDEA is the most used IDE for java nowadays and it’s probably the most complete in the opinion of many developers. Community version is a great alternative to traditional eclipse.</p><p>See you soon!</p><figure><a href="https://www.buymeacoffee.com/danielpadua"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aX8N3agTMMgqbcGnL0JXqQ.png" /></a><figcaption>If you found this post useful and would like to support me, you can do so by buying me a coffee using the button above!</figcaption></figure><p><em>Originally published at </em><a href="https://blog.danielpadua.dev/posts/java-spring-boot-intellij-idea"><em>https://blog.danielpadua.dev</em></a><em> on May 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b919b0097a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/danielpadua/java-spring-boot-intellij-idea-b919b0097a0">Java Spring Boot + IntelliJ IDEA</a> was originally published in <a href="https://medium.com/danielpadua">Daniel Padua Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>