Ron and Ella Wiki Page

Extremely Serious

Page 13 of 34

Sealed Classes and Interfaces

Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

public sealed interface IAnimal 
    permits AquaticAnimal, LandAnimal {
    String lifespan();
}

Notice the use of the sealed modifier and permits keyword. The sealed modifier indicates that the class or interface is restricted. The permit keyword indicates which classes (or interfaces) can implement (or extends) it. Thus, the sealed modifier and the permit keyword must be used together.

public sealed abstract class AquaticAnimal implements IAnimal permits SeaTurtle {
}

The class (or interface) that can implement (or extend) a sealed interface (or class) must have one of the following modifiers:

  • sealed
  • non-sealed
  • final
public non-sealed abstract class LandAnimal implements IAnimal {
}

Using the non-sealed modifier indicates that this class can be extended without restriction.

public sealed class Dog extends LandAnimal permits Boxer {
    @Override
    public String lifespan() {
        return "10 - 13 years";
    }
}

Limiting the hierarchy of Dog class to just Boxer class.

public final class Boxer extends Dog {
    @Override
    public String lifespan() {
        return "10 - 12 years";
    }
}

The final implementation of the Dog class.

public class Cat extends LandAnimal {
    @Override
    public String lifespan() {
        return "12 - 18 years";
    }
}

Since LandAnimal is non-sealed abstract class, it can be inherited without restriction.

public final class SeaTurtle extends AquaticAnimal {
    @Override
    public String lifespan() {
        return "Up to 50 years or more";
    }
}

SeaTurtle is the only class that can implement AquaticAnimal. Because this the only class permitted in the AquaticAnimal definition.

Unlinking Uphold Wallet with Brave

Identifying your Custodian member and Wallet Payment IDs [^1]

On the brave browser where you've successfully verified an uphold wallet.

  1. Type in on your brave browser address bar the following:

    brave://rewards-internals
  2. Select the General info tab.

  3. Note the Wallet payment ID from the the Wallet info section.

    Include this information in the description of the request form.

  4. Note the Custodian member ID from the External wallet info section.

  5. Create a request to Wallet Unlinking Request form

[^1]: How can i verify my browser on a new device have reached the lifetime limit

Ubuntu Stops Resolving Address

Issue

Pinging any known working internet address is returning the following message:

Temporary failure in name resolution

Example

Pinging www.google.com as follows:

ping: www.google.com: Temporary failure in name resolution

Resolution

Check where you /etc/resolve.conf is pointing using the following command:

 ls -al /etc | grep resolv.conf

If it is not pointing to /run/systemd/resolve/resolv.conf. Do the following:

sudo rm /etc/resolv.conf
sudo ln -s /run/systemd/resolve/resolv.conf  /etc/resolv.conf
sudo systemctl restart systemd-resolved.service

Regex Capture Groups with Java

The following java code extracts the group, artifact and version using regex capture groups:

import java.util.regex.Pattern;

public class Main {

    public static void main(String ... args) {
        //Text to extract the group, artifact and version
        var text = "org.junit.jupiter:junit-jupiter-api:5.7.0";

        //Regex capture groups for Group:Artifact:Version
        var pattern = "(.*):(.*):(.*)"; 

        var compiledPattern = Pattern.compile(pattern);
        var matcher = compiledPattern.matcher(text);
        if (matcher.find( )) {
            System.out.println("Whole text: " + matcher.group(0) );
            System.out.println("Group: " + matcher.group(1) );
            System.out.println("Artifact: " + matcher.group(2) );
            System.out.println("Version: " + matcher.group(3) );
        } else {
            System.out.println("NO MATCH");
        }
    }
}

Output

Whole text: org.junit.jupiter:junit-jupiter-api:5.7.0
Group: org.junit.jupiter
Artifact: junit-jupiter-api
Version: 5.7.0

Vagrant Basic Commands

Command Description
destroy Stops and deletes all traces of the vagrant machine
halt Stops the vagrant machine
init Initializes a new Vagrant environment by creating a Vagrantfile.
Vagrant boxes can be found from the following link:
Discover Vagrant Boxes - Vagrant Cloud (vagrantup.com)
provision Provisions the vagrant machine
reload Restarts vagrant machine, loads new Vagrantfile configuration
resume Resume a suspended vagrant machine
ssh Connects to machine via SSH
ssh-config Outputs OpenSSH valid configuration to connect to the machine
status Outputs status of the vagrant machine
suspend Suspends the machine
up Starts and provisions the vagrant environment
validate Validates the Vagrantfile
version Prints current and latest Vagrant version

Retrieving the Versions from maven-metadata.xml

Groovy Snippet

List<String> getMavenVersions(String metadataXmlURL) {
    def strVersions = new ArrayList<String>()
    def mvnData = new URL(metadataXmlURL)
    def mvnCN = mvnData.openConnection()
    mvnCN.requestMethod = 'GET'

    if (mvnCN.responseCode==200) {
        def rawResponse = mvnCN.inputStream.text
        def versionMatcher = rawResponse =~ '<version>(.*)</version>'
        while(versionMatcher.find()) {
            for (nVersion in versionMatcher) {
                strVersions.add(nVersion[1]);
            }
        }
    }

    strVersions.sort {v1, v2 ->
        v2.compareTo(v1)
    }

    return strVersions
}

Example Usage

def metatdataAddress = 'https://repo.maven.apache.org/maven2/xyz/ronella/casual/trivial-chunk/maven-metadata.xml'
def versions = getMavenVersions(metatdataAddress)
println versions

Removing the Timestamp from the downloaded SNAPSHOT

Use case

The downloaded snapshot has timestamp associated with it like the following:

artifact-1.0.0-20211012.041152-1.jar

But the tooling is expecting an absolute name like the the following:

artifact-1.0.0-SNAPSHOT.jar

Powershell Script

#The target artifact
$ArtifactId = "artifact"

#The target SNAPSHOT version
$Version = "1.0.0-SNAPSHOT"

if ($Version -match "^(.*)-SNAPSHOT$") 
{
    $Prefix = "{0}-{1}" -f $ArtifactId,$Matches.1
    $Pattern = "^(${Prefix}).*(\.jar)$"

    Get-ChildItem ('.') | ForEach-Object {
        If ($_.Name -match $Pattern) {
            $NewName = "{0}-SNAPSHOT{1}" -f $Matches.1, $Matches.2
            Rename-Item $_ -NewName $NewName
            $Message = "Renaming from {0} to {1}" -f $_.Name, $NewName
            echo $Message
        }
    }
}

Type Pattern Matching for instanceof

The pattern matching enhancement that conditionally extract data from an object if the instanceof operator was satisfied and assigns it to a variable.

The variable in this pattern matching is following a flow scope. This means that the variable is in scope if it is guaranted that it can satisfies the instanceof operator.

Code Without Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//Check if rec is a Person.
if (rec instanceof Person) {

    //rec can safely be casted to Person.
    var person = (Person) rec;

    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting the rec to Person once the check succeded is required.

Code With Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//If rec is a Person extract it to a variable person.
if (rec instanceof Person person) {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting is not required here and Person instance is extracted to person variable. Moreover, the scope of the variable is in the truth block of the if statement.

Flow Scope

Example 1

Record rec = new Person("Juan", "Dela Cruz");

if (!(rec instanceof Person person)) {
    System.out.println("In human.");
}
else {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that person variable usage is on the else block of the if statement.

Example 2

Record rec = new Person("Juan", "Dela Cruz");

if (rec instanceof Person person && "JUAN DELA CRUZ".equals(String.join(person.firstName(), " ", person.lastName().toUpperCase()))) {
    System.out.println("You won a price");
}

Notice that the person variable is usable after the AND (&&) operator. This is because the and operator guarantees that the instanceof operator was satisfied before evaluating the following condition. Changing it to OR (||) operator will be an error, since the person variable is out of scope.

Practical Usage

equals implementation

import java.util.Objects;

record Person(String firstName, String lastName) {

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (null == o) return false;
        if (o instanceof Person person) {
            return Objects.equals(firstName, person.firstName()) && Objects.equals(lastName, person.lastName());
        }
        return false;
    }

}

Record Class

A record class is a restricted form of classes that models data as data. Thus, also can be thought as data only class. Additionally, this type of class is immutable.

It automatically implements the following methods:

  • public boolean equals...
  • public int hashCode...
  • public String toString() {...}

The class generated by the record is a final class.

The constructor will also be handled and the parameters is matching the arrangement of the record parameter(s).

Use Cases

  • Data Transfer Objects (DTO) (i.e. not applicable to JPA entities)
  • Compound map keys
  • Multiple return values

Syntax

record <IDENTIFIER>([[[<FIELD_TYPE_1> <FIELD_NAME_1>][, <FIELD_TYPE_2> <FIELD_NAME_2>]][,... <FIELD_TYPE_2> <FIELD_NAME_N>]]) {}
Token Description
IDENTIFIER A valid Java identifier.
FIELD_TYPE_1
FIELD_TYPE_2
FIELD_TYPE_N
The type of the field(s) in the record parameter(s).
FIELD_NAME_1
FIELD_NAME_2
FIELD_NAME_N
The name of the field(s) in the record parameter(s).

The identifier has an equivalent cannonical constructor with parameters equivalent to its parameters.

Each fields has the following:

  • private final field of the same name.
  • public accessor method of the same name and type.

Example

record Person(String firstName, String lastName) {}

The above example is equivalent to the following class definition:

public final class PersonC {

    private final String firstName;
    private final String lastName;

    public PersonC(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() {
        return this.firstName;
    }

    public String lastName() {
        return this.lastName;
    }

    public boolean equals...
    public int hasCode...
    public String toString() {...}

}

Compact Constructor

In the record definition we can use a compact constructor. This constructor is the shorthand form of the generated default constructor. All of the fields indicated on the record parameters are implicitly available in it.

Syntax of the Compact Constructor

pubic <IDENTIFIER> {
    // Initilization logic.
}

The IDENTIFIER here is matching the record IDENTIFIER, just like when you are writing a constructor of a class but without parameters even the parentheses.

Example Usage

record Person(String firstName, String lastName) {
    public Person {
        java.util.Objects.requireNonNull(firstName);
        java.util.Objects.requireNonNull(lastName);
    }
}

Module Resolution

Resolve modules from the root module using the following syntax:

java --show-module-resolution -p <MODULE_PATHS> -m <ROOT_MODULE>
Identifier Description
MODULE_PATHS List of modules paths delimited by semi-colon (i.e. ;).
ROOT_MODULE The module to start the resolution.
« Older posts Newer posts »