Honrarás a tu padre y a tu madre

 Siempre he estado posteando sobre tecnología, cursos, pero, ya casi pronto a cumplir mis 48 años quiero comentarles algo que he visto en mi vida y que me ha ayudado muchísimo. No se que religión profeses, así que no juzques mi post por tu posición religiosa, sino miralo como una conclusión en base a la experiencia y si te sirve super, sino, simplemente ríete y sigue navegando en la internet.

Nunca he experimentando más satisfacción que apoyar y ver a mis padres. No ha sido fácil, cuando uno se casa o contrae matrimonio, su foco es tu familia y a veces te pierdes en tus temas, y puedes llegar a ver a tus padres muy poco. 

Hermano, cuidate de eso, no digo, ni apoyo que vivas con tus padres mientras ellos se pueden valer por si mismos. Pero, una cena, una salida con ellos de vez en cuando, te ayudará mucho, recordarás los viejos tiempos y reíras con quienes lo unico que quieren para ti es que seas feliz.

Hoy tengo a mi madre viva, mi padre nos dejo en 1995 y les confieso mis hermanos, que nunca he sido mas feliz que conversando con mi madre. No vive conmigo, pero, lo hará cuando necesite quien la asista. Siempre recibo una bendición de su parte y siempre ora por mi y la familia con su rosario. En verdad soy afortunado porque mi madre siempre me ha aconsejado en mis proyectos, en mis ideas, y siempre ha estado conmigo en los exitos y fracasos. 

Así que mis hermanos, ese mandamiento (y aqui si se me sale lo creyente), no es solo para los padres que fueron buenos contigo, que estuvieron siempre contigo, no hay distinción, no los juzgues, y mas bien, a pesar de sus errores, amalos, perdonalos y vive con ellos sus ultimos años, veras que serás feliz como una lombriz y tus proyectos siempre te iran bien. No dejes que se vayan sin haberte reconciliado con ellos, nunca, pero, nunca te arrepentiras. Habrás ganado muchísimo perdonando y siendo un buen hijo.

Tu amigo 

Joe

Share:

Renovate Bot - To keep your dependencies up to date.

 


I am a software engineer in ExoReaction and had the opportunity of configuring and use Renovate for our projects in our repositiores (Quadim, Cantara, entraeiendom)

It hasn't happened to your project that over time its dependencies are outdated.

Well, I'll tell you that there is an excellent tool to have your dependencies updated and it gives you the opportunity to auto-merge or generate PR for a major version and decide whether to accept it or not. It amazing tool is Renovate.

The best part is that renovate supports:

  • node projects
  • javascript projects
  • java projects. (Maven, Gradle)
  • golang projects
  • etc



The most surprising thing is that it is FREE. That is, you can use it on Github, Gitlab, and Gitea without paying anything else.

I will make this article based on Github and using renovate app (NO self-host).


1. First. locate the option to install the tool for Github.



2. Second. You will be redirected to its informative page



3. Third. You need to configure the GitHub account (choose one)



4. Fourth. You will see that it is already integrated into your account, but you need to tell it if you want it to be enabled for all your repositories or just for some. You will come to this page if you later want to add more reps.


In this section, you have to choose if you want it to be enabled for all repositories or just some.



5. Once you have enabled Renovate on a repository, you will get a "Configure Renovate" Pull Request looking something like this


The "Configure Renovate" PR will include a renovate.json file in the root directory, with suggested default settings


6. For renovatebot to do its magic, you have to configure a renovate.json file u other alternativas as the documentation says.



The content of it file is very simple:

{

  "extends": [

    "config:base"

  ]

}


7. After this, your repo will receive several pull requests for dependencies that are already out of date.



The information of its PR has many details for taking a good decision of accepting or not the update.


And if all the status checks are passed, the PR is ready to merge.



Amazing or not?


BE CAREFUL: He can become the best programmer in your team that releases more PRs than anyone hahaha.


8. You can further customize your renovate.json file, but I recommend following this article to get the most out of it.

First: Introduction to Renovate Bot

Second: https://www.augmentedmind.de/2021/07/25/renovate-bot-cheat-sheet/


The source code of it project is on Github. A good place to visit. 

The tab de Discussions is the correct place to find help and support for the same maintainers. 


Enjoy!


