Ron and Ella Wiki Page

Extremely Serious

Page 14 of 33

Private Certification Authority (CA)

Create the private key and certificate pair.

  1. Download OpenSSL binaries from the following link if you are using windows:

    https://slproweb.com/products/Win32OpenSSL.html

  2. Create a ca.cnf file using the following template:

    [ req ]
    default_bits        = 2048
    default_keyfile     = private.pem
    distinguished_name  = subject
    req_extensions      = req_ext
    x509_extensions     = x509_ext
    string_mask         = utf8only
    
    # The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
    #   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
    [ subject ]
    countryName         = Country Name (2 letter code)
    countryName_default     = <2_LETTER_COUNTRY_CODE>
    
    stateOrProvinceName     = State or Province Name (full name)
    stateOrProvinceName_default = <STATE_NAME>
    
    localityName            = Locality Name (eg, city)
    localityName_default        = <CITY_NAME>
    
    organizationName         = Organization Name (eg, company)
    organizationName_default    = <ORGANIZATION_NAME>
    
    organizationalUnitName         = Organizational Unit (eg, section)
    organizationalUnitName_default = <ORGANIZATIONAL_UNIT>
    
    # Use a friendly name here because it's presented to the user. The server's DNS
    #   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
    #   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
    #   must include the DNS name in the SAN too (otherwise, Chrome and others that
    #   strictly follow the CA/Browser Baseline Requirements will fail).
    commonName          = Common Name (e.g. server FQDN or YOUR name)
    commonName_default      = <YOUR_NAME>
    
    emailAddress            = Email Address
    emailAddress_default        = <YOUR_EMAIL_ADDR>
    
    # Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
    [ x509_ext ]
    
    subjectKeyIdentifier        = hash
    authorityKeyIdentifier    = keyid,issuer
    
    basicConstraints        = CA:TRUE
    keyUsage            = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyCertSign, cRLSign
    nsComment           = "Private CA"
    
    # Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
    [ req_ext ]
    
    subjectKeyIdentifier        = hash
    
    basicConstraints        = CA:true
    keyUsage            = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyCertSign, cRLSign
    nsComment           = "Private CA"

    Replace the following fields on the template:

    Field Name Description
    2_LETTER_COUNTRY_CODE The two letter code of your country.
    STATE_NAME The name of your state.
    CITY_NAME The name of your city.
    ORGANIZATION_NAME The name of your organization.
    ORGANIZATIONAL_UNIT The name of your section in the organization.
    YOUR_NAME Your full name or anything that represents you as a CA.
    YOUR_EMAIL_ADDR Your email address.

    Example:

    [ req ]
    default_bits        = 2048
    default_keyfile     = private.pem
    distinguished_name  = subject
    req_extensions      = req_ext
    x509_extensions     = x509_ext
    string_mask         = utf8only
    
    # The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
    #   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
    [ subject ]
    countryName         = Country Name (2 letter code)
    countryName_default     = NZ
    
    stateOrProvinceName     = State or Province Name (full name)
    stateOrProvinceName_default = Wellington
    
    localityName            = Locality Name (eg, city)
    localityName_default        = Wellington
    
    organizationName         = Organization Name (eg, company)
    organizationName_default    = My Company
    
    organizationalUnitName         = Organizational Unit (eg, section)
    organizationalUnitName_default = IT Department
    
    # Use a friendly name here because it's presented to the user. The server's DNS
    #   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
    #   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
    #   must include the DNS name in the SAN too (otherwise, Chrome and others that
    #   strictly follow the CA/Browser Baseline Requirements will fail).
    commonName          = Common Name (e.g. server FQDN or YOUR name)
    commonName_default      = Ronaldo Webb CA APR 2021
    
    emailAddress            = Email Address
    emailAddress_default        = ron@ronella.xyz
    
    # Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
    [ x509_ext ]
    
    subjectKeyIdentifier        = hash
    authorityKeyIdentifier    = keyid,issuer
    
    basicConstraints        = CA:TRUE
    keyUsage            = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyCertSign, cRLSign
    nsComment           = "Private CA"
    
    # Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
    [ req_ext ]
    
    subjectKeyIdentifier        = hash
    
    basicConstraints        = CA:true
    keyUsage            = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyCertSign, cRLSign
    nsComment           = "Private CA"
  3. Generate a private key using the following command:

    openssl genrsa -out ca.key.pem 2048
  4. Generate a certificate with a validity of 10 years from the private key using the following command:

    openssl req -x509 -sha256 -new -nodes -key ca.key.pem -days 3650 -out ca.cert.crt -config ca.cnf

