<?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 Gustavo Miranda on Medium]]></title>
        <description><![CDATA[Stories by Gustavo Miranda on Medium]]></description>
        <link>https://medium.com/@gustavo-miranda?source=rss-e2462c9ee14b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u8j32T5HjhI71N_1AK7Cpw.png</url>
            <title>Stories by Gustavo Miranda on Medium</title>
            <link>https://medium.com/@gustavo-miranda?source=rss-e2462c9ee14b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:34:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gustavo-miranda/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[Como identificar alterações no @Input() do meu componente Angular?]]></title>
            <link>https://gustavo-miranda.medium.com/como-identificar-altera%C3%A7%C3%B5es-no-input-do-meu-componente-angular-ae50c602ef8b?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae50c602ef8b</guid>
            <category><![CDATA[angular-input]]></category>
            <category><![CDATA[detectar-alteracoes]]></category>
            <category><![CDATA[alteracoes-input-angular]]></category>
            <category><![CDATA[angular-component-input]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 15:44:06 GMT</pubDate>
            <atom:updated>2020-12-06T15:44:06.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Este pequeno tutorial é para auxiliar vocês a identificar de forma simples alterações nos <a href="https://angular.io/api/core/Input">@Input()</a> dos seus componentes.</p><figure><img alt="Um camaleão olhando para frente (eu acho), nas cores verde e vermelha e alguns tons de azul." src="https://cdn-images-1.medium.com/max/1024/1*yaoJA75zn0bEHugKKWeNAQ.jpeg" /><figcaption>Então seu componente é um camaleão?</figcaption></figure><h4>Direto ao ponto</h4><p>O mundo agora é um componente, seja lá qual seja a sua linguagem. E todos os componentes são dinâmicos e respiram o gerenciamento de estado sem parar.</p><p><em>E isso é a cara de uma gambiarra não é mesmo?</em></p><p>Para facilitar a nossa vida, vamos criar um componente de testes para brincar com estes eventos, ok? (caso não queira seguir o exemplo e ir direto para a aplicação da técnica, pule para Detectando as Alterações)</p><pre>ng g c color-change</pre><blockquote>A firma pediu para criarmos um quadrado que muda de cor, olha só que criativo… Porém, temos um cliente que abomina a cor vermelha e por ironia do destino, é neste cliente que vamos utilizar o nosso componente.</blockquote><p>Para atender ao caso, vamos criar este quadrado e definir uma cor default pra ele no nosso <a href="https://angular.io/api/core/Input">@Input()</a> de cor.</p><p>HTML:</p><pre>&lt;div class=&quot;color-change-square&quot; [ngStyle]=&quot;{ backgroundColor: color }&quot;&gt;&lt;/div&gt;</pre><p>SCSS/CSS:</p><pre>.color-change-square {<br>  width: 100px;<br>  height: 100px;<br>}</pre><p>Component.ts:</p><pre>import { <strong><em>Component</em></strong>, <strong><em>Input</em></strong>, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-color-change&#39;,<br>  templateUrl: &#39;./color-change.component.html&#39;,<br>  styleUrls: [&#39;./color-change.component.scss&#39;]<br>})<br>export class ColorChangeComponent implements OnInit {<br>  @Input() color: &#39;red&#39; | &#39;grey&#39; | &#39;blue&#39; | &#39;yellow&#39; = &#39;grey&#39;;<br><br>  constructor() { }<br><br>  ngOnInit(): void {<br>  }<br><br>}</pre><p>Tudo certo né? Chamei o meu componente no <strong>app-component.html </strong>dessa forma:</p><pre>&lt;app-color-change [color]=&quot;boxColor&quot;&gt;&lt;/app-color-change&gt;</pre><p>Para testar, criei um script simples que fica alterando a cor do componente:</p><pre>import { <strong><em>Component</em></strong>, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit {<br>  boxColor: string;<br>  colors = [&#39;red&#39;, &#39;grey&#39;, &#39;blue&#39;, &#39;yellow&#39;];<br>  colorIntervalRef: number;<br><br>  ngOnInit(): void {<br>    this.colorIntervalRef = this.changeColorInterval();<br>    setTimeout(() =&gt; {<br>      clearInterval(this.colorIntervalRef);<br>    }, 10000);<br>  }<br><br>  changeColorInterval(): number {<br>    return setInterval(() =&gt; {<br>      this.boxColor = this.colors[this.getRandomInt(0, this.colors.length)];<br>    }, 1000);<br>  }<br><br>  getRandomInt(min, max): number {<br>    min = <strong><em>Math</em></strong>.ceil(min);<br>    max = <strong><em>Math</em></strong>.floor(max);<br>    return <strong><em>Math</em></strong>.floor(<strong><em>Math</em></strong>.random() * (max - min)) + min;<br>  }<br>}</pre><p>Tudo certo? Creio que agora tenha um quadrado piscando em seu monitor.</p><p>Precisamos atender a regra de negócio, o cliente não quer de jeito nenhum a cor vermelha!</p><h3>Detectando as Alterações</h3><p>Atualmente, temos duas formas de detectar este tipo de comportamento no querido framework da Google, a primeira, utilizando o evento <a href="https://angular.io/api/core/OnChanges">ngOnChanges </a>que é disparado no <a href="https://angular.io/guide/lifecycle-hooks">ciclo de vida dos componentes Angular</a>:</p><h4>Utilizando o método do Ciclo de Vida do Angular, o ngOnChanges:</h4><ol><li>No seu componente, herde a interface OnChanges:</li></ol><pre>import { <strong><em>Component</em></strong>, <strong><em>Input</em></strong>, OnChanges, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-color-change&#39;,<br>  templateUrl: &#39;./color-change.component.html&#39;,<br>  styleUrls: [&#39;./color-change.component.scss&#39;]<br>})<br>export class ColorChangeComponent implements OnInit, OnChanges {<br>  @Input() color: &#39;red&#39; | &#39;grey&#39; | &#39;blue&#39; | &#39;yellow&#39; = &#39;grey&#39;;<br><br>  constructor() { }<br><br>  ngOnInit(): void {<br>  }</pre><pre>}</pre><p>2. Após herdar a interface, implemente o método ngOnChanges(o: SimpleChanges):</p><pre>ngOnChanges(changes: SimpleChanges): void {<br>  if (changes.color) {<br>    if (changes.color.currentValue === &#39;red&#39;) {<br>      <strong><em>console</em></strong>.warn(&#39;Infelizmente esta cor está desabilitada.&#39;);<br>      this.color = changes.color.previousValue;<br>    }<br>  }<br>}</pre><p>Dentro do <em>changes </em>o Angular vai trazer para nós todas as alterações no nosso componente, de todos os Inputs, para identificar as alterações basta verificar se o seu Input está dentro do objeto (naquele <em>if(changes.color) </em>eu verifico isso).</p><p>O Angular vai trazer o novo valor dentro do campo “<em>currentValue</em>” e também vai trazer o valor anterior em “<em>previousValue</em>”.</p><p>3. Agora é só fazer a regra de negócio! Eu fiz uma condição simples para verificar se o currentValue é o vermelho, se sim, ele vai logar para nós no console que a cor está desabilitada e também vai atribuir a última cor no componente.</p><p>Legal né?</p><h4><strong>Utilizando métodos Setters para identificar alterações no Input</strong></h4><p>Também podemos declarar o nosso Input() em um método Setter, o comportamento será o mesmo, para isso vamos modificar nosso componente da seguinte forma:</p><ol><li>Crie um método setColor() que vai realizar a operação para nós, anote este método com @Input():</li></ol><pre>import { <strong><em>Component</em></strong>, <strong><em>Input</em></strong>, OnChanges, OnInit, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-color-change&#39;,<br>  templateUrl: &#39;./color-change.component.html&#39;,<br>  styleUrls: [&#39;./color-change.component.scss&#39;]<br>})<br>export class ColorChangeComponent implements OnInit {<br>  color: &#39;red&#39; | &#39;grey&#39; | &#39;blue&#39; | &#39;yellow&#39; = &#39;grey&#39;;<br><br>  constructor() { }<br><br>  ngOnInit(): void {<br>  }<br><br>  @Input(&#39;color&#39;) set setColor(color: &#39;red&#39; | &#39;grey&#39; | &#39;blue&#39; | &#39;yellow&#39;) {<br>    if (!color) {<br>      color = &#39;grey&#39;;<br>    }<br><br>    if (color === &#39;red&#39;) {<br>      <strong><em>console</em></strong>.warn(&#39;Infelizmente esta cor está desabilitada.&#39;);<br>      return;<br>    }<br><br>    this.color = color;<br>  }<br><br>}</pre><p>Aqui eu já apliquei a mesma lógica que tínhamos anteriormente, o comportamento é o mesmo, fica a seu critério qual utilizar!</p><p>Gostou? Eu particularmente utilizo ambos, se for algo simples demais eu faço no OnChanges se é algo mais complexo eu faço no Setter.</p><p>Ambos os métodos estão certos, beleza?</p><p>Qualquer dúvida, é só chamar, comenta aqui ou me chama no <a href="https://www.linkedin.com/in/gustavovitormiranda/">LinkedIn</a>.</p><p>Abraços, <strong>bora codar!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae50c602ef8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recusei 7 propostas de emprego na área de software muito boas durante a pandemia e abri uma…]]></title>
            <link>https://gustavo-miranda.medium.com/recusei-7-propostas-de-emprego-na-%C3%A1rea-de-software-muito-boas-durante-a-pandemia-e-abri-uma-2086995bf248?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2086995bf248</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[empreendedorismo]]></category>
            <category><![CDATA[emprego]]></category>
            <category><![CDATA[filosofia]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 15:27:05 GMT</pubDate>
            <atom:updated>2020-06-25T12:35:07.658Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recusei 7 boas propostas de emprego na área de software durante a pandemia e abri uma Startup, loucura!</h3><p>E não foi fácil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*fKOd5npg4grP_ua-.jpg" /><figcaption>..think different.</figcaption></figure><p>Durante a pandemia que estamos vivendo eu recebi 7 propostas de emprego que qualquer um que ler este post vai dizer que sou louco por não aceitar alguma delas.</p><h4>O começo</h4><p>No início da pandemia, lá pelo mês de março eu estava trabalhando em uma empresa de desenvolvimento de software na cidade onde eu moro, não era ruim, a cultura da empresa era dinâmica, a galera era legal, porém eu não era feliz com a gestão que a empresa tinha. Esse sentimento sempre me corroeu, eu gosto de trabalhar por propósito e não dinheiro, e o propósito daquela empresa sempre foi claro, era apenas ganhar dinheiro.</p><p>Eu analisei todas as minhas skills, olhei para as skills da galera que estava comigo, bati na mesa e disse, nós podemos fazer muito mais que isso.</p><p>Tentei mudar lá dentro mesmo, fazia as coisas de uma forma um tanto quanto diferente, para mim, <strong>não existe chefe e se você se acha um você está completamente errado</strong>, para mim todos são donos do negócio, e quando você toma ação como dono, o negócio vai bem, e se o negócio lhe valoriza como um dono, você vai bem, e se um negócio tem todas essas qualidades e ainda tem um propósito que não seja apenas ganhar dinheiro, mas algo que contribua de forma significativa para a sociedade, meu querido amigo, minha querida amiga, satisfação total!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*0G_vl-x24j2EgBn1.jpg" /><figcaption>Créditos na Imagem :)</figcaption></figure><p>É óbvio que não dava certo. Eu sempre me via naquela situação chata que muitos passam calados, trabalhava bastante, olhava para o lado e meus colegas estavam vendo o portal de notícias ou qualquer outra besteira.</p><p>Criava uma coisa nova, um conceito de uma tecnologia, mostrava com entusiasmo para a colega ao lado e ela não fazia o mínimo esforço possível para entender e tentar alavancar esse conceito.</p><p>Somava “a” + “b” e resultava em uma pessoa indo trabalhar sem vontade e chegando em casa triste e pensando em desistir.</p><h4>Aí, veio a primeira proposta de emprego</h4><p>Não procurei essa proposta efetivamente, eu estava no meu perfil do LinkedIn e uma nova conexão apareceu, mandou aquela mensagem de briefing para tentar acertar a <em>hunting arrow.</em></p><p>O que aconteceu? Bom, até conversei com a pessoa que estava caçando, e era um caçador astuto, queria um regime PJ, fechadinho, sem muitos compromissos, desenvolvimento agora e pagamento no final do mês, uma proposta interessante para um desenvolvedor, sem dúvidas.</p><p>Porém, eu não queria atuar a noite, já que eu trabalhava em um, como eu posso dizer… <strong>projetinho pessoal, sabe?</strong></p><p>Recusei a primeira proposta ali, fiquei quieto, não contei nada em casa. Apenas toquei o barco.</p><h4>A segunda e a terceira proposta foi mais complicada</h4><p>Lembra que eu falei que aquela empresa onde eu trabalhava não era muito fã de propósito? Pois é, houve uma comemoração de seu aniversário no ano anterior e os diretores estavam lá, e eu tinha uma admiração ímpar com todos eles, pessoas que cresceram do pó até o império atual, sempre inspiram novas histórias.</p><p>Esse gestor derramava lágrimas e lágrimas contando sobre a empresa, e disse uma frase ícone que ninguém esquecera:</p><p>“Tirem tudo de mim, só não tirem os meus funcionários.”</p><p>Poucos meses depois, COVID-19, mais de 40 funcionários sumiram em uma das ondas de demissões, vários audios e vídeos horríveis do mesmo autor da frase foram soltos na internet por ele mesmo, ele não tinha nem vergonha, um deles até <strong>utilizando uma calcinha como máscara</strong>, e dando dicas para a população “inovar” no período de crise, enquanto isso meu pai, mais velho, ainda frentista em um posto de gasolina, precisando utilizar a máscara todos os dias para poder ganhar o pão do dia.</p><p>Aconteceram outras 2 ondas semelhantes a onda que eu mencionei anteriormente, e eu me vi em uma situação bem maluca:</p><p>“Pera, ele falou: …tirem tudo de mim, só não tirem os meus funcionários.”</p><p>“Eu lembro, eu estava lá, e esses videos? Meu Deus, <strong>eu trabalho para um idiota.</strong>”</p><p>Comecei a efetivamente procurar outro lugar para trabalhar, foi onde eu encontrei o case da <strong>Softplan</strong> e do <strong>Serasa Experian</strong>. Amigos já trabalhavam lá, e contavam que era outra vida, analisei os locais de forma bem critica, eu queria ir para um lugar onde eu não me sentisse trabalhando para um idiota.</p><p>As duas propostas mais difíceis de se recusar, o que dizer de uma proposta para trabalhar Home Office, ganhar um ótimo salário, sério, programador de 21 anos ganhando mais de R$5.000,00 ainda é insano pra mim, e ainda ter liberdade para atuar realmente com tecnologia?</p><p>É galera, eu disse que seriam propostas difíceis de recusar, e sim, com um peso enorme no coração eu disse não e logo vocês vão entender o por que.</p><p>Fiz o teste técnico da <strong>Softplan </strong>é uma aplicação bem interessante, nomeei ela de <strong>Erriagá, </strong>era um CRUD, com login OAuth2 utilizando o ecossistema Spring.</p><p>Fiz todo o processo de recrutamento da empresa, estava nas etapas finais, quando aconteceu…</p><h4>Abri minha Startup</h4><p>A 4° revolução industrial é maluca, ela acaba com empresas e iniciam outras em questão de segundos.</p><p>Lembra daquele… <strong>“projetinho pessoal?”</strong></p><p>O negócio ficou sério. Chamei os sócios para uma reunião de rotina e eu apresentei para eles tudo que estava acontecendo na minha vida tal qual eu falei para vocês agora pouco. E levei um pequeno “pitch” da nossa empresa para avaliarmos, <strong>na cara e na coragem mesmo, bem maluco. </strong>Eu apresentei pra eles e falei, por que não abrimos logo a nossa empresa de uma vez?</p><p>Já temos produto sendo validado, já temos outro produto engatilhado, já temos isso e aquilo, já temos valor, vamos colocar isso para funcionar!</p><p>E ali nasceu o embrião da nossa Startup (só não falo o nome ainda por que estamos em processos jurídicos de abertura, mas logo sai mais alguma coisa sobre e quem me acompanha vai poder verificar isso daí).</p><p><strong>Loucura demais! </strong>Iniciamos o projeto da empresa a 2 meses e estamos trabalhando duro para fazer as coisas acontecerem.</p><p>Rapidamente após a reunião eu peguei o meu celular e cancelei o processo seletivo na <strong>Softplan, </strong>agradeço muito pelo tempo gasto pelo time deles em tentar entender o meu talento e como eu ia encaixar-me na empresa, agradeço demais toda a atenção, diferente da empresa onde eu tinha um idiota como chefe, na Softplan eu teria verdadeiros líderes olhando para mim e nós estaríamos realmente construindo tecnologia.</p><p>E claro, agradeço também ao time do <strong>Serasa, </strong>não posso esquecer que lá também eu tive a mesma atenção e recusei pelos mesmos motivos.</p><h4>Depois disso, não para de chegar oportunidade na caixa!</h4><p>Foram 3 propostas que eu levei até o final e recusei na linha de chegada, foram mais 4 propostas que simplesmente agradeci e expliquei o motivo pelo qual eu não estou aberto, e acreditem se quiser, estou escrevendo este artigo agora e uma nova mensagem chegou com outra oportunidade, mesmo eu não procurando, mesmo eu estando com o alerta do LinkedIn desligado.</p><p><strong>Eu quero agradecer de coração a todos e todas dos times de hunting que estão fazendo este trabalho</strong> <strong>de procurar talentos</strong>, agradeço muito por acharem-me por que vocês me trazem uma sensação de segurança muito boa em saber que nós desenvolvedores <strong>temos espaço, temos oportunidades, e acima de tudo nós temos boas empresas buscando gente boa para trabalhar.</strong></p><h4>Qual é a minha dica?</h4><p>Meu amigo, minha amiga, eu aprendi muitas coisas, mas uma marcou-me muito no decorrer dessa experiência na pandemia, pare agora e analise para quem você trabalha, sério,<strong> como ele ou ela é?</strong> <strong>Existe um propósito que não seja apenas grana?</strong></p><p><strong>Será que você não está trabalhando para um idiota também?</strong></p><p>Não cometa esse erro, não gaste a sua faculdade ou os seus cursos para enriquecer um idiota ou uma idiota, no final, você vai ter trocado sua vida por dinheiro e não vai ter feito absolutamente nada, seja inteligente, a mudança começa por você e mais ninguém.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2086995bf248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minha experiência com uma ferramenta de prototipagem em 1 semana — Uma semana de Figma]]></title>
            <link>https://gustavo-miranda.medium.com/minha-experi%C3%AAncia-com-uma-ferramenta-de-prototipagem-em-1-semana-uma-semana-de-figma-3a01e807b7f?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a01e807b7f</guid>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[prototipagem]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[desenvolvimento]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Sat, 30 May 2020 13:27:02 GMT</pubDate>
            <atom:updated>2020-05-30T13:27:02.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>Minha experiência com uma ferramenta de prototipagem em 1 semana — Uma semana de Figma</h3><p>Trabalho como programador a algum tempo e nunca havia utilizado uma ferramenta de prototipagem antes, até que um dia recebi um protótipo para desenvolver seguindo ele, e descobri que precisava daquilo no meu cinto de utilidades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*NdNNUMLNaoGCW8zY.jpg" /><figcaption><em>“Sabe por que caímos?<br>Para aprendermos a levantar”</em></figcaption></figure><h4>A Pastelaria</h4><p>Para o cliente, qualquer tipo de produção é como produzir pastéis, principalmente quando a produção não é palpável, tal como um projeto de arquitetura, uma arte e no nosso caso, software.</p><p>É natural, não devemos culpá-los, alguns clientes entendem e outros não entendem o quão árduo é o processo de planejamento de um grande projeto, e se o Google Tradutor pudesse traduzir esse momento seria algo mais ou menos assim:</p><blockquote>“Me vê um de carne! .. (2 minutos depois) Perdão, cancela o de carne, quero um de Frango!”</blockquote><p>Projetistas geralmente estão com fome de entregar resultados, e sempre queremos colocar a mão na massa e já fazer o pastel, porém para nós, não são 2 minutos como a metáfora, passaram-se dias até que o cliente mude totalmente a ideia, e durante esse tempo, nós estávamos com a mão na massa.</p><h4>E depois?</h4><p>Depois os projetistas ficam de saco cheio, o projeto é muito legal, porém quando ocorre essas trocas de cenário durante o desenvolvimento do projeto tanto o projetista quanto quem está executando o projeto fica um tanto quanto chateado com essa história.</p><p>Claro que o cliente (quando eu falo cliente, pode ser o seu Product Owner, pode ser o seu Scrum Master, seu chefe, seu líder, qualquer um) vai querer mudar os requisitos, ele vai querer mudar o rumo das coisas e eu encontrei no Figma uma válvula de escape para essas situações.</p><p>Antes eu fazia os protótipos direto na linha de código, isso mesmo, programava as telas e não estava nem aí, queria ver o resultado, na minha cabeça era mais fácil desenhar no código, <strong>trazendo isso para números:</strong></p><p>Eu levava em média <strong>10 horas</strong> fazendo um protótipo utilizando o <strong>código puro</strong>.</p><p>Parece pouco tempo, porém o problema vem depois.</p><p>Fora <strong>10 horas </strong>programando! Se o cliente pedir qualquer alteração eu vou levar no mínimo <strong>30 minutos</strong> para alterar. Olha só o problema!</p><p>Em média, meus clientes pedem de 2 até 6 alterações em um protótipo, no melhor cenário eu teria que ficar mais de <strong>15 horas </strong>fazendo um protótipo.</p><p><strong>Figma</strong></p><p>Programadores, quem ainda não entendeu, entenda: <strong>time is money!</strong></p><p>Abri o Figma pela primeira vez para clicar no velho <strong>file-new-project</strong> na segunda-feira, dia 25, sem ver 1 vídeo no Youtube sobre ele, fui fuçar na ferramenta tal como nós fazemos na linguagem que estamos programando.</p><p>O primeiro resultado disso foi isso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*5Q9OAx4d2GfoiNxEYg2dXA.png" /><figcaption>Jesus, apaga a luz e leve meu computador.</figcaption></figure><p>É óbvio que está feio e deveras incompleto, mas isso foi um teste que fiz em 10 minutos, e olhe lá.</p><p>Decidi estudar um pouco mais e comecei a recriar alguns protótipos antigos que eu havia feito direto no código, aqui no Figma, e o resultado foi impressionante.</p><p>Passei 1 dia estudando a ferramenta e anotando como ela funcionava, depois descobri que eu posso apresentar o projeto pra qualquer um clicando no ícone de “play” na parte superior direita, e o melhor, <strong>gratuitamente! É free, é grátis!</strong></p><p>Decidi no final daquela segunda-feira que eu precisava deixar aquilo como primeira sacada do meu cinto de utilidades, e é claro que eu tinha um cenário real para aplicar.</p><p>Um cliente precisava de um site, de um aplicativo e de mil e uma coisas, eu disse a ele que apresentaria o aplicativo na terça-feira dia 26. Exatamente, no outro dia e olhe o que aconteceu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*RGe_js6L9bKvozeGMtWlBA.png" /><figcaption>É claro que não é só isso, tem mais coisas, porém não estou autorizado a divulgar ainda.</figcaption></figure><p>O projeto inteiro tem 10 telas, claro que é apenas um conceito inicial de tudo, porém toda a confecção do protótipo fora feita em menos de <strong>4 horas</strong>, uma manhã.</p><h4><strong>O que?! De 15 horas para 4 horas?!</strong></h4><p>Não, calma, lembra que eu falei que é pastelaria certo? O cliente vai pedir alterações ainda.</p><p>E não deu outra, apresentei para o cliente na terça-feira mesmo, de cara, ele adorou, até porque a reunião fora online e ele pode “utilizar o aplicativo” na apresentação do <strong>Figma, </strong>validamos todo o fluxo e veio as primeiras alterações de requisitos e por consequência, o protótipo seria afetado.</p><p>Revalidei os requisitos em meu caderninho aqui e logo alterei o protótipo, em 5 minutos durante a reunião com o cliente, e não foram poucas mudanças não! Água para o vinho:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*egU17cThdmOk1pbLrI0zSA.png" /><figcaption>Mudança não só de requisitos, mas de cores e conceitos.</figcaption></figure><p>Sim, eu alterei durante a reunião mesmo, e ele ficou encantado com a velocidade e praticidade do processo, ele estava vendo as telas enquanto eu alterava.</p><h4>Voltando para os números..</h4><p>Refiz boa parte do protótipo depois, é claro, não fora só as telas de login que sofreram alterações, no entanto, a reunião durou 1 hora e alteramos o protótipo, <strong>juntos</strong>, sim, cliente e programador juntos.</p><p><strong>Antes:</strong> <strong>10 horas</strong> de prototipagem direto no código, <strong>5 horas</strong> de alterações, tudo isso com o <strong>cliente aguardando no banco de reservas</strong>.</p><p><strong>Agora: 4 horas </strong>de prototipagem no <strong>Figma, 1 hora </strong>de alterações e com o cliente super animado ajudando no processo.</p><h4>No final</h4><p>Bom, no final eu estava conversando com o cliente com o projeto validado com a sua necessidade, agradeceu muito a forma como fora feito o processo, e já disse que ia me chamar para fazer outras coisas.</p><p>Logo fiz um site e a plataforma administrativa no mesmo design, aproveitando 100% de todos os componentes que eu já havia criado e na sexta-feira estava com tudo pronto para apresentar.</p><p>Fechei um bom projeto, já com o que eu tenho para fazer definido em 1 semana, aprendi ou desenvolvi uma nova forma de planejar software e ainda fui indicado!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*twxLzvq4tVRLNXzTmIUQqQ.png" /><figcaption>15 horas com código puro e 5 horas com o Figma.</figcaption></figure><p>Se você é desenvolvedor e ainda não utiliza alguma ferramenta de prototipagem, olha, recomendo bastante, mesmo que você trabalhe em uma grande empresa e tenha “um cara que faça isso”, é sempre bom você tem uma utilidade a mais em seu cinto.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a01e807b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Album Photo Application Using Flutter, Java and AWS S3]]></title>
            <link>https://medium.com/analytics-vidhya/creating-an-album-photo-application-using-flutter-java-and-aws-s3-1d421c432b0d?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d421c432b0d</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 21:53:15 GMT</pubDate>
            <atom:updated>2020-03-29T13:20:04.711Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a continuation of <a href="https://medium.com/analytics-vidhya/aws-s3-with-java-using-spring-boot-7f6fcf734aec">AWS S3 with Java using Spring Boot</a>. To do it you need to read it before, if you don’t want to write the Java code you can download the project from Github, the download link is in first post of this serie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-VDlv_lOH6dgfbzhujh_g.png" /><figcaption>Finished application.</figcaption></figure><h4>Application Usability</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3YWeojIZvYkeetxfCD7mqQ.gif" /><figcaption>Albums Page.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*fYCm9xApT6kVEY-rfurYKg.gif" /><figcaption>Insert Album Page.</figcaption></figure><p>To do this application you need:</p><ol><li>Intermediarie knowledge on Flutter.</li><li>Read <a href="https://medium.com/analytics-vidhya/aws-s3-with-java-using-spring-boot-7f6fcf734aec">AWS S3 with Java using Spring Boot</a> and the API running.</li><li>30 minutes to code.</li></ol><p><strong>Tecnologies Used in This Project</strong></p><ol><li>Slidy</li><li>Mobx (v.1.1.1)</li><li>Flutter Modular (v.1.0.0)</li><li>Json Serializable (v.3.3.0)</li><li>Flutter Form Builder (v.3.8.2)</li><li>Image Cropper (v1.2.1)</li><li>Image Picker (v0.6.4)</li></ol><h4>Slidy</h4><p>For this project we use <a href="https://pub.dev/packages/slidy">Slidy</a>.</p><p><a href="https://pub.dev/packages/slidy">Slidy</a> is a CLI for Flutter, project pattern can be make from it eas’ly and it include a lot of util dependencies.</p><h4>Installing Slidy</h4><p>To install it you can follow the tutorial on the project page on pub, <a href="https://pub.dev/packages/slidy">click here!</a></p><h4>Creating the Project</h4><p>First, start the API created on the first article. Started? <strong>Ok!</strong></p><p>Let’s go to the code. I show for you what I do when I code using Slidy, soo, create a clean project in Flutter running the command:</p><pre>flutter create photos_app</pre><p>Open the project on your own IDE, in my case, I will to use IntelliJ IDEA. And run the command:</p><pre>slidy start -f</pre><p>To provider, select defaults “flutter_modular”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*tvB8yms8hvlTpzlFkEKNrg.png" /><figcaption>Provider select.</figcaption></figure><p>State manager, select Mobx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*AUTkfefZX0RWNNn4sS8nkQ.png" /><figcaption>State manager select.</figcaption></figure><p>Run:</p><pre>flutter packages get</pre><p>Now, Slidy are create for us the basic structure of the project, after run this, your project like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fznpdu8Dke_IAiLokYv9PA.png" /><figcaption>Project pattern generated by Slidy CLI.</figcaption></figure><p>Now you have erros inside yours Controllers right? This thing ocurrer because Mobx need the <a href="https://dart.dev/tools/build_runner">flutter build runner</a> to generate code for us.</p><p>However, Slidy install it for us, now we need to call on terminal the command:</p><pre>flutter pub run build_runner watch</pre><p>Wait for the build runner complete your actions and “beep”, the errors are been destroyed.</p><h4>Install Dependencies</h4><p>Run these commmands:</p><pre>slidy install json_serializable<br>slidy install flutter_form_builder<br>slidy install transparent_image<br>slidy install image_picker</pre><p>After, run:</p><pre>flutter packages get</pre><p>To update dependencies.</p><h4>Undestanding About Slidy</h4><p>If you’re a Google Enthusiast you can spec about the project structure is most similar to Angular, you have a <em>AppModule</em>, you have a <em>Controllers </em>and <em>Views/Pages.</em></p><p>Modules on Slidy is a Class with the capability to provide singletons and organize your code, for example, the big AppModule is the main module on us application, because the main method call it for start the playground.</p><p>Slidy is thinking about the <strong>Flutter Web, </strong>because this your structure use Named Route instead the tradicional navigate on Flutter.</p><p>So, following the structure, the main calls the AppModule, and the first route on AppModule (“/”) call the HomeModule, and on HomeModule, we have an Page, the HomePage are called from the route “/” on HomeModule.</p><p>Easy no?</p><h4>The Repository on Flutter</h4><p>Yes, Slidy works using an structure similar to <strong>MVC </strong>(Model View Controller), but it have one particularity, the <strong>Repository </strong>layer.</p><p>Repositories in Flutter is class where we can call the APIs/Storages or, more simple, Databases.</p><p>Every data are manipulated from the Repository and the Controller have some business logic to controls the View.</p><h4>The Project</h4><p>The project arquiteture is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaglekURvOdNA_ZGGlUcwA.png" /><figcaption>Project arquiteture.</figcaption></figure><p>Well, come with me to create the basic’ly.</p><p>First, we need a Album class, that’s class represent for us the same on backend.</p><p>For do that, we need create the AmazonImage class before because Album have a List of it.</p><pre>import &#39;package:json_annotation/json_annotation.dart&#39;;<br><br>part &#39;amazon_image_model.g.dart&#39;;<br><br>@JsonSerializable()<br>class AmazonImageModel {<br>  AmazonImageModel({<br>    this.amazonUserImageId,<br>    this.imageUrl<br>  });<br><br>  String amazonUserImageId;<br>  String imageUrl;<br><br>  factory AmazonImageModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$AmazonImageModelFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$AmazonImageModelToJson(this);<br>}</pre><p>Now, we can create the Album class.</p><pre>import &#39;package:json_annotation/json_annotation.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/amazon/amazon_image_model.dart&#39;;<br><br>part &#39;album_model.g.dart&#39;;<br><br>@JsonSerializable()<br>class AlbumModel {<br>  AlbumModel({<br>    this.albumId,<br>    this.title,<br>    this.images<br>  });<br><br>  String albumId;<br>  String title;<br>  List&lt;AmazonImageModel&gt; images;<br><br>  factory AlbumModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$AlbumModelFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$AlbumModelToJson(this);<br>}</pre><p>Now, we need to do the Repository class, to call the backend, for it, we need to configure the API url.</p><p>Slidy uses Dio by default to make requests, and Dio have a lot of util configurations for us, for example, the base url of API.</p><p>To provide Dio with the basic options we need to code at AppModule, inside the binds list, an instance of Dio with the basic configurations like this:</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:photos_app/app/app_controller.dart&#39;;<br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:photos_app/app/app_widget.dart&#39;;<br>import &#39;package:photos_app/app/modules/home/home_module.dart&#39;;<br><br>class AppModule extends MainModule {<br>  @override<br>  List&lt;Bind&gt; get binds =&gt; [<br>        Bind((i) =&gt; AppController()),<br>        Bind((i) =&gt; Dio(BaseOptions(<br>          baseUrl: &#39;http://{api_url}:{api_port}&#39;<br>        )))<br>      ];<br><br>  @override<br>  List&lt;Router&gt; get routers =&gt; [<br>        Router(&#39;/&#39;, module: HomeModule()),<br>      ];<br><br>  @override<br>  Widget get bootstrap =&gt; AppWidget();<br><br>  static Inject get <em>to </em>=&gt; Inject&lt;AppModule&gt;.of();<br>}</pre><blockquote><strong>Remember! </strong>The Flutter runs on your emulator/phone device, on device, the URL be the exacly IP of your machine, because the “localhost” on your device call the device. So, when you up your backend remember to expose it on the your local web. (Generally is)</blockquote><p>In my case, the url like this: “baseUrl: ‘http://192.168.0.106:8080&#39;”</p><p>Cool, now we need to create an Repository to call the API. Slidy have a command to create the basic for us:</p><pre>slidy generate repository modules/shared/repository/album</pre><blockquote>If you get errors on tests folder, please, remove everything from them, Slidy auto generate tests for us, and this is not the focus of this tutorial.</blockquote><p>Slidy generate a repository on the path provided, modify this Repository with this code:</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:path/path.dart&#39;;<br><br>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/album/album_model.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/amazon/amazon_image_model.dart&#39;;<br><br>class AlbumRepository extends Disposable {<br>  final Dio dio;<br><br>  AlbumRepository({<br>    this.dio<br>  });<br><br>  // FindAllAlbums on Maker Resource in the backend.<br>  // This calls is one put because your filter, these request receive<br>  // an Album.class on backend to do an filter. :)<br>  Future&lt;List&lt;AlbumModel&gt;&gt; findAllAlbums(AlbumModel filter) async {<br>    // Call the backend, this method are asyncronous, than, await.<br>    // If any error throws an DioError. But these errors are responsibility of<br>    // controller to manipulate the screen state.<br>    Response&lt;List&gt; response = await dio.put(&#39;/album/search&#39;, data: filter);<br><br>    // Case success.<br>    if (_successResponse(response)) {<br>      return response.data.map&lt;AlbumModel&gt;((json) =&gt; AlbumModel.fromJson(json)).toList();<br>    } else {<br><br>      // Case error, return null.<br>      return null;<br>    }<br>  }<br><br>  // uploadImage send image to backend to send AWS S3.<br>  // This method receive an List of Images, because the<br>  // backend can receive an List of MultipartFile.<br>  Future&lt;List&lt;AmazonImageModel&gt;&gt; uploadImages(List&lt;File&gt; images) async {<br>    // Create the FormData from Dio.<br>    var formData = FormData();<br><br>    // Populate the formData files with the field &quot;images&quot;<br>    // Thats images for Dio is a MapEntry of String, MultipartFile,<br>    // easl&#39;y no? If you builded the backend, it receive an MultipartFile like Dio can send!<br>    formData.files.addAll(images.map&lt;MapEntry&lt;String, MultipartFile&gt;&gt;((image) =&gt; _createMapEntryFromFile(image)));<br><br>    // Now, is easy. Call the API.<br>    Response&lt;List&gt; response = await dio.post&lt;List&gt;(<br>        &#39;/amazon/images&#39;,<br>        data: formData,<br>        options: Options(<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>          }<br>        )<br>    );<br><br>    // Case success.<br>    if (_successResponse(response)) {<br>      return response.data.map&lt;AmazonImageModel&gt;((json) =&gt; AmazonImageModel.fromJson(json)).toList();<br>    } else {<br><br>      // Case error, return null.<br>      return null;<br>    }<br><br>  }<br><br>  // Insert the Album.<br>  Future&lt;AlbumModel&gt; insertAlbum(AlbumModel albumModel) async {<br>      Response&lt;Map&gt; response = await dio.post(&#39;/album&#39;, data: albumModel);<br><br>      // Case success.<br>      if (_successResponse(response)) {<br>        return AlbumModel.fromJson(response.data);<br>      } else {<br><br>        // Case error, return null.<br>        return null;<br>      }<br>  }<br><br>  MapEntry&lt;String, MultipartFile&gt; _createMapEntryFromFile(File image) {<br>    return MapEntry&lt;String, MultipartFile&gt;(&#39;images&#39;, MultipartFile<br>            .<em>fromFileSync</em>(image.path, filename: basename(image.path)));<br>  }<br><br>  @override<br>  void dispose() { }<br><br>  bool _successResponse(Response response) =&gt; response.statusCode &gt;= 200 &amp;&amp; response.statusCode &lt; 300;<br>}</pre><blockquote>I commented the code explain what I are doing on methods.</blockquote><p>Now we need to create the screens.</p><p>For do this, run the command:</p><pre>slidy generate module modules/album -c</pre><p>Inside the module, generate one additional page:</p><pre>slidy generate page modules/album/album_form</pre><p>Actually, this is my project pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVz9VI1eeBOKjvoJdtPsdg.png" /><figcaption>Project pattern.</figcaption></figure><p>Now, you can remove the HomeModule from the source, and change the principal route of your AppModule to call AlbumModule.</p><pre>import &#39;package:photos_app/app/modules/album/album_module.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/repository/album_repository.dart&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:photos_app/app/app_controller.dart&#39;;<br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:photos_app/app/app_widget.dart&#39;;<br><br>class AppModule extends MainModule {<br>  @override<br>  List&lt;Bind&gt; get binds =&gt; [<br>        // Inject to AlbumRepository the Dio instance.<br>        Bind((i) =&gt; AlbumRepository(<br>          dio: i.get()<br>        )),<br>        Bind((i) =&gt; AppController()),<br>        Bind((i) =&gt; Dio(BaseOptions(baseUrl: &#39;http://192.168.0.106:8080&#39;)))<br>      ];<br><br>  @override<br>  List&lt;Router&gt; get routers =&gt; [<br>        Router(&#39;/&#39;, module: AlbumModule()),<br>      ];<br><br>  @override<br>  Widget get bootstrap =&gt; AppWidget();<br><br>  static Inject get <em>to </em>=&gt; Inject&lt;AppModule&gt;.of();<br>}</pre><h4>Start from the basic concepts!</h4><p>To build the page we need to know: “Where are the album information now?” Following the project arquiteture, come with me to create the Controllers, the first Controller, AlbumController:</p><pre>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:mobx/mobx.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/album/album_model.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/repository/album_repository.dart&#39;;<br><br>part &#39;album_controller.g.dart&#39;;<br><br>class AlbumController = _AlbumBase with _$AlbumController;<br><br>abstract class _AlbumBase with Store {<br><br>  AlbumRepository _albumRepository = Modular.<em>get</em>();<br><br>  List&lt;AlbumModel&gt; albums = [];<br><br>  // Create an enumeraiton to easl&#39;y manage the page state.<br>  @observable<br>  AlbumState albumState = AlbumState.LOADING;<br><br>  @action<br>  fetchAlbums(AlbumModel filter) async {<br>    albumState = AlbumState.LOADING;<br><br>    albums = [];<br>    albums.addAll(await _albumRepository.findAllAlbums(filter));<br><br>    if (albums.length &gt; 0) {<br>      albumState = AlbumState.IDLE;<br>    } else {<br>      albumState = AlbumState.NOITENS;<br>    }<br><br>  }<br><br>}<br><br>enum AlbumState { IDLE, LOADING, NOITENS }</pre><p>Now, let’s go build a cool layout for this page.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_form_builder/flutter_form_builder.dart&#39;;<br>import &#39;package:flutter_mobx/flutter_mobx.dart&#39;;<br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:photos_app/app/modules/album/album_controller.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/album/album_model.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/amazon/amazon_image_model.dart&#39;;<br>import &#39;package:transparent_image/transparent_image.dart&#39;;<br><br>class AlbumPage extends StatefulWidget {<br>  final String title;<br><br>  const AlbumPage({Key key, this.title = &quot;Album&quot;}) : super(key: key);<br><br>  @override<br>  _AlbumPageState createState() =&gt; _AlbumPageState();<br>}<br><br>class _AlbumPageState extends ModularState&lt;AlbumPage, AlbumController&gt; {<br><br>  final GlobalKey&lt;RefreshIndicatorState&gt; _refreshIndicatorKey = new GlobalKey&lt;RefreshIndicatorState&gt;();<br>  final GlobalKey&lt;FormBuilderState&gt; _searchFormBuilderKey = new GlobalKey&lt;FormBuilderState&gt;();<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    controller.fetchAlbums(AlbumModel());<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        child: Icon(Icons.<em>add</em>),<br>        onPressed: () async {<br>          await Modular.<em>to</em>.pushNamed(&#39;/form&#39;);<br>          controller.fetchAlbums(AlbumModel());<br>        },<br>      ),<br>      body: SafeArea(<br>        child: Column(<br>          children: &lt;Widget&gt;[<br>            Container(<br>              padding: const EdgeInsets.all(16),<br>              child: Column(<br>                children: &lt;Widget&gt;[<br>                  Text(&#39;Albums&#39;, style: TextStyle(fontWeight: FontWeight.<em>bold</em>, fontSize: 26),),<br>                  SizedBox(height: 12,),<br>                  FormBuilder(<br>                    onChanged: (_) {<br>                      controller.fetchAlbums(AlbumModel.fromJson(_searchFormBuilderKey.currentState.value));<br>                    },<br>                    key: _searchFormBuilderKey,<br>                    initialValue: {<br>                      &#39;title&#39;: null<br>                    },<br>                    child: Column(<br>                      children: &lt;Widget&gt;[<br>                        FormBuilderTextField(<br>                          attribute: &#39;title&#39;,<br>                          maxLines: 1,<br>                          decoration: InputDecoration(<br>                            labelText: &#39;Search&#39;,<br>                            border: OutlineInputBorder(<br>                              borderRadius: BorderRadius.circular(40)<br>                            )<br>                          ),<br>                        )<br>                      ],<br>                    ),<br>                  )<br>                ],<br>              ),<br>            ),<br>            Expanded(<br>              child: Padding(<br>                padding: const EdgeInsets.all(16),<br>                child: Observer(builder: (_) {<br>                  if (controller.albumState == AlbumState.LOADING) {<br>                    return Center(<br>                      child: CircularProgressIndicator(),<br>                    );<br>                  } else if (controller.albumState == AlbumState.IDLE) {<br>                    return RefreshIndicator(<br>                      key: _refreshIndicatorKey,<br>                      onRefresh: () async {<br>                        _searchFormBuilderKey.currentState.reset();<br>                        await controller.fetchAlbums(AlbumModel());<br>                      },<br>                      child: ListView.builder(<br>                          itemCount: controller.albums.length, itemBuilder: (_, i) =&gt; _buildAlbumTile(controller.albums[i])),<br>                    );<br>                  } else {<br>                    return Container();<br>                  }<br>                }),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _buildAlbumTile(AlbumModel albumModel) {<br>    return GestureDetector(<br>      onTap: () {<br>        Modular.<em>to</em>.pushNamed(&#39;/form&#39;, arguments: albumModel);<br>      },<br>      child: Card(<br>        margin: EdgeInsets.only(bottom: 12),<br>        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),<br>        child: Padding(<br>          padding: const EdgeInsets.all(22.0),<br>          child: Column(<br>            children: &lt;Widget&gt;[<br>              Text(<br>                albumModel.title,<br>                style: TextStyle(fontSize: 22, fontWeight: FontWeight.<em>bold</em>),<br>              ),<br>              SizedBox(<br>                height: 12,<br>              ),<br>              Container(<br>                height: 120,<br>                child: ClipRRect(<br>                  borderRadius: BorderRadius.circular(40),<br>                  child: ListView.builder(<br>                    scrollDirection: Axis.horizontal,<br>                    itemCount: albumModel.images.length,<br>                    itemBuilder: (_, i) =&gt; _buildImage(albumModel.images[i]),<br>                  ),<br>                ),<br>              )<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _buildImage(AmazonImageModel amazonImageModel) {<br>    return ClipRRect(<br>      child: FadeInImage.memoryNetwork(<br>        placeholder: kTransparentImage,<br>        image: amazonImageModel.imageUrl,<br>        fit: BoxFit.cover,<br>        width: 120,<br>        height: 120,<br>      ),<br>    );<br>  }<br>}</pre><p>Simple beauty page!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*ym8CyTChK_EXXFtKQSXTTQ.png" /><figcaption>AlgumPage Widget.</figcaption></figure><p>Now, let’s go to create the AlbumFormController.</p><pre>import &#39;dart:io&#39;;<br><br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:mobx/mobx.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/album/album_model.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/repository/album_repository.dart&#39;;<br><br>part &#39;album_form_controller.g.dart&#39;;<br><br>class AlbumFormController = _AlbumFormBase with _$AlbumFormController;<br><br>abstract class _AlbumFormBase with Store {<br><br>  // Get Repository Instance<br>  AlbumRepository _albumRepository = Modular.<em>get</em>();<br><br>  // Simple logic to check if is editing or is insert new Album.<br>  AlbumModel savedAlbum;<br>  setSavedAlbum(AlbumModel albumModel) =&gt; savedAlbum = albumModel;<br><br>  // State Management<br>  @observable<br>  AlbumFormState albumFormState = AlbumFormState.IDLE;<br><br>  // Save Album<br>  @action<br>  saveAlbum(Map&lt;String, dynamic&gt; form) async {<br>    // Set state to Loading to disable form and save button.<br>    albumFormState = AlbumFormState.LOADING;<br><br>    // Capture typed fields from form.<br>    List images = form[&#39;images&#39;] as List;<br>    String title = form[&#39;title&#39;] as String;<br><br>    // Get images to send to Amazon.<br>    List&lt;File&gt; imageNotSaved = images.where((image) =&gt; image is File).whereType&lt;File&gt;().toList();<br>    if (savedAlbum == null) {<br><br>      // New Album<br>      AlbumModel albumModel = AlbumModel(<br>        // First, upload images to Amazon.<br>        images: await _albumRepository.uploadImages(imageNotSaved),<br>        title: title<br>      );<br><br>      // Save Album<br>      await _albumRepository.insertAlbum(albumModel);<br>      Modular.<em>to</em>.pop();<br>      albumFormState = AlbumFormState.IDLE;<br>    } else {<br>      // <em>TODO: Update Album Here<br>    </em>}<br>    albumFormState = AlbumFormState.IDLE;<br>  }<br><br>}<br><br>enum AlbumFormState { IDLE, LOADING }</pre><p>Awesome, now, we need to create a CustomFormBuilderField for the images.</p><p>Create a Widget called ImageSourceSheet like this:</p><pre>import &#39;dart:io&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:image_picker/image_picker.dart&#39;;<br><br>class ImageSourceSheet extends StatelessWidget {<br><br>  final Function(File) onImageSelected;<br><br>  ImageSourceSheet({ @required this.onImageSelected });<br><br>  void imageSelected(File image) async {<br>    if (image != null) {<br>      onImageSelected(image);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      child: Wrap(<br>        children: &lt;Widget&gt;[<br>          ListTile(<br>            leading: Icon(Icons.<em>camera_enhance</em>),<br>            title: Text(&#39;Camera&#39;),<br>            onTap: () async {<br>              File image = await ImagePicker.<em>pickImage</em>(source: ImageSource.camera);<br>              imageSelected(image);<br>            },<br>          ),<br>          ListTile(<br>            leading: Icon(Icons.<em>image</em>),<br>            title: Text(&#39;Gallery&#39;),<br>            onTap: () async {<br>              File image = await ImagePicker.<em>pickImage</em>(source: ImageSource.gallery);<br>              imageSelected(image);<br>            },<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>With this Widget we have this cool “Image Picker”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*h9Fy0DVH8_Xlsfov_apIcw.png" /><figcaption>ImageSourceSheet Widget.</figcaption></figure><p>Now, create one FormBuilderImageField, like this:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_form_builder/flutter_form_builder.dart&#39;;<br>import &#39;package:photos_app/app/modules/album/album_form/image_source_sheet.dart&#39;;<br><br>class FormBuilderImageField extends StatefulWidget {<br>  final String attribute;<br>  final List&lt;FormFieldValidator&gt; validators;<br>  final List initialValue;<br>  final bool readOnly;<br>  final String labelText;<br>  final ValueTransformer valueTransformer;<br>  final ValueChanged onChanged;<br><br>  final double imageWidth;<br>  final double imageHeight;<br>  final EdgeInsets imageMargin;<br>  final FormFieldSetter onSaved;<br><br>  const FormBuilderImageField({<br>    Key key,<br>    @required this.attribute,<br>    this.initialValue,<br>    this.validators = const [],<br>    this.valueTransformer,<br>    this.labelText,<br>    this.onChanged,<br>    this.imageWidth = 130,<br>    this.imageHeight = 130,<br>    this.imageMargin,<br>    this.readOnly = false,<br>    this.onSaved<br>  }) : super(key: key);<br><br>  @override<br>  _FormBuilderImageFieldState createState() =&gt; _FormBuilderImageFieldState();<br>}<br><br>class _FormBuilderImageFieldState extends State&lt;FormBuilderImageField&gt; {<br>  bool _readOnly = false;<br>  List _initialValue;<br>  final GlobalKey&lt;FormFieldState&gt; _fieldKey = GlobalKey&lt;FormFieldState&gt;();<br>  FormBuilderState _formState;<br><br>  @override<br>  void initState() {<br>    _formState = FormBuilder.<em>of</em>(context);<br>    _formState?.registerFieldKey(widget.attribute, _fieldKey);<br>    _initialValue = List.of(widget.initialValue ??<br>        (_formState.initialValue.containsKey(widget.attribute)<br>            ? _formState.initialValue[widget.attribute]<br>            : []));<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    _formState?.unregisterFieldKey(widget.attribute);<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    _readOnly = (_formState?.readOnly == true) ? true : widget.readOnly;<br><br>    return FormField&lt;List&gt;(<br>      key: _fieldKey,<br>      enabled: !_readOnly,<br>      initialValue: _initialValue,<br>      validator: (val) {<br>        for (int i = 0; i &lt; widget.validators.length; i++) {<br>          if (widget.validators[i](val) != null)<br>            return widget.validators[i](val);<br>        }<br>        return null;<br>      },<br>      onSaved: (val) {<br>        var transformed;<br>        if (widget.valueTransformer != null) {<br>          transformed = widget.valueTransformer(val);<br>          _formState?.setAttributeValue(widget.attribute, transformed);<br>        } else<br>          _formState?.setAttributeValue(widget.attribute, val);<br>        if (widget.onSaved != null) {<br>          widget.onSaved(transformed ?? val);<br>        }<br>      },<br>      builder: (state) =&gt; Column(<br>        crossAxisAlignment: CrossAxisAlignment.start,<br>        children: &lt;Widget&gt;[<br>          Text(<br>            widget.labelText != null ? widget.labelText : &#39;Images&#39;,<br>            style: TextStyle(<br>              color: Theme.<em>of</em>(context).primaryColor<br>            ),<br>          ),<br>          SizedBox(<br>            height: 8,<br>          ),<br>          Container(<br>            height: widget.imageHeight,<br>            child: ListView(<br>              scrollDirection: Axis.horizontal,<br>              children: state.value.map&lt;Widget&gt;((item) {<br>                return Container(<br>                  width: widget.imageWidth,<br>                  height: widget.imageHeight,<br>                  margin: widget.imageMargin,<br>                  child: GestureDetector(<br>                    child: item is String ?<br>                      Image.network(item, fit: BoxFit.cover) :<br>                      Image.file(item, fit: BoxFit.cover),<br>                    onLongPress: () {<br>                      state.didChange(state.value..remove(item));<br>                    },<br>                  ),<br>                );<br>              }).toList()<br>                ..add(<br>                  GestureDetector(<br>                    child: Container(<br>                      width: widget.imageWidth,<br>                      height: widget.imageHeight,<br>                      child: Icon(<br>                        Icons.<em>camera_enhance</em>,<br>                        color: Theme.<em>of</em>(context).primaryColor,<br>                      ),<br>                      color: Theme.<em>of</em>(context).primaryColor.withAlpha(50),<br>                    ),<br>                    onTap: () {<br>                      showModalBottomSheet(context: context, builder: (_) {<br>                        return ImageSourceSheet(<br>                          onImageSelected: (image) {<br>                            state.didChange(state.value..add(image));<br>                            Navigator.<em>of</em>(context).pop();<br>                          },<br>                        );<br>                      });<br>                    },<br>                  )<br>                )<br>            ),<br>          ),<br>          state.hasError<br>              ? Text(<br>            state.errorText,<br>            style: TextStyle(color: Colors.<em>red</em>, fontSize: 12),<br>          ) : Container()<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Very nice, that is this component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*rIByzmsOnbbp7lC3CoSoQg.png" /><figcaption>FormBuilderImageField Widget.</figcaption></figure><p>Now, create your AlbumFormPage like this:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_form_builder/flutter_form_builder.dart&#39;;<br>import &#39;package:flutter_mobx/flutter_mobx.dart&#39;;<br>import &#39;package:flutter_modular/flutter_modular.dart&#39;;<br>import &#39;package:photos_app/app/modules/album/album_form/album_form_controller.dart&#39;;<br>import &#39;package:photos_app/app/modules/album/album_form/form_builder_image_field.dart&#39;;<br>import &#39;package:photos_app/app/modules/shared/models/album/album_model.dart&#39;;<br><br>class AlbumFormPage extends StatefulWidget {<br>  final AlbumModel savedAlbum;<br><br>  const AlbumFormPage({Key key, this.savedAlbum}) : super(key: key);<br><br>  @override<br>  _AlbumFormPageState createState() =&gt; _AlbumFormPageState();<br>}<br><br>class _AlbumFormPageState extends ModularState&lt;AlbumFormPage, AlbumFormController&gt; {<br>  AlbumModel _value;<br>  Map&lt;String, dynamic&gt; _initialValue;<br><br>  final GlobalKey&lt;FormBuilderState&gt; _albumFormBuilderKey = new GlobalKey&lt;FormBuilderState&gt;();<br><br>  @override<br>  void initState() {<br>    _value = widget.savedAlbum;<br>    controller.setSavedAlbum(_value);<br><br>    if (_value != null) {<br>      _initialValue = {<br>        &#39;albumId&#39;: _value.albumId,<br>        &#39;images&#39;: _value.images.map&lt;String&gt;((image) =&gt; image.imageUrl).toList(),<br>        &#39;title&#39;: _value.title<br>      };<br>    } else {<br>      _initialValue = {<br>        &#39;albumId&#39;: null,<br>        &#39;title&#39;: null,<br>        &#39;images&#39;: []<br>      };<br>    }<br><br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SafeArea(<br>        child: Column(<br>          children: &lt;Widget&gt;[<br>            Row(<br>              children: &lt;Widget&gt;[<br>                IconButton(<br>                  icon: Icon(Icons.<em>arrow_back</em>),<br>                  onPressed: () {<br>                    Modular.<em>to</em>.pop();<br>                  },<br>                ),<br>                Padding(<br>                  padding: const EdgeInsets.only(left: 26),<br>                  child: Text(<br>                    &#39;New Album&#39;,<br>                    style: TextStyle(fontWeight: FontWeight.<em>bold</em>, fontSize: 26),<br>                  ),<br>                ),<br>                Expanded(<br>                  child: Padding(<br>                    padding: const EdgeInsets.only(right: 8.0),<br>                    child: Observer(<br>                      builder: (_) =&gt; Align(<br>                        alignment: Alignment.<em>centerRight</em>,<br>                        child: IconButton(<br>                          icon: Icon(Icons.<em>save</em>),<br>                          onPressed: controller.albumFormState == AlbumFormState.LOADING ? null : () {<br>                            if (_albumFormBuilderKey.currentState.saveAndValidate()) {<br>                              controller.saveAlbum(_albumFormBuilderKey.currentState.value);<br>                            }<br>                          },<br>                        ),<br>                      ),<br>                    ),<br>                  ),<br>                )<br>              ],<br>            ),<br>            Expanded(<br>              child: ListView(<br>                padding: const EdgeInsets.all(16),<br>                children: &lt;Widget&gt;[<br>                  Observer(<br>                    builder: (_) =&gt; FormBuilder(<br>                      readOnly: controller.albumFormState == AlbumFormState.LOADING,<br>                      key: _albumFormBuilderKey,<br>                      initialValue: _initialValue,<br>                      child: Column(<br>                        children: &lt;Widget&gt;[<br>                          FormBuilderImageField(<br>                            attribute: &#39;images&#39;,<br>                            validators: [<br>                              (images) {<br>                                if (images is List) {<br>                                  if (images.isEmpty) {<br>                                    return &#39;Images are required.&#39;;<br>                                  }<br>                                }<br>                                return null;<br>                              }<br>                            ],<br>                          ),<br>                          SizedBox(<br>                            height: 20,<br>                          ),<br>                          FormBuilderTextField(<br>                            maxLines: 1,<br>                            attribute: &#39;title&#39;,<br>                            decoration: InputDecoration(<br>                                labelText: &#39;Title&#39;,<br>                                border: OutlineInputBorder(<br>                                    borderRadius: BorderRadius.circular(40)<br>                                )<br>                            ),<br>                            validators: [<br>                              FormBuilderValidators.<em>required</em>(),<br>                              FormBuilderValidators.<em>maxLength</em>(64)<br>                            ],<br>                          ),<br>                        ],<br>                      ),<br>                    ),<br>                  )<br>                ],<br>              ),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>I have documented the Controller for explain the State Management of this screen, but it is simple.</p><p>This is my project pattern now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_yS3d30G-ngtECC3NomHQ.png" /><figcaption>Project Pattern.</figcaption></figure><p>Cool!<br>The application is done.</p><p>But I have one challenge for you. I don’t implement in this project the possibility to user update your Album, and this is your challenge.</p><p>You need to change the controller because the editing an pré behavior for editing I maded.</p><p><strong>The link for this project: </strong><a href="https://github.com/gustavovitor/photo_app">https://github.com/gustavovitor/photo_app</a></p><p>If you have any question about this, comment, or send a private message on my <a href="https://www.linkedin.com/in/gustavo-m-369a3011b/">LinkedIn</a>.</p><p>If you make the challenge, send it on GitHub :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d421c432b0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/creating-an-album-photo-application-using-flutter-java-and-aws-s3-1d421c432b0d">Creating an Album Photo Application Using Flutter, Java and AWS S3</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Standardizing Spring Boot Applications With Maker Project]]></title>
            <link>https://medium.com/analytics-vidhya/standardizing-spring-boot-applications-with-maker-project-449d906917fd?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/449d906917fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 01:49:54 GMT</pubDate>
            <atom:updated>2020-03-25T12:29:39.318Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of standard frameworks are built every day, but, if you stop to think, yours applications in the most of cases, not standardized. I touch you now? :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*E0wgBldJV1sTy0Lc" /><figcaption>Pattern, pattern, pattern.</figcaption></figure><p>Look this shape, now think how the designer made this. Did you know? Well, when I are designer, I make one standard shape, and kick the notebook on Ctrl + C and Ctrl + V a lot of times and make it!</p><p>Thinking about this, I made the <a href="https://github.com/gustavovitor/maker">Maker Project</a>. With this project you can speed up your Restful API development using Spring Boot.</p><h4>Where are the standard shape on Maker?</h4><p>I think soo you have made a lot of APIs in your career, and (if these APIs are builded using MVC pattern) these APIs have a lot of CRUDs, and <strong>Services</strong> working with <strong>Repositories</strong> and <strong>Entities</strong>, and everything is exposed on web with an <strong>RestController</strong>. You built these APIs every time, and every time you write your Repositories, your Service, and your Controller, the same code inside your Controller calling your Service methods in all of your APIs. <strong>Really?!</strong></p><p>Please, change the page and think about Standard Pattern for your APIs!</p><p>For example, your API needs expose for web an CRUD resource about your Customer, cool everything normal about this, you write your Entity, your Repository and your Controller, implements the business rules inside your service, made your JPA rules on your Entity, and very well, job done, but you lost <strong>45–60 minutes</strong> doing this,<strong> time is money bro!</strong></p><p>Using <a href="https://github.com/gustavovitor/maker">Maker Project</a> you can create your pattern, and transform this 45–60 minutes in <strong>10–20 minutes</strong> doing the same API, with plus!</p><p><strong>Let me show an example for you!</strong></p><p>Create your Entity using Spring Data JPA, normally, alright?</p><pre>@Data<br>@Entity<br>class Car {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    <br>    private String model; <br>}</pre><p>Awesome, now, create your Repository, but now, extend RepositoryMaker instead JpaRepository.</p><pre>public interface CarRepository extends RepositoryMaker&lt;Car, Long&gt; {}</pre><p><strong>Why? RepositoryMaker</strong> implements for us the Spring Boot Specification Executor, with this, you can make queries inside iterables Spring Boot default repository, for example, the <em>findAll()</em> method.</p><p>Very well, now, the Maker needs an Specification for this class, to work well.</p><pre>public class CarSpecification extends SpecificationBase&lt;Car&gt; {<br><br>    public CarSpecification(Car car) throws ReflectionException {<br>        super(car);<br>    }<br><br>    @Override<br>    public Predicate toPredicate(Root&lt;Car&gt; root, CriteriaQuery&lt;?&gt; criteriaQuery, CriteriaBuilder criteriaBuilder) {<br>        List&lt;Predicate&gt; predicates = new ArrayList&lt;&gt;();<br><br>        if (nonNull(getObject().getModel())) {<br>            predicates.add(criteriaBuilder.like(root.get(&quot;model&quot;), &quot;%&quot; + getObject().getModel() + &quot;%&quot;));<br>        }<br><br>        return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));<br>    }<br>}</pre><p>Look on the method <em>toPredicate(), </em>this method are called before Spring Data runs the <em>findAll() </em>on your database, and look that, <strong>root, criteriaQuery and criteriaBuilder! </strong>You can go to the moon using this bro!</p><p>Here, using Maker, you can create and build your query, without depends to use the JPQL.</p><p>Very cool. Now, create an Service for your Entity.</p><pre>@Service<br>public class CarService extends ServiceMaker&lt;CarRepository, Car, Long, Car, CarSpecification&gt; {}</pre><p><strong>Stop!</strong> Ok, now is the cherry on the cake now.<strong> ServiceMaker </strong>produces for us a standardizing methods for your CRUD, (like <a href="https://developers.redhat.com/courses/quarkus/panache/">Redhat Panache</a> does), using on <strong>ServiceMaker </strong>we have methods like:</p><ol><li><em>findAllPageable() — Call the repository and returns a Spring Boot Standard page of your Entity.</em></li><li><em>findAll() — Call the repository and return an list of your Entity.</em></li><li><em>findById() — Find your Entity by Id.</em></li><li><em>beforeInsert() — Used for business rules, implement your RuntimeException here and create another pattern for API Exception Handler.</em></li><li><em>insert() — Call Repository insert method.</em></li><li><em>beforeUpdate() — Used for business rules, the same behavior of beforeInsert().</em></li><li><em>update() — Copy all properties of the object are send to save and use the save method on Repository.</em></li><li><em>beforePatch() — Used for business rules, the same behavior of beforeInsert().</em></li><li><em>patch() — Copy not empty properties of the object are send to save and use the save method on Repository.</em></li><li><em>beforeDelete() — Used for business rules, the same behavior of beforeInsert().</em></li><li><em>delete() — Delete the entity using delete method of Repository.</em></li></ol><p>Every methods are prebui with an standard implementation. The <em>before </em>methods are specifically for business rules implementations.</p><p>You can see now? The time are reduced from 30 minutes to 8–10 minutes now, the developer can <strong>focus your time on business logic instead verbose code.</strong></p><p>So, we need an controller now, alright?</p><pre>@RestController<br>@RequestMapping(&quot;/car&quot;)<br>public class CarResource extends ResourceMaker&lt;CarService, Car, Long, Car&gt; {}</pre><p>Simple like the Service. Using the pattern of Service, why Controller cannot be a pattern soo?</p><p><strong>ResourceMaker </strong>made for us all calls using the pattern created by <strong>ServiceMaker, </strong>awesome?</p><p>The Maker made for us API calls like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*lRSDq-IFyzJvKS4EYLXLqw.png" /><figcaption>Maker calls generated by ResourceMaker.</figcaption></figure><p>All methods you need to work with an CRUD. Why<strong> &quot;Get All Cars&quot; </strong>and<strong> &quot;Get All Cars Pageable&quot; </strong>use PUT HTTP verb?</p><p>These method receive two objects to work, the SpecificationObject, implemented before to do search and (on Pageable method) the Pageable object, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*At7cYojY5eK_1lmRFyRQ7w.png" /><figcaption>ResourceMaker search pageable request.</figcaption></figure><p>Soo, to simplify the implementation and simplify the usability of the &quot;framework&quot;, we need to sen an body with these information.</p><p>And the Spring Security PreAuthorize rules?</p><p>If you use Spring Security with PreAuthorize its simple, Maker have the <strong>SecurityResourceMaker </strong>with this maker you can override methods about PreAuthorize roles permissions. Today maker works with roles.</p><h4>I can use?</h4><p>Yes! Everyone can use the project, I&#39;m using this in production environment on four projects, and I want to use in more projects in the future, Maker made everything I need on API and make an standardized API, I can create another pattern on front-end to consume it, and reduces more my development time.</p><p>The link for the Maker Project: <a href="https://github.com/gustavovitor/maker">https://github.com/gustavovitor/maker</a></p><p>An live example: <a href="https://github.com/gustavovitor/maker-example">https://github.com/gustavovitor/maker-example</a></p><p>MongoDB example (Maker Mongo using QueryDsl instead Specification): <a href="https://github.com/gustavovitor/maker-example/tree/maker-mongo">https://github.com/gustavovitor/maker-example/tree/maker-mongo</a></p><p>Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=449d906917fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/standardizing-spring-boot-applications-with-maker-project-449d906917fd">Standardizing Spring Boot Applications With Maker Project</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS S3 with Java using Spring Boot]]></title>
            <link>https://medium.com/analytics-vidhya/aws-s3-with-java-using-spring-boot-7f6fcf734aec?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6fcf734aec</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 19:10:22 GMT</pubDate>
            <atom:updated>2021-10-22T13:41:47.140Z</atom:updated>
            <content:encoded><![CDATA[<h4>A functional tutorial, creating a Photo Album project.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*meDufEEM20Q9HTWA-oPGoA.png" /><figcaption>Spring + AWS S3 + Maker Project</figcaption></figure><p>Today I will show for you how to make this work, to do this you need:</p><ol><li>Intermediate knowledge with Spring Framework</li><li>AWS Account</li><li>Java 11+ and Maven</li><li>MongoDB</li></ol><h4>I like to start from the Backend</h4><p>Is more simple do it from the backend, for this, we need to create a Bucket on AWS S3. Buckets is an simple abstraction for us know <em>“where are my files?”.</em></p><h4>Preparing AWS S3</h4><p>In your AWS Console go to Storage Session and click on S3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*q5DhSw2hiMd4TFRpQbmY9g.png" /><figcaption>AWS &gt; Storage &gt; S3</figcaption></figure><p>Click on <strong>“Create bucket”</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xp2unzAEmtuWIzcy-wHsuQ.png" /><figcaption>Amazon S3 — Buckets screen</figcaption></figure><p>Now, you need to inform basic information about your bucket, for you identify it after for future maintain (the bucket name is unique on all Amazon S3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNvDB2O0JHkaTltmlGhREw.png" /><figcaption>Create bucket form</figcaption></figure><p>Alright, now you have a bucket on AWS S3, now we need create a<strong> “Access Key”</strong> and <strong>“Secret Key”</strong> to access your bucket on <strong>AWS Java SDK. </strong>Back to the AWS Console and search <strong>“IAM </strong>on <strong>Security, Identity, &amp; Compliance”</strong> group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*_kQ9aUw_I3S8VkwXWS_2vg.png" /><figcaption>AWS &gt; Security, Identity, &amp; Compliance &gt; IAM</figcaption></figure><p>Don’t scary with this panel, we don’t need to change anything here, go to <strong>“Users”</strong> menu and click on <strong>“Add user”:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Fq_ZpPr-I03ybsyih0TNg.png" /><figcaption>Create user on AWS</figcaption></figure><p>Follow the steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*G0RzNTsG9B7e8tYdQCyirA.png" /><figcaption>Create user on AWS — Step 1 — User Informations</figcaption></figure><p>Now, on second step, you need to select<strong> “AmazonS3FullAccess” </strong>because this user will be add/remove images from your bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*lZ3HlNzfnnIuAoqzpeghgg.png" /><figcaption>Create user on AWS — Step 2 — Permissions</figcaption></figure><p>Step 3,<strong> “Add tags” </strong>is optional, so, go to Step 4, <strong>“Review”</strong> and <strong>“Create user”.</strong></p><p>Right, now, on Step 5, AWS show for us your<strong> “Access key ID” </strong>and the <strong>“Secret access key”, copy and don’t forget this!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*nZtEVspdPHft7uHLltl0fA.png" /><figcaption>Create user on AWS — Step 5 — Access Key and Secret Key</figcaption></figure><h4>Creating Spring Project</h4><p>Consider you have an intermediate knowledge on Spring Framework, go to <a href="https://start.spring.io/">Spring Initializr</a> and create your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjVN5KjC8RplbA_n9GXiDg.png" /><figcaption>Spring Initializr — Step 1 — Project Information</figcaption></figure><p>With these dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXF7iK1-t-hfDzLp6pyrdA.png" /><figcaption>Spring Initializr — Step 2— Dependencies</figcaption></figure><p>Now, click on <strong>“Generate”.</strong></p><p>Unzip your project and open on your favorite IDE, in my case IntelliJ.</p><p>First, we need to import the <strong>AWS Java SDK </strong>in the project, go to your <strong>“pom.xml” </strong>and add the dependency:</p><pre>&lt;!-- Maker, to create the API more faster --&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;com.github.gustavovitor&lt;/groupId&gt;<br>   &lt;artifactId&gt;maker-mongo&lt;/artifactId&gt;<br>   &lt;version&gt;${maker-mongo.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;!-- Amazon S3 --&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>   &lt;artifactId&gt;aws-java-sdk&lt;/artifactId&gt;<br>   &lt;version&gt;${amazon-sdk.version}&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- Apache Commons for FileUtils and misc. --&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;commons-io&lt;/groupId&gt;<br>   &lt;artifactId&gt;commons-io&lt;/artifactId&gt;<br>   &lt;version&gt;${commons-io.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Properties:</p><pre>&lt;properties&gt;<br>    &lt;java.version&gt;11&lt;/java.version&gt;<br>    &lt;maker-mongo.version&gt;0.0.6&lt;/maker-mongo.version&gt;<br>    &lt;amazon-sdk.version&gt;1.11.728&lt;/amazon-sdk.version&gt;<br>    &lt;commons-io.version&gt;2.6&lt;/commons-io.version&gt;<br>&lt;/properties&gt;</pre><p>Alright, basicly <strong>AWS Java SDK </strong>works like a API, you need to make one call on AWS API and send yours files to bucket.</p><p>Add these properties on <strong>application.properties</strong>:</p><pre>amazon.s3.bucket-name=awesome-project-java-flutter<br>amazon.s3.endpoint=https://awesome-project-java-flutter.s3-sa-east-1.amazonaws.com/<br>amazon.s3.access-key=${ACCESS_KEY}<br>amazon.s3.secret-key=${SECRET_KEY}</pre><p>For more security, create two environment variables in your machine, <strong>ACCESS_KEY</strong> and <strong>SECRET_KEY</strong> and populate it with IAM informations.</p><p>Now, create a AmazonClientService:</p><pre>package com.github.gustavovitor.photos.service.amazon;</pre><pre>import com.amazonaws.auth.AWSStaticCredentialsProvider;<br>import com.amazonaws.auth.BasicAWSCredentials;<br>import com.amazonaws.regions.Regions;<br>import com.amazonaws.services.s3.AmazonS3;<br>import com.amazonaws.services.s3.AmazonS3ClientBuilder;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br><br>import javax.annotation.PostConstruct;<br><br>@Service<br>public class AmazonClientService {<br><br>    // AmazonS3 Client, in this object you have all AWS API calls about S3.<br>    private AmazonS3 amazonS3;<br><br>    // Your bucket URL, this URL is https://{bucket-name}.s3-{region}.amazonaws.com/<br>    // If you don&#39;t know if your URL is ok, send one file to your bucket using AWS and<br>    // click on them, the file URL contains your bucket URL.<br>    @Value(&quot;${amazon.s3.endpoint}&quot;)<br>    private String url;<br><br>    // Your bucket name.<br>    @Value(&quot;${amazon.s3.bucket-name}&quot;)<br>    private String bucketName;<br><br>    // The IAM access key.<br>    @Value(&quot;${amazon.s3.access-key}&quot;)<br>    private String accessKey;<br><br>    // The IAM secret key.<br>    @Value(&quot;${amazon.s3.secret-key}&quot;)<br>    private String secretKey;<br><br>    // Getters for parents.<br>    protected AmazonS3 getClient() {<br>        return amazonS3;<br>    }<br><br>    protected String getUrl() {<br>        return url;<br>    }<br><br>    protected String getBucketName() {<br>        return bucketName;<br>    }<br><br>    // This method are called after Spring starts AmazonClientService into your container.<br>    @PostConstruct<br>    private void init() {<br><br>        // Init your AmazonS3 credentials using BasicAWSCredentials.<br>        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);<br><br>        // Start the client using AmazonS3ClientBuilder, here we goes to make a standard cliente, in the<br>        // region SA_EAST_1, and the basic credentials.<br>        this.amazonS3 = AmazonS3ClientBuilder.<em>standard</em>()<br>                .withRegion(Regions.<em>SA_EAST_1</em>)<br>                .withCredentials(new AWSStaticCredentialsProvider(credentials))<br>                .build();<br>    }<br><br>}</pre><p>Okay, with this client you can extends them to use the online client.</p><p>Now, we need to save basic informations about the AWS Images, for do this, we goes to create a simple domain/document:</p><pre>package com.github.gustavovitor.photos.domain.amazon;</pre><pre>import lombok.Data;<br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.mapping.Document;<br><br>import javax.validation.constraints.NotNull;<br><br>@Data<br>@Document<br>public class AmazonImage {<br><br>    @Id<br>    private String amazonUserImageId;<br><br>    @NotNull<br>    private String imageUrl;<br><br>}</pre><p>Following the Spring, create a Repository for it:</p><pre>package com.github.gustavovitor.photos.repository.amazon;<br><br>import com.github.gustavovitor.photos.domain.amazon.AmazonImage;<br>import org.springframework.data.mongodb.repository.MongoRepository;<br><br>public interface AmazonImageRepository extends MongoRepository&lt;AmazonImage, String&gt; {<br>}</pre><p>Spring provide for us one especificly Form Data called <strong>MultipartFile</strong>, but you can’t upload this type on your bucket, bucket need a <strong>java.io.File </strong>instead. So, for do this conversion, we need create a Util class like this:</p><pre>package com.github.gustavovitor.photos.util;<br><br>import org.springframework.web.multipart.MultipartFile;<br><br>import java.io.File;<br>import java.io.FileOutputStream;<br>import java.io.IOException;<br>import java.util.Date;<br>import java.util.Objects;<br><br>public class FileUtils {<br><br>    public static File convertMultipartToFile(MultipartFile file) throws IOException {<br>        File convertedFile = new File(Objects.<em>requireNonNull</em>(file.getOriginalFilename()));<br>        FileOutputStream fileOutputStream = new FileOutputStream(convertedFile);<br>        fileOutputStream.write(file.getBytes());<br>        fileOutputStream.close();<br>        return convertedFile;<br>    }<br><br>    public static String generateFileName(MultipartFile multipartFile) {<br>        return new Date().getTime() + &quot;-&quot; + Objects.<em>requireNonNull</em>(multipartFile.getOriginalFilename()).replace(&quot; &quot;, &quot;_&quot;);<br>    }<br><br>}</pre><p>Awesome, now we can do a service to send images to bucket:</p><pre>package com.github.gustavovitor.photos.service.amazon;<br><br>import com.amazonaws.services.s3.model.CannedAccessControlList;<br>import com.amazonaws.services.s3.model.DeleteObjectRequest;<br>import com.amazonaws.services.s3.model.PutObjectRequest;<br>import com.github.gustavovitor.photos.domain.amazon.AmazonImage;<br>import com.github.gustavovitor.photos.repository.amazon.AmazonImageRepository;<br>import com.github.gustavovitor.photos.service.amazon.except.FileConversionException;<br>import com.github.gustavovitor.photos.service.amazon.except.InvalidImageExtensionException;<br>import com.github.gustavovitor.photos.service.amazon.util.AmazonClientService;<br>import com.github.gustavovitor.photos.util.FileUtils;<br>import com.github.gustavovitor.util.MessageUtil;<br>import lombok.extern.log4j.Log4j2;<br>import org.apache.commons.io.FilenameUtils;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import java.io.File;<br>import java.io.IOException;<br>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@Log4j2<br>@Service<br>public class AmazonS3ImageService extends AmazonClientService {<br><br>    @Autowired<br>    private AmazonImageRepository amazonImageRepository;<br><br>    // Upload a List of Images to AWS S3.<br>    public List&lt;AmazonImage&gt; insertImages(List&lt;MultipartFile&gt; images) {<br>        List&lt;AmazonImage&gt; amazonImages = new ArrayList&lt;&gt;();<br>        images.forEach(image -&gt; amazonImages.add(uploadImageToAmazon(image)));<br>        return amazonImages;<br>    }<br><br>    // Upload image to AWS S3.<br>    public AmazonImage uploadImageToAmazon(MultipartFile multipartFile) {<br><br>        // Valid extensions array, like jpeg/jpg and png.<br>        List&lt;String&gt; validExtensions = Arrays.<em>asList</em>(&quot;jpeg&quot;, &quot;jpg&quot;, &quot;png&quot;);<br><br>        // Get extension of MultipartFile<br>        String extension = FilenameUtils.<em>getExtension</em>(multipartFile.getOriginalFilename());<br>        if (!validExtensions.contains(extension)) {<br>            // If file have a invalid extension, call an Exception.<br>            <em>log</em>.warn(MessageUtil.<em>getMessage</em>(&quot;invalid.image.extesion&quot;));<br>            throw new InvalidImageExtensionException(validExtensions);<br>        } else {<br><br>            // Upload file to Amazon.<br>            String url = uploadMultipartFile(multipartFile);<br><br>            // Save image information on MongoDB and return them.<br>            AmazonImage amazonImage = new AmazonImage();<br>            amazonImage.setImageUrl(url);<br><br>            return amazonImageRepository.insert(amazonImage);<br>        }<br><br>    }<br><br>    public void removeImageFromAmazon(AmazonImage amazonImage) {<br>        String fileName = amazonImage.getImageUrl().substring(amazonImage.getImageUrl().lastIndexOf(&quot;/&quot;) + 1);<br>        getClient().deleteObject(new DeleteObjectRequest(getBucketName(), fileName));<br>        amazonImageRepository.delete(amazonImage);<br>    }<br><br>    // Make upload to Amazon.<br>    private String uploadMultipartFile(MultipartFile multipartFile) {<br>        String fileUrl;<br><br>        try {<br>            // Get the file from MultipartFile.<br>            File file = FileUtils.<em>convertMultipartToFile</em>(multipartFile);<br><br>            // Extract the file name.<br>            String fileName = FileUtils.<em>generateFileName</em>(multipartFile);<br><br>            // Upload file.<br>            uploadPublicFile(fileName, file);<br><br>            // Delete the file and get the File Url.<br>            file.delete();<br>            fileUrl = getUrl().concat(fileName);<br>        } catch (IOException e) {<br><br>            // If IOException on conversion or any file manipulation, call exception.<br>            <em>log</em>.warn(MessageUtil.<em>getMessage</em>(&quot;multipart.to.file.convert.except&quot;), e);<br>            throw new FileConversionException();<br>        }<br><br>        return fileUrl;<br>    }<br><br>    // Send image to AmazonS3, if have any problems here, the image fragments are removed from amazon.<br>    // Font: https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3Client.html#putObject%28com.amazonaws.services.s3.model.PutObjectRequest%29<br>    private void uploadPublicFile(String fileName, File file) {<br>        getClient().putObject(new PutObjectRequest(getBucketName(), fileName, file)<br>                .withCannedAcl(CannedAccessControlList.<em>PublicRead</em>));<br>    }<br><br>}</pre><p>This is my project right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*4UK7W5RiRvA_e4rvDb8sPA.png" /><figcaption>Project Design Pattern</figcaption></figure><p>If you read this post for AWS S3, this is everything you need to know, after this, I will show for you codes about <a href="https://github.com/gustavovitor/maker">Maker Project</a> and Flutter (Flutter in another post, this post is too long).</p><h4>Building a Simple Photo Album API</h4><p>This API is very simple, we need one API route to upload photos and other route to get information about these photos, right? So I want to use the <a href="https://github.com/gustavovitor/maker">Maker Project</a> to do this for us.</p><p><a href="https://github.com/gustavovitor/maker">Maker Project</a> is an abstraction to speed up the development time of RestAPI using Spring Framework, who?</p><p>Every pardonized API needs a lot of CRUD’s (Create Read Update Delete) operations, and these CRUD’s can cost time, and time for me is too short. Thinking this, I created for my personal projects the Maker, with this, I can build an CRUD API in 10 minutes, with all business rules applied.</p><p>Using <a href="https://github.com/gustavovitor/maker">Maker Project</a> you can focus all of your time in business rules.</p><p>So, let’s go to create the Album entity:</p><pre>package com.github.gustavovitor.photos.domain.album;<br><br>import com.github.gustavovitor.photos.domain.amazon.AmazonImage;<br>import lombok.Data;<br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.mapping.Document;<br><br>import javax.validation.constraints.NotBlank;<br>import javax.validation.constraints.NotNull;<br>import javax.validation.constraints.Size;<br>import java.util.List;<br><br>@Data<br>@Document<br>public class Album {<br><br>    @Id<br>    private String albumId;<br><br>    @Size(max = 64)<br>    @NotNull<br>    @NotBlank<br>    private String title;<br><br>    // A list of AmazonImage, for this simple project, the AmazonImage is one request<br>    // and AlgumPhoto is another request.<br>    private List&lt;AmazonImage&gt; images;<br><br>}</pre><p>Okay, now we need create a SpecificationObject for the Album (Maker requirements):</p><pre>package com.github.gustavovitor.photos.repository.album.spec;<br><br>import com.github.gustavovitor.maker.repository.MongoSpecificationBase;<br>import com.github.gustavovitor.photos.domain.album.Album;<br>import com.github.gustavovitor.photos.domain.album.QAlbum;<br>import com.querydsl.core.BooleanBuilder;<br>import com.querydsl.core.types.Predicate;<br><br>import javax.management.ReflectionException;<br><br>import static java.util.Objects.<em>nonNull</em>;<br><br>public class AlbumSpecification extends MongoSpecificationBase&lt;Album&gt; {<br>    public AlbumSpecification(Album object) throws ReflectionException {<br>        super(object);<br>    }<br><br>    @Override<br>    public Predicate toPredicate() {<br>        BooleanBuilder builder = new BooleanBuilder();<br>        if (<em>nonNull</em>(getObject().getTitle())) {<br>            builder.and(QAlbum.<em>album</em>.title.containsIgnoreCase(getObject().getTitle()));<br>        }<br>        return builder;<br>    }<br>}</pre><p>Where is <strong>QAlbum.class</strong>? QAlbum is generated using one plugin to do this, add on your pom.xml, inside build plugins this:</p><pre>&lt;!-- Code Generation QueryDsl --&gt;<br>&lt;plugin&gt;<br>   &lt;groupId&gt;com.mysema.maven&lt;/groupId&gt;<br>   &lt;artifactId&gt;apt-maven-plugin&lt;/artifactId&gt;<br>   &lt;version&gt;1.1.3&lt;/version&gt;<br>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.querydsl&lt;/groupId&gt;<br>         &lt;artifactId&gt;querydsl-apt&lt;/artifactId&gt;<br>         &lt;version&gt;4.2.2&lt;/version&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br>   &lt;executions&gt;<br>      &lt;execution&gt;<br>         &lt;phase&gt;generate-sources&lt;/phase&gt;<br>         &lt;goals&gt;<br>            &lt;goal&gt;process&lt;/goal&gt;<br>         &lt;/goals&gt;<br>         &lt;configuration&gt;<br>            &lt;outputDirectory&gt;target/generated-sources/apt&lt;/outputDirectory&gt;<br>            &lt;processor&gt;<br>               org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor<br>            &lt;/processor&gt;<br>            &lt;logOnlyOnError&gt;true&lt;/logOnlyOnError&gt;<br>         &lt;/configuration&gt;<br>      &lt;/execution&gt;<br>   &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>After, run the command “<em>mvn clean install -DskipTests” </em>to generate code.</p><blockquote>Note: You need to specify to your IDE where is the generated source root, in my case, using IntelliJ, I need to right click on /target/generated-sources and Mark Directory As -&gt; Generated Sources Root.</blockquote><p>Now, we need create a repository:</p><pre>package com.github.gustavovitor.photos.repository.album;<br><br>import com.github.gustavovitor.maker.repository.MongoRepositoryMaker;<br>import com.github.gustavovitor.photos.domain.album.Album;<br><br>public interface AlbumRepository extends MongoRepositoryMaker&lt;Album, String&gt; {<br>}</pre><blockquote>Note: extends MongoRepositoryMaker, using the Maker Project to do methods for us.</blockquote><p>Alright, now, create a service:</p><pre>package com.github.gustavovitor.photos.service.album;<br><br>import com.github.gustavovitor.maker.service.MongoServiceMaker;<br>import com.github.gustavovitor.photos.domain.album.Album;<br>import com.github.gustavovitor.photos.repository.album.AlbumRepository;<br>import com.github.gustavovitor.photos.repository.album.spec.AlbumSpecification;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class AlbumService extends MongoServiceMaker&lt;AlbumRepository, Album, String, Album, AlbumSpecification&gt; {<br>    @Override<br>    public void beforeInsert(Album object) {<br>        // Business rules here.<br>    }<br><br>    @Override<br>    public void beforeUpdate(String objectId, Album object) {<br>        // Business rules here.<br>    }<br><br>    @Override<br>    public void beforePatch(Album object) {<br>        // Business rules here.<br>    }<br><br>    @Override<br>    public void beforeDelete(String objectId) {<br>        // Business rules here.<br>    }<br>}</pre><p>Maker Project do for us a lot of methods, inside MongoServiceMaker you can see these methods.</p><p>Alright, now, we need to create the resources/endpoints:</p><pre>package com.github.gustavovitor.photos.resource.album;<br><br>import com.github.gustavovitor.maker.resource.MongoResourceMaker;<br>import com.github.gustavovitor.photos.domain.album.Album;<br>import com.github.gustavovitor.photos.service.album.AlbumService;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/album&quot;)<br>public class AlbumResource extends MongoResourceMaker&lt;AlbumService, Album, String, Album&gt; {<br><br>}</pre><p>Finally, one more resource/endpoint for Amazon:</p><pre>package com.github.gustavovitor.photos.resource.amazon;<br><br>import com.github.gustavovitor.photos.domain.amazon.AmazonImage;<br>import com.github.gustavovitor.photos.service.amazon.AmazonS3ImageService;<br>import lombok.Getter;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestPart;<br>import org.springframework.web.bind.annotation.RestController;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import java.util.List;<br><br>@Getter<br>@RestController<br>@RequestMapping(&quot;/amazon&quot;)<br>public class AmazonResource {<br><br>    @Autowired<br>    private AmazonS3ImageService amazonS3ImageService;<br><br>    @PostMapping(&quot;/images&quot;)<br>    public ResponseEntity&lt;List&lt;AmazonImage&gt;&gt; insertImages(@RequestPart(value = &quot;images&quot;) List&lt;MultipartFile&gt; images) {<br>        return ResponseEntity.<em>ok</em>(getAmazonS3ImageService().insertImages(images));<br>    }<br><br>}</pre><h4>Let’s Go Test-it?</h4><p>First, configure your MongoDB access on application.properties like this:</p><pre>spring.data.mongodb.host=172.17.0.2<br>spring.data.mongodb.database=photo</pre><p><strong>And start your Spring Application.</strong></p><blockquote>Note: if you get error about SecurityAutoConfiguration, exclude this class on your SpringBootApplication, this error are caused because Maker Project include Spring Security dependencies.</blockquote><pre>package com.github.gustavovitor.photos;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;<br><br>@SpringBootApplication(exclude = SecurityAutoConfiguration.class)<br>public class PhotosApplication {<br><br>   public static void main(String[] args) {<br>      SpringApplication.<em>run</em>(PhotosApplication.class, args);<br>   }<br><br>}</pre><p>First, come with me and test the AmazonResource, open your Postman or another application to call the API and call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-YB6EQmOcxSc-zn6DsoiA.png" /><figcaption>Amazon Resource response.</figcaption></figure><p><strong>Awesome!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*Tdr4-3xvqZnBlAPW9iU_AA.gif" /><figcaption>Happy! Happy! Happy!</figcaption></figure><p>Checkout your Amazon bucket now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygAKBXpY5rlSjnFjvl6ZtQ.png" /><figcaption>Oh my God!</figcaption></figure><p>Okay, okay, calm down! Now, you need to get the response of the request to make the Album request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xw4E4boK6JB9LJnNi8nUPg.png" /><figcaption>Insert album request.</figcaption></figure><p><strong>What?! Post? 201 Created? What? </strong>Yeah! Maker do this for us, everything we need to do this CRUD, the Maker Project do for us.</p><p>You can do request for your API like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZRGIDROW3Hn-nKAxUnKBQ.png" /><figcaption>Get all Album Filtered request.</figcaption></figure><p>For more information about <a href="https://github.com/gustavovitor/maker">Maker Project</a> please read the documentation on GitHub!</p><p><strong>See?</strong> Send images to AWS S3 is simple, and more faster with Maker!</p><p>If you have any question about this, comment, or send a private message on my <a href="https://www.linkedin.com/in/gustavo-m-369a3011b/">LinkedIn</a>.</p><p><strong>Integrate this API with a Flutter project following this another lesson: </strong><a href="https://medium.com/analytics-vidhya/creating-an-album-photo-application-using-flutter-java-and-aws-s3-1d421c432b0d">https://medium.com/analytics-vidhya/creating-an-album-photo-application-using-flutter-java-and-aws-s3-1d421c432b0d</a></p><p>The code of this API: <a href="https://github.com/gustavovitor/photo-album">https://github.com/gustavovitor/photo-album</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f6fcf734aec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/aws-s3-with-java-using-spring-boot-7f6fcf734aec">AWS S3 with Java using Spring Boot</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empresário, você precisa de um Programador]]></title>
            <link>https://gustavo-miranda.medium.com/empres%C3%A1rio-voc%C3%AA-precisa-de-um-programador-e4307644daca?source=rss-e2462c9ee14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4307644daca</guid>
            <category><![CDATA[negocios]]></category>
            <category><![CDATA[tecnologia]]></category>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[empresarios]]></category>
            <dc:creator><![CDATA[Gustavo Miranda]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 00:46:33 GMT</pubDate>
            <atom:updated>2020-02-03T03:30:43.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>A sua empresa precisa de um Programador.</h3><p>Sim, você precisa de um programador, todos nós precisamos de um programador por perto, um programador nos dias atuais não é mais um programador que você conheceu a 20 anos atrás, um programador nos dias atuais é um talento que não pode faltar em seu negócio.</p><h4>Por quê?</h4><p>Creio que sua empresa já tenha um sistema que faça a gestão do seu negócio, e apresenta a você dados extremamente confiáveis para a tomada das suas decisões. Certo?</p><p>Digamos que você tenha uma revenda de produtos no atacado, você não recebe clientes em sua loja, apenas faz o <a href="https://www.significados.com.br/delivery/"><em>delivery</em></a> de mercadorias para a cidade, região ou até mesmo o estado, uma empresa como esta precisa de um sistema que se encaixe com o seu dia a dia.</p><p>Porém, este mesmo sistema que realiza tantos controles, peca drasticamente num dos controles essenciais do negócio, no controle de frotas, ele até gerencia muito bem todas as informações da frota, porém é antigo, é ruim de utilizar, o seu supervisor de frotas reclama dele dia após dia, diz que o sistema é de difícil manuseio, e que poderia controlar a frota de uma forma mais fácil e rápida, e acaba largando o sistema no seu dia a dia para utilizar planilhas.</p><p>Isso é bem chato, você paga a mensalidade do software e ainda sim precisa utilizar planilhas para controlar o seu negócio.</p><p>Grande parte dos softwares são desenvolvidos para um modelo de negócio e não gostam de receber modificações que alterem este modelo, visto que este mesmo software está inserido em vários clientes diferentes que utilizam este modelo.</p><p>A empresa que desenvolve este software vai cobrar muito caro, muito caro mesmo para alterar o modelo de seu software, para que ele se adeque a este novo cenário e que possa, ainda sim, atender os seus outros clientes.</p><h4>Ta, mas e daí, onde entra o programador que eu preciso?</h4><p>Um dos principais motivos pelo qual você precisa de um programador na sua empresa é sem dúvidas a flexibilidade para lidar com o problema acima.</p><p>O programador que você precisa é aquela pessoa fora da caixa, que vai solucionar este problema e outros problemas da melhor forma para o seu negócio.</p><p>No exemplo acima, o seu <a href="https://www.significados.com.br/delivery/"><em>delivery</em></a>, por exemplo, precisará ter um controle de frotas que seja fácil de utilizar, que substitua a planilha que o seu supervisor está utilizando. O programador começa a atuar neste tipo de cenário, onde ele possa transformar um processo chato e repetitivo, principalmente os repetitivos, em um trabalho mais fácil e automatizado.</p><h4>O que esperamos do programador neste momento?</h4><p>O programador neste momento deverá analisar todos os requisitos em torno deste problema, ele pode lhe ajudar a escolher um sistema no mercado que faça o que você precisa (<em>que não será fácil encontrar</em>) como também poderá desenvolver um sistema que faça este controle, e olha que legal, você pode <strong>expandir seus negócios </strong>com este programador.</p><p>Então digamos que vocês optem pelo desenvolvimento. O nosso programador agora vai cair de cabeça no novo sistema, ele vai trabalhar dia e noite para poder lhe entregar um bom software, afinal, ele se sente bem com isso, ele vai lhe ajudar e ainda vai desenvolver um novo produto para ser vendido no mercado, e você, junto com ele, podem iniciar um novo negócio com este software, levando-o para outras empresas que precisem de um controle aprimorado de frotas.</p><h4>E no final das contas…</h4><p>Você não precisará passar por aquele longo processo na empresa que desenvolve o seu software para que ela possa fazer o que este programador fará para você em poucas semanas, você não precisará desembolsar uma grande quantia em dinheiro para chegar aonde você quer chegar para solucionar um problema deveras, simples, e ainda terá um sistema desenvolvido em cima do seu modelo de negócio, e vai parar de jogar <a href="https://pt.wikipedia.org/wiki/Tetris"><em>tétris</em></a> tentando encaixar aquele sistema gigantesco num simples controle de frota que alguém pode desenvolver para você.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*bbaR2t-SB0nBULYP_SR4Yg.jpeg" /><figcaption>“Todos devem saber como programar um computador, porque ele ensina a pensar.” — Steve Jobs</figcaption></figure><p>E sim, é óbvio que sim, este mesmo problema pode estar ocorrendo agora no seu modelo de negócio, pode estar acontecendo num processo repetitivo e chato que o seu setor financeiro executa todos os dias, ou no processo que ainda está no papel e caneta que a sua guarita desempenha.</p><p>Empresas que desenvolvem grandes sistemas não vão olhar para estes pequenos detalhes na sua empresa, essas fábricas de software tem aos montes, e o pior de tudo é que elas estão pescando bons programadores para dentro delas e limitando o poder que eles tem em automatizar o seu negócio.</p><blockquote>E se você é programador, fique atento com isto, você pode ter sido pescado por uma dessas gigantes e está se limitando a programar poucas coisas quando a sua capacidade pode ir muito além do que solucionar problemas nos códigos dos outros.</blockquote><p>Você, <strong>empresário</strong>, você mesmo pode investir em tecnologia para sua empresa, basta estar disposto a encarar o desafio. Abra uma vaga para um programador, valorize-o, explique para ele que ele tem liberdade para usar a criatividade para expandir os seus negócios, automatizar processos e melhorar a sua empresa, coloque-o para realizar tarefas do financeiro, do setor de logística, da recepção, de qualquer setor, desperte a criatividade desta pessoa que ela despertará a tecnologia em seu negócio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4307644daca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>