In the next article, I will write about "How to centralize your configuration for many repositories" (Be patient and read the documentation first, because they are not so friendly if they realize that you haven't even read the documentation hahaha. I am kidding).


Joe



Share:

Applying Google Code Style to your Java Projects

 


Over the years I have seen how some projects upload their code with indentation or without indentation.

I learned working with teams that apply good practices, that it is good to use a style guide for the source code.

One of them and widely used in other companies, is the google java format which follows google Java style guide. This post will explain how to use it and make sure no one else uploads its code without format.


Pre-requisites

- You need to download the Google Style  and save it in a location on your PC.

- IntelliJ IDEA

- Any project using maven 

IntelliJ IDEA

The first step is add it file in IntelliJ IDEA - Preferences - Editor - Code Style - Import Scheme


You need to import the scheme and ready.

Maven Plugin

In the project where you need to apply it code style you need to add the fmt-maven-plugin (available in GitHub) in your pom.xml. 

 


We are configuring the plugin to apply Google format to src/main/java (our principal source code) and src/test/java (our tests cases).

Note: The plugin changed of groupId and will be soon in maven central. In the meantime, we are going to use the old groupId.


Pre-commit with Git

To make sure our format is always applied, we add a hook on the pre-commit in Git. Then when you execute a git commit -m "commit code changes", this guarantees  that the format is applied before.

vi .git/hooks/pre-commit
#! /bin/bash
mvn com.coveo:fmt-maven-plugin:format
git add -u

Don't forget to give execute permission:  chmod a+x .git/hooks/pre-commit



Test

Apply a commit and check your code before doing a push and you will see the final result.



Looks your entity:



Ready. No more code without format or indentation in your git repo.

Enjoy


Joe




Share:

Automating Resource Management in Java





One day ago, my friend "Nazareno" showed me his code of how to call a database function and it had a structure like this:




Try-with-resources

The problem with it code is that only is managing the automatic close connection with the try-with-resources:

In it new try all the resources are closed in the reverse of the order in which they are created.  Then an improvement to it code should be:

try (var conn = ds.getConnection(); var cs = conn.prepareCall(sql)) {
        
       .... code supressed ....

      try(var rs = cs.executeQuery()){
          .... code supressed ....
     }
}

Stop doing this:


rs.close();

cs.close();

While it is a good habit to close all the three resources, it isn't strictly necessary. Closing a JDBC resource should close any resources that is created. In theory it should happens:

  • Closing a connection also closes PreparedStatement (or CallableStatement) and ResultSet.
  • Closing a PreparedStatement (or CalleStatement) also closes the ResultSet.

 It is important to close resources in the right order. This avoids both resource leaks and exceptions.


Bonus


Use SQL Exception instead Exception and get more information:

         ...


         } catch (SQLException e) {


            System.out.println(e.getMessage());


            System.out.println(e.getSQLState());


            System.out.println(e.getErrorCode());


         } 

I learned of it experience so much too.

Enjoy!


Joe


 

Share:

Virtual Checker built with Angular + Firebase + Flutter + JakartaEE + Microprofile + PostgreSQL on Azure - Parte 4






This post is about the inspector backend,  it will be deployed in our payara server.


The source code is on GitHub: https://github.com/joedayz/ws-inspector


1. This project will be using Jakarta EE, Microprofile, Blaze Persistence, Apache DeltaSpike, Lombok and Firebase-Admin as principal dependencies. See the pom.xml in GitHub.

2. In webapp/WEB-INF we have the beans.xml, glassfish-resource.xml and glassfish-web.xml:


beans.xml


glassfish-web.xml (context root)


glassfish-resources.xml




3. We will use the publicKey.pem generated in our first post to validate if the user has been authenticated or has the authorization to execute some method. 



4. firebase-sdk.json is the file downloaded from firebase.com mandatory to interact with our firebase account.


5. persistence.xml shows the JDBC resource configured in our payara server.





6. apache-deltaspike.properties is configured according to transaction type: JTA.

globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy = org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy


7.  The model will be according to the database model explained in my last post.

For example it is the configuration for the table "asegurado" in the "core" scheme.

@Getter
@Setter
@Entity
@Table(name = "asegurado", schema = "core")
public class AseguradoModel {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_asegurado")
private Long idAsegurado;

@Column(name = "nombre")
private String nombre;

@Column(name = "apellido_paterno")
private String apellidoPaterno;

@Column(name = "apellido_materno")
private String apellidoMaterno;

@Column(name = "id_ct_tipo_documento")
private String idCtTipoDocumento;

@Column(name = "numero_documento")
private String numeroDocumento;

@Column(name = "direccion")
private String direccion;

@Column(name = "id_distrito")
private Integer idDistrito;

@Column(name = "telefono_movil")
private String telefonoMovil;

@Column(name = "telefono_fijo")
private String telefonoFijo;

@Column(name = "correo")
private String correo;

@Column(name = "usuario_creacion", updatable = false)
private String usuarioCreacion;

@Column(name = "usuario_modificacion")
private String usuarioModificacion;

@Column(name = "fecha_creacion", updatable = false)
private LocalDateTime fechaCreacion;

@Column(name = "fecha_modificacion")
private LocalDateTime fechaModificacion;
}