Viewing the generated certificate

  1. View the generated certificate using the following command:

    openssl x509 -in ca.cert.crt -text

Generating a Self-signed CA Certificate for JSON Web Token (JWT) in Java

In the world of secure communication and authentication, JSON Web Tokens (JWTs) play a crucial role. They are often used to verify the authenticity of clients and servers, ensuring secure data transmission. In this guide, we will walk you through the steps to generate a self-signed CA certificate for JWTs in Java.

Prerequisites

Before we get started, make sure you have the necessary tools and binaries installed. If you're using Windows, you can download the OpenSSL binaries from slproweb.com.

Step 1: Generate an RSA Private Key

The first step is to generate an RSA private key, which will be used to create the self-signed certificate. Open your terminal or command prompt and run the following command:

openssl genrsa -aes256 -out jwt.private.pem 2048

This command generates an encrypted PEM private key. If you wish to generate a decrypted PEM based on it, you can use the following command:

openssl rsa -in jwt.private.pem -out decrypted.jwt.private.pem

Step 2: Generate a Public Key (Optional)

Generating a public key is optional in the context of creating a self-signed CA certificate for JWTs in Java. However, if you want to generate one, use the following command:

openssl rsa -pubout -in jwt.private.pem -out jwt.public.pem

The public key generation is not used in the Java keystores, but it can be useful for other purposes.

Step 3: Generate a Self-signed CA Certificate

Now, it's time to create the self-signed CA certificate using the private key you generated earlier. This certificate will be valid for one year. Customize the template by replacing the placeholder values with your own information. Run the following command:

openssl req -key jwt.private.pem -new -x509 -sha256 -days 365 -subj "/C=<2_LETTER_COUNTRY_CODE>/ST=<STATE_NAME>/L=<CITY_NAME>/O=<ORGANIZATION_NAME>/OU=<ORGANIZATIONAL_UNIT>/CN=<YOUR_NAME>/emailAddress=<YOUR_EMAIL_ADDR>" -out jwt.cert.pem

Here's a breakdown of the fields you need to replace:

  • <2_LETTER_COUNTRY_CODE>: The two-letter code of your country.
  • <STATE_NAME>: The name of your state.
  • <CITY_NAME>: The name of your city.
  • <ORGANIZATION_NAME>: The name of your organization.
  • <ORGANIZATIONAL_UNIT>: The name of your section in the organization.
  • <YOUR_NAME>: Your full name.
  • <YOUR_EMAIL_ADDR>: Your email address.

For example:

openssl req -key jwt.private.pem -new -x509 -sha256 -days 365 -subj "/C=NZ/ST=Wellington/L=Wellington/O=RnE/OU=IT/CN=Ronaldo Webb/emailAddress=ron@ronella.xyz" -out jwt.cert.pem

Step 4: Generate a PKCS12 File

Now, create a PKCS12 file by combining the generated private key and certificate. Give it the "selfsigned" alias using the following command:

openssl pkcs12 -export -in jwt.cert.pem -inkey jwt.private.pem -out jwt.pfx -name "selfsigned"

Step 5: Store the PKCS12 Content in a Java Keystore

Java applications often use keystores for certificate management. To store the content of the PKCS12 file in a Java keystore, use the following command:

"%JAVA_HOME%\bin\keytool" -importkeystore -destkeystore jwt-ks.jks -deststorepass password -deststoretype PKCS12 -srckeystore jwt.pfx -srcstoretype PKCS12 -srcstorepass password

Replace "%JAVA_HOME%" with the path to your Java installation directory and customize the keystore name and password as needed.

Step 6: Store the Certificate in a Java Truststore

In Java, truststores are used to store certificates that are trusted for secure communication. Store the certificate you generated earlier in a Java truststore with the "selfsigned" alias using the following command:

"%JAVA_HOME%\bin\keytool" -import -file jwt.cert.pem -keystore jwt-ts.jks -storetype PKCS12 -storepass password -alias selfsigned

Again, make sure to adjust the paths, keystore name, password, and alias according to your requirements.

By following these steps, you can generate a self-signed CA certificate for JWTs in Java, ensuring secure authentication and data transmission in your applications.

Related Topics

For further information on working with JWTs in Java, you can explore these related topics.

Generating a Self-signed CA Certificate for Java Keystores

Creating the java keystore and truststore with private key and certificate pair

  1. Download OpenSSL binaries from the following link if you are using windows:

    https://slproweb.com/products/Win32OpenSSL.html

  2. Create an openssl configuration (i.e. openssl.cnf) file using the following template:

    [ req ]
    default_bits        = 2048
    default_keyfile     = privkey.pem
    distinguished_name  = subject
    req_extensions      = req_ext
    x509_extensions     = x509_ext
    string_mask         = utf8only
    
    # The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
    #   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
    [ subject ]
    countryName         = Country Name (2 letter code)
    countryName_default     = <2_LETTER_COUNTRY_CODE>
    
    stateOrProvinceName     = State or Province Name (full name)
    stateOrProvinceName_default = <STATE_NAME>
    
    localityName            = Locality Name (eg, city)
    localityName_default        = <CITY_NAME>
    
    organizationName         = Organization Name (eg, company)
    organizationName_default    = <ORGANIZATION_NAME>
    
    organizationalUnitName   = Organizational Unit
    organizationalUnitName_default = <ORGANIZATIONAL_UNIT>
    
    # Use a friendly name here because it's presented to the user. The server's DNS
    #   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
    #   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
    #   must include the DNS name in the SAN too (otherwise, Chrome and others that
    #   strictly follow the CA/Browser Baseline Requirements will fail).
    commonName          = Common Name (e.g. server FQDN or YOUR name)
    commonName_default      = <YOUR_NAME>
    
    emailAddress            = Email Address
    emailAddress_default        = <YOUR_EMAIL_ADDRESS>
    
    # Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
    [ x509_ext ]
    
    subjectKeyIdentifier        = hash
    authorityKeyIdentifier    = keyid,issuer
    
    # You only need digitalSignature below. *If* you don't allow
    #   RSA Key transport (i.e., you use ephemeral cipher suites), then
    #   omit keyEncipherment because that's key transport.
    basicConstraints        = CA:FALSE
    keyUsage            = digitalSignature, keyEncipherment
    subjectAltName          = @alternate_names
    nsComment           = "OpenSSL Generated Certificate"
    
    # RFC 5280, Section 4.2.1.12 makes EKU optional
    #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
    #   In either case, you probably only need serverAuth.
    # extendedKeyUsage    = serverAuth, clientAuth
    
    # Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
    [ req_ext ]
    
    subjectKeyIdentifier        = hash
    
    basicConstraints        = CA:FALSE
    keyUsage            = digitalSignature, keyEncipherment
    subjectAltName          = @alternate_names
    nsComment           = "OpenSSL Generated Certificate"
    
    # RFC 5280, Section 4.2.1.12 makes EKU optional
    #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
    #   In either case, you probably only need serverAuth.
    # extendedKeyUsage    = serverAuth, clientAuth
    
    [ alternate_names ]
    
    DNS.1       = <DNS_1>
    
    # Add more DNS by incrementing the DNS.<SUFFIX> like the following.
    # 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
    
    # IPv6 localhost
    # DNS.8     = ::1
    
    # IP address using the following:
    # IP.1       = 127.0.0.1

    Replace the following fields on the template:

    Field Name Description
    2_LETTER_COUNTRY_CODE The two letter code of your country.
    STATE_NAME The name of your state.
    CITY_NAME The name of your city.
    ORGANIZATION_NAME The name of your organization.
    ORGANIZATIONAL_UNIT The name of your section in the organization.
    YOUR_NAME Your full name.
    YOUR_EMAIL_ADDR Your email address.
    DNS.<INDEX> Your DNS name.

    Example:

    [ req ]
    default_bits        = 2048
    default_keyfile     = privkey.pem
    distinguished_name  = subject
    req_extensions      = req_ext
    x509_extensions     = x509_ext
    string_mask         = utf8only
    
    # The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
    #   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
    [ subject ]
    countryName         = Country Name (2 letter code)
    countryName_default     = NZ
    
    stateOrProvinceName     = State or Province Name (full name)
    stateOrProvinceName_default = Wellington
    
    localityName            = Locality Name (eg, city)
    localityName_default        = Wellington
    
    organizationName         = Organization Name (eg, company)
    organizationName_default    = My Organization
    
    organizationalUnitName   = Organizational Unit
    organizationalUnitName_default = IT Department
    
    # Use a friendly name here because it's presented to the user. The server's DNS
    #   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
    #   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
    #   must include the DNS name in the SAN too (otherwise, Chrome and others that
    #   strictly follow the CA/Browser Baseline Requirements will fail).
    commonName          = Common Name (e.g. server FQDN or YOUR name)
    commonName_default      = Ronaldo Webb
    
    emailAddress            = Email Address
    emailAddress_default        = ron@ronella.xyz
    
    # Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
    [ x509_ext ]
    
    subjectKeyIdentifier        = hash
    authorityKeyIdentifier    = keyid,issuer
    
    # You only need digitalSignature below. *If* you don't allow
    #   RSA Key transport (i.e., you use ephemeral cipher suites), then
    #   omit keyEncipherment because that's key transport.
    basicConstraints        = CA:FALSE
    keyUsage            = digitalSignature, keyEncipherment
    subjectAltName          = @alternate_names
    nsComment           = "OpenSSL Generated Certificate"
    
    # RFC 5280, Section 4.2.1.12 makes EKU optional
    #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
    #   In either case, you probably only need serverAuth.
    # extendedKeyUsage    = serverAuth, clientAuth
    
    # Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
    [ req_ext ]
    
    subjectKeyIdentifier        = hash
    
    basicConstraints        = CA:FALSE
    keyUsage            = digitalSignature, keyEncipherment
    subjectAltName          = @alternate_names
    nsComment           = "OpenSSL Generated Certificate"
    
    # RFC 5280, Section 4.2.1.12 makes EKU optional
    #   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
    #   In either case, you probably only need serverAuth.
    # extendedKeyUsage    = serverAuth, clientAuth
    
    [ alternate_names ]
    
    DNS.1       = www.ronella.xyz
    
    # Add more DNS by incrementing the DNS.<SUFFIX> like the following.
    # 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
    
    # IPv6 localhost
    # DNS.8     = ::1
    
    # IP address using the following:
    # IP.1       = 127.0.0.1
  3. Save the openssl.cnf on your desired location.

  4. Generate the private key and certificate with 1yr validity using the following command:

    openssl req -config openssl.cnf -new -x509 -sha256 -newkey rsa:2048 -keyout privkey.pem -days 365 -out cert.pem
  5. Generate a pkcs12 file from the generated private key and certificate with the selfsigned alias using the following command:

    openssl pkcs12 -export -in cert.pem -inkey privkey.pem -out cert.pfx -name selfsigned
  6. Store the pfx file to a java keystore using the following command:

    "%JAVA_HOME%\bin\keytool" -importkeystore -destkeystore keystore.jks -deststorepass password -deststoretype PKCS12 -srckeystore cert.pfx -srcstoretype PKCS12 -srcstorepass password
  7. Store the certificate to a java truststore using the following command:

    "%JAVA_HOME%\bin\keytool" -import -file cert.pem -keystore truststore.jks -storetype PKCS12 -storepass password -alias selfsigned

Tomcat 8.5 Service Basic Management

Service Creation

  1. Open a cmd terminal and change the current directory to the following:

    %CATALINA_HOME%\bin

    In this directory you will find the following files:

    • tomcat8.exe
    • tomcat8w.exe
  2. Copy the file tomcat8w.exe to CustomTomcat8w.exe.

    tomcat8w.exe is in the following pattern:

    <SERVICE_NAME>w.exe

    This makes the default service name set to tomcat8. Copying it to CustomTomcat8w.exe makes a service name of CustomTomcat8.

  3. Set the basic properties of the CustomTomcat8 service using the following command:

    tomcat8.exe //IS//CustomTomcat8 --DisplayName="Apache Custom Tomcat 8" --Install="%CATALINA_HOME%\bin\tomcat8.exe" --StartMode=jvm --StopMode=jvm --StartClass=org.apache.catalina.startup.Bootstrap --StartParams=start --StopClass=org.apache.catalina.startup.Bootstrap --StopParams=stop --Description="Apache Custom Tomcat 8 by Ron"
  4. Set the classpath using the following command:

    tomcat8.exe //US//CustomTomcat8 --Classpath="%CATALINA_HOME%\bin\bootstrap.jar;%CATALINA_HOME%\bin\tomcat-juli.jar"
  5. Set the JVM to use using the following command:

    tomcat8.exe //US//CustomTomcat8 --Jvm="%JAVA_HOME%\jre\bin\server\jvm.dll"
  6. Set some JVM options using the following command:

    tomcat8.exe //US//CustomTomcat8 --JvmOptions="-Dcatalina.home=%CATALINA_HOME%;-Dcatalina.base=%CATALINA_HOME%"
  7. Set logging using the following command:

    tomcat8.exe //US//CustomTomcat8 --LogLevel="Info" --LogPrefix="custom_tomcat8_service-" --LogPath="%CATALINA_HOME%\logs" --StdOutput="auto" --StdError="auto" --PidFile="tomcat8.pid"
  8. Set JVM memory using the following command:

    tomcat8.exe //US//CustomTomcat8 --JvmMs=512 --JvmMx=1024

Service Post Creation

  1. Using the file explorer, find the directory specified by your CATALINA_HOME environment variable and add the LOCAL SERVICE group on the security. Also add the permissions Full Control and Modify to it.

    For example if your CATALINA_HOME is pointing to C:\dev\tools\apache-tomcat-8.5.64 directory, expect something like the following as an output:

  2. Using the file explorer, navigate to %CATALINA_HOME%\bin directory and double click the CustomTomcat8w.exe file. Click the Java tab and ensure that the Java Virtual Machine field was correctly set. If not, update it accordingly.

    For example if your JAVA_HOME is pointing to C:\Program Files\Java\jdk1.8.0_271 directory, ensure that the Java Virtual Machine field is pointing to the correct location of the jvm.dll.

Service Execution

  1. Open a cmd terminal and change the current directory to the following:

    %CATALINA_HOME%\bin
  2. Run the CustomTomcat8 service using the following command:

    tomcat8.exe //RS//CustomTomcat8

Service Termination

  1. Open a cmd terminal and change the current directory to the following:

    %CATALINA_HOME%\bin
  2. Stop the CustomTomcat8 service using the following command:

    tomcat8.exe //SS//CustomTomcat8

Service Removal

  1. Open a cmd terminal and change the current directory to the following:

    %CATALINA_HOME%\bin
  2. Remove the CustomTomcat8 service using the following command:

    tomcat8.exe //DS//CustomTomcat8

Windows Services App

After the service creation was completed and without any error, we can also manage the service using the windows services app. Just look for the value of the --DisplayName parameter (i.e. Apache Custom Tomcat 8) when setting the basic properties of the service. This is depicted as follows by the following snapshot:

Reference

Functional Programming with Gosu

First Class Citizen

An entity that can be passed around as an argument, returned from a function, modified and assigned to a variable.

First Class Function

A function that is treated as first class citizen.

Higher-Order Functions (HOF)

A function which takes function as an argument and/or that return a function.

Closure

A function that remembers its lexical scope even when the function is executed outside that lexical scope.

function greeterFn() : block() {
  var name="World" //name is a local variable created by init
  var greet = \-> print("Hello ${name}") //greet is an inner function 
                                         //that uses the variable declared 
                                         //in parent function.
  return greet
}

var greeter = greeterFn()
greeter()

Currying

The process of converting a function that takes multiple arguments into a function that takes them one at a time.

var sum = \ a : int, b : int -> a + b
print(sum(1,2))

var curriedSum = \ a : int -> \ b : int -> a + b
print(curriedSum(1)(2))

Function Composition

The act of putting two functions together to form a third function where the output of one function is the input of the other.

uses java.lang.Integer
uses java.lang.Double
uses java.lang.Math

var compose = \ output : block(out : Integer) : String, func : block(param: Double) : Integer -> \ arg : Double -> func(output(arg)) //Definition

var floorToString = compose(\ out -> out.toString(), \ param -> Math.floor(param)) //Usage

print(floorToString(121.212121))

Continuation

The part of the code that's yet to be executed.

uses java.lang.Double

var printAsString = \ num : Double -> print("Given ${num}")

var addOneAndContinue = \ num: Double, cc : block(___num : Double) -> {
  var result = num + 1
  cc(result)
}

addOneAndContinue(2, printAsString)

Purity

A function is pure if the return value is only determined by its input values, and does not produce side effects.

var greet = \ name: String -> print("Hello ${name}")
greet("World")

The following is not pure since it modifies state outside of the function:

var greeting : String
var greet = \ name: String -> {greeting ="Hello ${name}"}
greet("World")
print(greeting)

Side Effects

A function or expression is said to have a side if apart from returning a value, it interacts with (reads from or writes to) external mutable state.

var currentDate = java.util.Date.CurrentDate //Retrieves the date from the system.
print(currentDate)

gw.api.util.Logger.forCategory("side-effect").info('IO is a side effect!')

Idempotent

A function is idempotent if reapplying it to its result does not produce a different result.

print(java.lang.Math.abs(java.lang.Math.abs(10)))

Point-Free Style (Tacit Programming)

Write functions where the definition does not explicitly identify the arguments used. This style usually requires currying or other higher order functions.

uses java.lang.Integer

// Given
var map = \ fn : block(item : int) : int -> \ list : List<Integer> -> list.map<Integer>(\ item -> fn(item))
var add = \ a : int -> \ b : int -> a + b
var nums : List<Integer> = (0..5).toList()

// Not points-free - 'numbers' is an explicit argument
var incrementAll = \ numbers : List<Integer> -> map(add(1))(numbers)

print(incrementAll(nums))

// Points-free - The list is an implicit argument
var incrementAll2 = map(add(1))

print(incrementAll2(nums))

Predicate

A function that returns true or false for a given value.

var predicate = \ a : int -> a > 2

print((1..4).where(\ a -> predicate(a)))

Lambda

An anonymous function that can be treated like a value.

(\ a : int -> a + 1)(1)

Lambda can be assigned to a variable

var add1 = \ a : int -> a + 1
print(add1(1))

Reference

https://github.com/hemanth/functional-programming-jargon
https://en.wiktionary.org/wiki/second-class_object#English
https://en.wiktionary.org/wiki/third-class_object#English

Gosu Collection Enhancements Functions

flatMap

Maps each element of the Collection to a Collection of values and then flattens them into a single List.

Syntax

flatMap<R>(mapper(item : Collection<?>) : Collection<R>) : List<R>

Example

var items = {{1},{2,2},{3,3,3},{4,4,4,4}}
print(items.flatMap(\ ___item -> ___item))
Output
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

fold

Accumulates the values of an Collection into a single T.

Syntax

fold(aggregator(aggregate : T, item : T) : T) : T

Example

var items = {{1},{2,2},{3,3,3},{4,4,4,4}}
var flatItems = items.flatMap(\ ___item -> ___item)
print(flatItems.fold(\ ___aggr, ___item -> ___aggr + ___item))
Output
30

intersect

Returns a Set that is the intersection of the two Collection objects.

Syntax

intersect(that: Collection<T>) : Set<T>

Example

var items1 = {1,2,3,4,5,6}
var items2 = {4,5,6,7,8,9}
print(items1.intersect(items2))
Output
[4, 5, 6]

map

Returns a List of each element of the Collection mapped to a new value.

Syntax

map<Q>(mapper(item : <INPUT>) : <Q>) : List<Q>

Example

var numbers = {1,2,3}
var words = {"one","two","three"}
print(numbers.map(\ ___number -> words[___number-1]))
Output
[one, two, three]

partition

Partitions this Collection into a Map of keys to a list of elements in this Collection.

Syntax

partition<Q>(partitioner(item : R) : Q) : Map<Q, List<R>>

Example

var numbers = {1,2,3,4,5,6,8}
print(numbers.partition<String>(\ ___number -> ___number % 2 == 0 ? "even" : "odd"))
Output
{even=[2, 4, 6, 8], odd=[1, 3, 5]}

reduce

Accumulates the values of a Collection into a single V given an initial seed value

Syntax

reduce<T>(init : T, aggregrator(aggregate: T, item : ?) : T) : T

Example

var numbers = {1,2,3,4,5,6,8}
var sumOfNumbers = numbers.reduce(0, \ ___aggr, ___number -> ___aggr + ___number)
print(sumOfNumbers)
Output
29

union

Returns a new Set that is the union of the two Collections

Syntax

union(that : Collection<T>) : Set<T>

Example

var items1 = {1,2,3,4,5,6}
var items2 = {4,5,6,7,8,9}
print(items1.union(items2))
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

disjunction

Returns a new Set that is the set disjunction of this collection and the other collection

Syntax

disjunction(that : Collection<T>) : Set<T>

Example

var items1 = {1,2,3,4,5,6}
var items2 = {4,5,6,7,8,9}
print(items1.disjunction(items2))
Output
[1, 2, 3, 7, 8, 9]

join

Joins all elements together as a string with a delimiter

Syntax

join(delim : String) : String

Example

var words = {"Hello", "World"}
print(words.join(" "))
Output
Hello World

Maven Scope to Gradle Configuration Mapping

Maven Gradle Comment
compile api if the dependency should be exposed to consumers.
implementation if the dependency should not be exposed to consumers.
provided compileOnly Maven provided is also available at runtime. Gradle compileOnly is limited to compile only.
runtime runtimeOnly
test testImplementation

IPv6 Unicast Address Types

Global Unicast Address

This address has a global scope with the same purpose as IPv4 public address.

Link Local Address

This address has a local scope and cannot be used outside the link (i.e. network segment or broadcast address) and non routable. Normally has the following prefix:

FE80::/10

Loopback Address

This address corresponds to the software loopback interface of the network card and doesn't necessarily requires hardware associated with it. Normally has the following address:

::1/128

Unspecified Address

This address indicates an absence of address. This is represented by the following:

::/128

Unique Local Address

This is analogous to IPv4 private networking and has the following range:

FC00::/7
FD00::/8

Assigning an IP to an Interface of a Cisco Router

Pre-requisite

  • Putty application

Displaying the Interfaces

Use the following command to display the available interfaces and their states:

show ip interface brief

Assigning an IP

  1. Connect to cisco console using putty.

  2. Press the enter key to enter into user mode.

  3. Execute the following command to enter into privilege mode:

    enable
  4. Load the startup-config into the running-config using the following command:

    copy startup-config running-config
  5. Execute the following command to enter into the configuration mode:

    config terminal
  6. Configure an interface using the following syntax:

    interface <INTERFACE_NAME> 

    Example

    interface GigabitEthernet0/0
  7. Assign an IP address using the following syntax:

    ip address <IP_ADDRESS> <SUBNET_MASK>

    Example

    ip address 10.0.0.210 255.255.255.0
  8. Turn on the interface using the following command:

    no shutdown
  9. Exit the interface configuration using the following command:

    exit
  10. Exit the configuration mode:

    exit

    After this you can display the interfaces and see the state of the interface just configured

  11. Save the update on the running-config to the startup-config file using the following command:

    copy running-config startup-config

Synchronizing Logging in Cisco Router

To always have a readable command line on cisco console, aux and/or virtual terminals it is recommended to synchronize the logging.

Pre-requisite

  • Putty application

Synchronizing the Logging

  1. Connect to cisco console using putty.

  2. Press the enter key to enter into user mode.

  3. Execute the following command to enter into privilege mode:

    enable
  4. Load the startup-config into the running-config using the following command:

    copy startup-config running-config
  5. Execute the following command to enter into the configuration mode:

    config terminal
  6. Synchronize the logging on console using the following commands:

    line con 0
    logging sync
  7. Synchronize the logging on AUX using the following command:

    line aux 0
    logging sync
  8. (Optional) Synchronize the logging on 5 virtual terminals using the following command:

    line vty 0 4
    logging sync

    Only do this if you are using virtual terminals, specially with SSH connections.

  9. Exit the virtual terminal configuration using the following command:

    exit
  10. Exit the configuration mode:

    exit
  11. Save the update on the running-config to the startup-config file using the following command:

    copy running-config startup-config
« Older posts Newer posts »