Bitsmi Blog

OCP11 - Creating nested classes (I)

30-10-2021 - Xavier Salvador

A nested class is a class that is defined within another class. We have four different nested classes types:

  1. Inner class: A non-static type defined at the member level of a class.
  2. Static nested class: A static type defined at the member level of a class.
  3. Local class: A class defined within a method body.
  4. Anonymous class: A special case of a local class that does not have a name.

By convention we use the term inner or nested class to apply to other Java types, including enums and interfaces.

Interfaces and enums can be declared as both inner classes and static nested classes but not as local or anonymous classes.

We will explain each one of these nested classes in a different post and we will use this post to show which are the syntax rules permitted in Java for nested classes in three tables.

more…

OCP11 - Creating nested classes (III) - Creating an static nested class

30-10-2021 - Xavier Salvador

A static nested class is a static type defined at the member level. Unlike an inner class, a static nested class can be instantiated without an instance of the ecnlosing class.

The trade-off though, is it can’t access instance variables or methods in the outer class directly. It can be done but it requires an explicit reference to an outer class variable. It is like a top-level class except for:

  • The nesting creates a namespace because the cnlosing class name must be used to refer it.
  • It can be made private or use one of the other access modifiers to encapsulate it.
  • The enclosing class can refer to the fields and methods of the static nested class.

Example:

1: public class Enclosing {
2:    static class Nested {
3:       private int price = 6;
4:    }
5:    public static void main(String[] args) {
6:       Nested nested = new Nested();
7:       System.out.println(nested.price);
8: } }

Line 6 instantiates the nested class. Since the class is static, you don’t need an instance of Enclosing to use it. Line 7 allows you to access private instance variables.

Importing a static Nested Class

Importing a static nested class is done using the regular import.

  // Toucan.java
    package bird;
    public class Toucan {
       public static class Beak {}
    }
    // BirdWatcher.java
    package watcher;
    import bird.Toucan.Beak; // regular import ok
    public class BirdWatcher {
       Beak beak;
    }

Since it is static you can also use a static import:

import  static  bird.Toucan.Beak;

IMPORTANT TO CONSIDER HERE FOR THE EXAM: Java treats the cnsloing class as if were a namespace.

more…

Montar unidades de disco externas de forma permanente en Linux

10-10-2021 - Antonio Archilla

En el siguiente artículo se explica la configuración necesaria en Linux para montar unidades de disco externas automáticamente al iniciar el sistema. Aunque la explicación y ejemplos se han hecho específicamente para sistemas Ubuntu, los mismos pasos también son aplicables a otros sistemas Linux.

El proceso se puede dividir en los siguientes pasos:

  • Identificar el dispositivo de disco externo en el sistema
  • (Opcional) Configurar un grupo que permita restringir el acceso al contenido de las unidades externas
  • Modificar la configuración en fstab para añadir las unidades de disco externas a los dispositivos a montar durante el arranque del sistema

Adicionalmente, se explica cómo habilitar disco montado como volumen en contenedores Docker cuando se utilizan usuarios con acceso restringido a las ubicaciones de disco.

more…

OCP 11 - Language Enhancements (Java Fundamentals - Enumerations)

27-09-2021 - Xavier Salvador

Generally speaking an Enumeration is like a fixed set of constants. But in Java an enum (short for enumerated type) can be a top-level type like a class or a interface, as well as a nested type like an inner class.

Using an enum is much better than using a lot of constants because it provides type safe checkline. With numeric or Strings contants you can pass an invalid value and not find out until runtime. On the other hand, with enums it is impossible to create an invalid value without introducing a compiler error.

more…

OCP11 - Services in a Modular Application

28-08-2021 - Antonio Archilla

Since Java 6 the Java platform provides a mechanism to implement dynamic service loading. Starting from Java 9, it is possible to implement this mechanism together with JPMS.

In this post we will expose the way to implement a modular service.

more…

OCP11 - Migration to a Modular Application

26-08-2021 - Antonio Archilla


Following the introductory post of Java Platform Module System , also known as JPMS, this post exposes different strategies to migrate applications developed in Java as they can make use of it. This covers the cases where original application is based on a non compatible Java version (< Java 9) or it is compatible (>=Java9) but it was not originally implemented, since the use of this mechanism is fully optional.

Migration strategies

The first step to perform in the migration of an application to the module system is to determine which modules / JAR files are present in an application and what dependencies exists between them. A very useful way to do so is through a hierarchical diagram where these dependencies are represented in a layered way.

This will help giving an overview of the application’s components and which one of them and in which order they can be migrated, identifying those which won’t be able to adapt temporarily or definitively.

The latter case can be given for example in third parties libraries that have stopped offering support and that will hardly become modules. This overview will help determine the migration strategy that will be carried out.

Next, 2 migration mechanisms are exposed that respond to different initial situations.

more…

Usando Let's Encrypt y Certbot para generar certificados TLS para nginx

15-06-2021 - Antonio Archilla

Let’s Encrypt es una autoridad de certificación que proporciona certificados TLS de forma gratuita a todo host que lo necesite para securizar las comunicaciones con éste. Si además se utiliza un sistema NOIP como DuckDNS como servidor DNS, se consigue sin costes adicionales tener un servidor publicado en la red aunque no se disponga de IP fija.

Las únicas contrapartidas que tiene son que el host ha de ser accesible desde internet, lo que deja fuera a hosts dentro de intranets, y que la duración del certificado generado es de 3 meses, lo que implica una renovación constante.

Afortunadamente, el proceso de generación y renovación de los certificados se puede automatizar completamente mediante la herramienta Certbot que tiene soporte para multitud de sistemas operativos y plataformas cloud.

En este post se describe el proceso de generación de certificados para un servidor HTTP nginx ubicado en un sistema Ubuntu 20.04 con IP dinámica gestionada por el servicio DuckDNS.

more…

OCP 11 - Language Enhancements (Java Fundamentals - Final modifier)

02-06-2021 - Xavier Salvador

Introduction

Final modifier can be applied to variables, methods and classes. Marking a:

  1. Variable final means the value cannot be changed after it is assigned.
  2. Method or a class means it cannot be overridden (for methods) or extended (for classes).

Declaring final local variables

For final variables there are several aspects to consider.

We do not need to assign a value to the final variable when we declare it. What we have to assure is the a value has been assigned to it before this final variable is used. We will get a compilation error in case we don’t follow this rule. Example which illustrates this:

private void printZooInfo(boolean isWeekend) {
    final int giraffe = 5;
    final long lemur;
    if (isWeekend) lemur = 5;
    giraffe = 3; // DOES NOT COMPILE   
    System.out.println(giraffe+" "+lemur); // DOES NOT COMPILE
}

Here we have two compilation errors:

  1. The giraffe variable has an assigned value so we can’t assign a new value because it has been declared as final. We will get a compilation error.
  2. When attempting to use lemur variable we will get a compilation error. If condition isWeekend is false we can’t assign the value to lemur so we will the error the error compilation because a local variable to has to be declared and assigned before using it (despite the fact of being declared as final or not).

When we mark a variable as final it does not mean that the object associated with it cannot be modified. Example to illustrate this:

final StringBuilder cobra = new StringBuilder();
cobra.append("Hssssss");
cobra.append("Hssssss!!!");

We have declared the variable as constant but the content of the class can be modified.

Adding final to Instance and static variables

Instance and static class variables can be marked as final too.

When we mark as final a:

  1. Instance variable which it means that it must be assigned a value when it is declared or when the object is instantiated (Remember: We can only assign once, like Local Variables). Example to illustrate this:
    public class PolarBear {
    final int age = 10;
    final int fishEaten;
    final String name;
    
    { fishEaten = 10; }
    
    public PolarBear() {
       name = "Robert";
    }
    public PolarBear(int height) {
       this();
    }
    }
    

    Does this code compile? Yes. Everything. Exercise: Explain why.

  2. Static variable which it means they have to use static initializers instead of instance initializers. Example to illustrate this:
    public class Panda {
      // We assign a value when we declare the final variable
      final static String name = "Ronda";
      static final int bamboo;
      static final double height; // DOES NOT COMPILE - Why? Because we do not have assign any value to height variable  
      // It will work because we are initializing a final static variable through an static initializer
      static { bamboo = 5;}}
    

Writing final methods

Methods marked as final cannot be overriden by a subclass. This avoids polymorphic behavior and always ensures that it is always called the same version method. Be aware because a method can have abstract or final modifier but not both at the same time.

When we combine inheritance with final methods we always get an error compilation.

We cannot declare a method final and abstract at the same time. It is not allowed by the compiler and of course we will get a compilation error. Example to illustrate this:

abstract class ZooKeeper {   
	public abstract final void openZoo(); // DOES NOT COMPILE
}

Marking Classes final

A final class is one class that cannot be extended. In fact we will get a compilation error if we tried. Example to illustrate this:

public final class Reptile {}
public class Snake extends Reptile {} // DOES NOT COMPILE

We cannot use abstract and final modifiers at the same time.

public abstract final class Eagle {} // DOES NOT COMPILE

It also happens the same for interfaces.

public final interface Hawk {} // DOES NOT COMPILE

We will get a compilation error in both cases.

more…

Construcción de imágenes de Docker multiplataforma con Buildx

09-05-2021 - Antonio Archilla

Docker proporciona soporte para crear y ejecutar contenedores en una multitud de arquitecturas diferentes, incluyendo x86, ARM, PPC o Mips entre otras. Dado que no siempre es posible crear las imágenes correspondientes de arquitectura equivalente por cuestiones de disponibilidad, comodidad o rendimiento, la alternativa de poder crearlas desde un mismo entorno crea interesantes escenarios, como la posibilidad de tener un servicio de integración continua encargado de la creación de todas las variaciones para las diferentes arquitecturas cubiertas por una aplicación.

En este artículo se expone la configuración de la herramienta buildx de Docker para la creación imágenes de múltiples arquitecturas en un mismo entorno. En el ejemplo incluido se crearán 2 imágenes para las arquitecturas AMD64 y ARM64 en un entorno basado en Ubuntu Linux AMD64.

more…

Restaurar pendrive bootable

11-04-2021 - Antonio Archilla

Habitualmente se utilizan pendrives como soporte para la instalación de sistemas operativos mediante la creación de un pendrive bootable. El problema es que después de hacer esto este queda en un estado que no permite su uso para el almacenamiento de datos porque el proceso de conversión a bootable ha creado múltiples particiones y sistemas como Windows no son capaces de reconocerlo correctamente.

En este post se describe el proceso de restauración de un pendrive bootable a su estado original en Windows.

more…

results matching ""

    No results matching ""