It is the table "inspeccion" in the "inspeccion" scheme:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "inspeccion", schema = "inspeccion")
public class InspeccionModel {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_inspeccion")
private Long idInspeccion;

@Column(name = "id_vehiculo_asegurado")
private Integer idVehiculoAsegurado;

@Column(name = "codigo_inspeccion")
private String codigoInspeccion;

@Column(name = "codigo_inspeccion_legall")
private String codigoInspeccionLegall;

@Column(name = "id_ct_estado_inspeccion")
private String estado;

@Column(name = "id_tramite")
private Integer idTramite;

@Column(name = "id_distrito")
private String idDistrito;

@Column(name = "id_empleado_inspector")
private Integer idEmpleadoInspector;

@Column(name = "observaciones")
private String observaciones;

@Column(name = "latitude")
private Double latitude;

@Column(name = "longitude")
private Double longitude;

@Column(name = "fecha_termino")
private LocalDateTime fechaTermino;

@Column(name = "direccion_inspeccion")
private String direccionInspeccion;

@Column(name = "usuario_creacion", updatable = false)
private String usuarioCreacion;

@Column(name = "fecha_creacion", updatable = false)
private LocalDateTime fechaCreacion;

@Column(name = "usuario_modificacion")
private String usuarioModificacion;

@Column(name = "fecha_modificacion")
private LocalDateTime fechaModificacion;
}

If you need use some view (vw_inspecciones) the declaration is similar:


@Getter
@Setter
@Entity
@Table(name = "vw_inspecciones", schema = "public")
public class InspeccionView {

@Id
@Column(name = "id_informe")
private Long id;

@Column(name = "id_inspeccion")
private Long idInspeccion;

@Column(name = "codigo_inspeccion")
private String codigoInspeccion;

@Column(name = "codigo_inspeccion_legall")
private String codigoInspeccionLegall;

@Column(name = "observaciones")
private String observaciones;

@Column(name = "informe_fecha_programada")
private LocalDateTime fechaProgramada;

@Column(name = "id_distrito")
private String idDistrito;

@Column(name = "id_empleado_inspector")
private String idEmpleadoInspector;

@Column(name = "usuario_creacion")
private String usuarioCreacion;

@Column(name = "id_tramite")
private Integer idTramite;

@Column(name = "nro_tramite_compania_seguro")
private String numeroTramite;

@Column(name = "contacto")
private String contacto;

@Column(name = "placa")
private String placa;

@Column(name = "id_ct_motivo")
private String idCtMotivo;

@Column(name = "id_estado")
private String idEstado;

@Column(name = "estado")
private String estado;

@Column(name = "contratante_nombre")
private String contratanteNombre;

@Column(name = "contratante_razon_social")
private String contratanteRazonSocial;

@Column(name = "asegurado_nombre")
private String nombreApellido;

@Column(name = "telefono_fijo")
private String telefonoFijo;

@Column(name = "telefono_movil")
private String telefono;

@Column(name = "correo")
private String correo;

@Column(name = "direccion")
private String direccion;

@Column(name = "id_marca")
private String idMarca;

@Column(name = "marca")
private String marca;

@Column(name = "id_modelo")
private String idModelo;

@Column(name = "modelo")
private String modelo;

@Column(name = "id_vehiculo_asegurado")
private String idVehiculoAsegurado;

@Column(name = "id_asegurado")
private String idAsegurado;

public String getEstado() {
switch (estado) {
case "Pendiente":
return Constantes.ON_HOLD;
case "Digitado":
return Constantes.AVAILABLE;
case "Terminado":
return Constantes.COMPLETE;
default:
return estado;
}
}


}

This view exists in the database in the public scheme:


That's a short overview of our model. You can see the other classes in this package:




8. The repository layer is very easy if you use the deltaspike  data module:

- For example, you can declare an interface as repository and extends of some interface as EntityRepository that will generate the CRUD methods.  



These are the methods that will be generated thanks to EntityRepository:


- You can generate your own finders:





- Fortunately for us there is an integration between blaze and deltaspike to use views as entities, I used this integration to work with the view "vw_inspecciones" declared in our entity InspeccionView.


9. Before looking at our service layer. We see the producers created for the project in the config package:


Log Producer


It then can be injected in some class to produce log in this way:



FirebaseConfig to work with our firebase account:



Note: It use the file firebase-sdk.json that must be in src/main/resources.

EntityManagerProducer where we use the reference of our persistence unit ("legall_pu"):



CriteriaBuilderFactoryProducer uses blaze-persistence to have a rich criteria API for JPA providers:


EntityViewManagerProducer use the BlazePersistence - Entity View ModuleBlaze Persistence entity views try to solve these and many more problems a developer faces when having to implement efficient model mapping in a JPA application. It allows to define DTOs as interfaces and provides the mappings to the JPA model via annotations. It favors convention-over-configuration by providing smart defaults that allow to omit most mappings. By applying DTOs to a query builder through the ObjectBuilder extension point it is possible to separate query logic from the projections while still enjoying high performance queries.


Finally CorsFilter to evict problems of CORS with our frontend:



10. Now is the moment of see our JAXRSConfiguration where will be using MicroProfile JWT



This is very simple and minimalist. I love that.


- Our controllers depend on the roles allowed. 


- We have some DTOs for request and response:






11. In our service layer we use the repositories and create the business logic:




In some cases is necessary the sincronization with firebase, for example for a re-schedule of inspection:

 




It backend will be used by our frontend and mobile application in the next articles. 


Enjoy!

Joe





Share: