Windows Shutdown and Restart Event IDs

The event IDs that can be searched on in windows event viewer for the confirmation of shutdown or restart.

Event ID Name Description
14 The system has rebooted without cleanly shutting down first This event indicates that some unexpected activity prevented Windows from shutting down correctly. Such a shutdown might be caused by an interruption in the power supply or by a Stop error. If feasible, Windows records any error codes as it shuts down.
1074 System has been shutdown by a process/user. This event is written when an application causes the system to restart, or when the user initiates a restart or shutdown by clicking Start or pressing CTRL+ALT+DELETE, and then clicking Shut Down.
6006 The event log service was stopped. The event is logged at boot time noting that the Event Log service was stopped.
6008 Unexpected system shutdown The previous system shutdown at Time on
Date was unexpected.

Authorization Code Grant Type

The authorization code grant type is designed for confidential clients (e.g. websites with a server back end) that can keep a secret. This type can request for offline_access scope (i.e. to request for refresh token).

  1. Use the authorization end point to request the authorization code with the following query parameters:

    response_type = code 
    client_id = the client unique code
    redirect_uri = redirection URL.
    state = (Optional) value to echo to us.
    scope = (Optional) what permision wanted. If not specified, default permission will be given.
    response_mode = (Optional) query

    A login form will be displayed if not yet filled-up before.

    Expected Response

    The redirect_uri with the following query parameters:

    code = The authorization code
    state = state value if given.
  2. Use the token end point to do post request for the access token with the following headers:

    Content-Type = application/x-www-form-urlencoded
    Authorization = Basic <CREDENTIAL>

    And with the following parameters:

    grant_type = authorization_code.
    code = The authorization code from step 1.
    redirect_uri = The used from step 1.

    Expected Response

    Header

    Content-Type: application/json
    
    {
    "access_token" : <ACCESS_TOKEN>,
    "token_type" : "Bearer",
    "expires_in" : 3600,
    "scope" : <The scope allowed by the server>
    }
  3. Call the API with the authorization header like the following syntax:

    Bearer <ACCESS_TOKEN>

Gradle Binary to Package with the Wrapper

  1. Download the gradle binary from the following address:

    https://services.gradle.org/distributions/

    For example gradle-7.4-all.zip.

  2. Place the downloaded gradle binary to the gradle/wrapper directory of the gradle project.

  3. Update the wrapper configuration (i.e. gradle/wrapper/gradle-wrapper.properties) like the following:

    If you've downloaded gradle-7.4-all.zip binary from step 1.

    distributionBase=PROJECT
    distributionPath=wrapper/dists
    distributionUrl=gradle-7.4-all.zip
    zipStoreBase=PROJECT
    zipStorePath=wrapper/dists

Java UTF-16LE Base64 CODEC

The UTF-16LE base64 encoding is compatible to be used with powershell's encoded command.

Encoding

//The text to encode.
var command = "Write-Output \"Hello World\"";
var encodedString = Base64.getEncoder().encodeToString(command.getBytes(StandardCharsets.UTF_16LE));
System.out.printf("Base64: %s%n", encodedString);

Output

Base64: VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==

The preceding output can be used with powershell like the following:

powershell -encodedcommand VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==

Decoding

//The base64 text to decode.
var base64="VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==";
byte[] decodedBytes = Base64.getDecoder().decode(base64);
String decodedString = new String(decodedBytes, StandardCharsets.UTF_16LE);
System.out.printf("Decoded: %s%n", decodedString);

Output

Decoded: Write-Output "Hello World"

Mocking Static Method with Mockito

Sample codes for mocking a static with Mockito.

The StringUtil class is a very trivial class that converts the text to all capitalized.

StringUtil class

public final class StringUtil {

    private StringUtil() {}

    public static String upperCase(String text) {
        return text.toUpperCase();
    }
}

Mocking the StringUtil.upperCase method

Stubbing the StringUtil.upperCase method to return test if test is passed as argument.

Dependencies Required

org.junit.jupiter:junit-jupiter-engine:5.8.2
org.mockito:mockito-inline:4.4.0

StringUtilTest class

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

