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 |
Author: ron (Page 14 of 34)
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
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
}
}
}
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;
}
}
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);
}
}
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. |
[open] module <MODULE_NAME> {
[[requires [transitive] <MODULE_NAME>;]
[exports <PACKAGE>[ to <MODULE_NAME_1>[,<MODULE_NAME_2>..,<MODULE_NAME_N>];]
[opens <PACKAGE>;]
[provides <SERVICE> with <SERVICE_IMPLEMENTATION_1>[,<SERVICE_IMPLEMENTATION_2>..,<SERVICE_IMPLEMENTATION_N>];]
[uses <SERVICE>;]]
}
Identifier | Description |
---|---|
module | The module keyword that holds the module directives. |
<MODULE_NAME> | The module identier. |
<PACKAGE> | The package identifier. |
requires | The requires directive indicates that this module depends on another module. ^1 |
transitive | The transitive directive indicates that the user of the current module will also requite another module that the current user will also have access into. |
exports | The exports directive indicates which public types of the module's package are accessible to other modules. ^1 |
opens | The opens directive also indicates which public types of the module's package are accessible to other modules. The difference between that and exports is that opens is not for compile time, only during runtime, while exports is for both compile time and runtime. The opens directive can typically be used when you want to allow other modules to use reflection for the types in the specified packages, but not to use them during compile time. Let's make this more clear by means of an example. ^1 |
open | This is like the opens directive but with this it opens the whole module. |
to <MODULE_NAME_1>[, <MODULE_NAME_2>.., <MODULE_NAME_N>] | This indicates to target just specific module(s). |
provides...with | The provides...with directive indicates that the module provides a service implementation.^1 |
uses | The uses directive indicates that the module requires a service implementation. |
<SERVICE> | The interface or abstract class that will be implemented as a service. |
<SERVICE_IMPLEMENTATION_1>[, <SERVICE_IMPLEMENTATION_2>.., <SERVICE_IMPLEMENTATION_N>] | The implementation classes of the SERVICE_INTERFACE. |
The text blocks is Java's way to simplify rendering of a string that spans multiple lines. A text block begins with three double-quote characters followed by a line terminator.^1
Example:
String text = """
The quick
brown fox
jumps over
the lazy dog""";
The above example is equivalent to:
String text = "The quick \n"
+ "brown fox \n"
+ "jumps over \n"
+ "the lazy dog";
Notice who how simple the example against its equivalent.
Incidental and essential white space
The java text blocks differentiates the incidental white space from essential white space^1. Like the following example:
void writeHTML() {
String html = """
········<html>
········ <body>
········ <p>Hello World.</p>
········ </body>
········</html>
········""";
writeOutput(html);
}
The dots, preceding the tag represents the incidental white spaces while the space preceding the
tag not including the dots, represents the essential white spaces.Normally the left incidental white space can be controlled by the location of the ending delimiter of the text blocks.
Trailing white space on each line in a text block is also considered incidental and is stripped away by the Java compiler^1.
Removing the ending new line of each line
Using the backslash at the end of each line will remove the implicit \n character.
String text = """
The quick \
brown fox \
jumps over \
the lazy dog""";
If you output the preceding variable it will become a single line like the following:
The quick brown fox jumps over the lazy dog
Pre-requisite
Installing a Java Service
-
Register a java application as a windows service using the following syntax:
nssm install <SERVICE_NAME> <JAVA_EXECUTABLE> <JAVA_ARGUMENTS>
Example
nssm install "JavaService" "${JAVA_HOME}\bin\java.exe" "-jar java-service.jar --spring.profiles.active=dev"
-
Update the service with application directory using the following syntax:
nssm set <SERVICE_NAME> AppDirectory <JAR_FILE_DIRECTORY>
Example
nssm set "JavaService" AppDirectory "C:\apps"
-
Update the service with description using the following syntax:
nssm set <SERVICE_NAME> Description <APP_DESCRIPTION>
Example
nssm set "JavaService" Description "A custom java service."
Displaying the NSSM details of the Java Service
Use the following syntax to display the details of the services:
nssm dump <SERVICE_NAME>
Example
nssm dump "JavaService"
Uninstalling a Java Service
Use the following syntax to remove a java service using nssm:
nssm remove <SERVICE_NAME> confirm
confirm parameter here specifies that we don't want to see the gui confirmation.
Example
nssm remove "JavaService" confirm
Signing the CSR
-
Download OpenSSL binaries from the following link if you are using windows:
-
Create a v3.cnf file using the following template:
authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alternate_names nsComment = "Self-signed Certificate" [ alternate_names ] DNS.1 = <DNS_1> #DNS.2 = <DNS_2> #DNS.3 = <DNS_3> #DNS.4 = <DNS_4> # Add these if you need them. But usually you don't want them or # need them in production. You may need them for development. # DNS.5 = localhost # DNS.6 = localhost.localdomain # DNS.7 = 127.0.0.1 # IPv6 localhost # DNS.8 = ::1
Replace the following fields on the template:
Field Name Description DNS_<INDEX> Identify the DNS names from the CSR. Example:
authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alternate_names nsComment = "Self-signed Certificate" [ alternate_names ] DNS.1 = www.ronella.xyz #DNS.2 = <DNS_2> #DNS.3 = <DNS_3> #DNS.4 = <DNS_4> # Add these if you need them. But usually you don't want them or # need them in production. You may need them for development. # DNS.5 = localhost # DNS.6 = localhost.localdomain # DNS.7 = 127.0.0.1 # IPv6 localhost # DNS.8 = ::1
-
Generate a CA private key and certificate pair. The following link can help:
PRIVATE CERTIFICATION AUTHORITY (CA) -
Once you have the pair (i.e. key is ca.key.pem and the certificate is ca.cert.crt), sign the CSR using the following command:
openssl x509 -req -days 365 -sha256 -in domain.csr -extfile v3.cnf -CA ca.cert.crt -CAkey ca.key.pem -CAcreateserial -out domain.crt
Viewing the generated certificate from CSR
-
View the signed certificate using the following the command:
openssl x509 -in domain.crt -text
Recent Comments