public class StringUtilTest {

    @Test
    void staticMethod() {
        try (var utilities = mockStatic(StringUtil.class)) {
            utilities.when(() -> StringUtil.upperCase("test")).thenReturn("test");
            assertEquals("test", StringUtil.upperCase("test"));
        }
    }
}

Generating Random Number

Listing the Available Random Algorithms

System.out.printf("%-13s| %s\n-------------|---------------------\n", "Group", "Name");
java.util.random.RandomGeneratorFactory.all()
        .sorted(java.util.Comparator.comparing(java.util.random.RandomGeneratorFactory::name))
        .forEach(factory -> System.out.printf("%-13s| %s\n", factory.group(), factory.name()));

The output is similar to the following:

Group        | Name
-------------|---------------------
LXM          | L128X1024MixRandom
LXM          | L128X128MixRandom
LXM          | L128X256MixRandom
LXM          | L32X64MixRandom
LXM          | L64X1024MixRandom
LXM          | L64X128MixRandom
LXM          | L64X128StarStarRandom
LXM          | L64X256MixRandom
Legacy       | Random
Legacy       | SecureRandom
Legacy       | SplittableRandom
Xoroshiro    | Xoroshiro128PlusPlus
Xoshiro      | Xoshiro256PlusPlus

Check from the following address on how to choose which algorithm to choose:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html#algorithms

Creating an instance of RandomGenerator

The default algorithm (i.e. L32X64MixRandom)

var generator = java.util.random.RandomGenerator.getDefault();

The specific algorithm (e.g. L64X128MixRandom)

var generator = java.util.random.RandomGenerator.of("L64X128MixRandom");

Use the static method RandomGenerator.of and pass the name of the algorithm.

Generating Random Number

Use one of the following instance methods of the RandomGenerator class:

  • nextDouble()
  • nextDouble(double bound)
  • nextDouble(double origin, double bound)
  • nextFloat()
  • nextFloat(float bound)
  • nextFloat(float origin, float bound)
  • nextInt()
  • nextInt(int bound)
  • nextInt(int origin, int bound)
  • nextLong()
  • nextLong(long bound)
  • nextLong(long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

 var generator = java.util.random.RandomGenerator.of("Random");
 System.out.println(generator.nextInt());

The output is a random integer number.

Generating Random Number Using Streams

Use one of the following instance methods of RandomGenerators class to create streams:

  • doubles()
  • doubles(double origin, double bound)
  • doubles(long streamSize)
  • doubles(long streamSize, double origin, double bound)
  • ints()
  • ints(int origin, int bound)
  • ints(long streamSize)
  • ints(long streamSize, int origin, int bound)
  • longs()
  • longs(long origin, long bound)
  • longs(long streamSize)
  • longs(long streamSize, long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

var generator = java.util.random.RandomGenerator.of("Random");
var randomInt = generator.ints(100, 1, 100)
        .filter(number -> number % 2 == 0 )
        .findFirst();
randomInt.ifPresent(System.out::println);

The output is a random integer number.

Downloading Dependencies with Gradle Script

  1. Create settings.gradle file with the following content:

    rootProject.name = 'download-dependecies'
  2. Create build.gradle file with the following content:

    plugins {
        id 'application'
    }
    
    group 'xyz.ronella.gradle'
    version '1.0.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        //Add all the target dependencies here
        implementation 'org.apache.poi:poi:3.5-FINAL'
    }
    
    task download(group: 'resolver') {
        doFirst {
            ant.delete(dir: 'libs')
            ant.mkdir(dir: 'libs')
        }
        doLast {
            copy {
                from sourceSets.main.runtimeClasspath
                into 'libs/'
            }
            def outputFile = "${project.buildDir}\\${project.name}-${version}.zip"
            ant.zip(basedir: "${file('libs')}", destfile: "${outputFile}", excludes: '*.class')
            println "Output: ${outputFile}"
            ant.delete(dir: 'libs')
        }
    }
  3. Run the following gradle command:

    gradle download

    If you are using the gradle wrapper, use the following command:

    gradlew download

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.

Extremely Serious