Latest published articles

Safely retrieve properties using Supplier and Optional in Java

Safely retrieve properties using Supplier and Optional in Java

The supplier allows you to pass something but not retrieve it right away. One use case is retrieving a property an object that could throw a null pointer exception. By not retrieving right away, but instead using a supplier, the supplier can be later executed inside a try/catch block and handle any exceptions thrown.

public void example() {
    // Without supplier - could throw a nullpointer exception on any getter
    try {
        String str = someObject.getLevel1().getLevel2().getLevel3().getString();
        someOtherObject.appendValue(str);
    catch (Exception e) {
        // Exception throw - do nothing
        // This code is ugly!!!
    }

    // With supplier
    Optional<String> result = resolve() => someObject.getLevel1().getLevel2().getLevel3().getString());
    // Now we can do something if the property is present or skip if it doesn't exist
    // Much cleaner code
    result.ifPresent(someOtherObject::appendValue);
}


// This resolve method can be reused
protected <T> Optional<T> resolve(Supplier<T> supplier) {
    try {
        T result = resolver.get();
        return Optional.ofNullable(result);
    } catch (NullPointerException) {
        return Optional.empty();
    }
}

Function Composition in Java

Function Composition in Java

An incredible tool in Java is the ability to create functions and compose them.

One common use case is to extract a variable from an object and then transform it.

In the object oriented paradigm, you would have a method that extracts and another that transforms. Then intermediate variables would be used to convert from the initial object to the final transformed result.

With function composition this is greatly simplified. The separate steps can be defined as functions and then composed together to create the chain of events that need to occur. Then, the final composed function can be used instead of manually calling each method. See the examples below.

Eclipse Gotcha: Refactor->Move not showing up in Git

Eclipse Gotcha: Refactor->Move Not Showing Up in Git

In eclipse, if you refactor->move a file from one project to another, it may not show up in your eclipse git staging as deleted from the original project.

To Avoid: Copy the file to a different project and then delete from the original.

To Fix: Use the command line to delete the file (it will no longer show up in eclipse, but the command line will display it) and then use git from then command line to push the change.

Set Interval Timer

Set Interval Timer

Be careful when using setInterval as a timer.

let timeInSeconds = 0;
let interval = setInterval(() => {
    someFunction();
    timeInSeconds++;
}, 1000);

While it appears your time increments every second, it will actually increment one second (1000 milliseconds) plus the time the someFuntion() takes to run. This timer will eventually be out of sync.

A better approach is to create a point in time when the timer starts and then subtract the difference anytime the timeInSeconds is updated. In this scenerio, you can set the interval to any milliseconds amount and get an accurate time everytime the timeInSeconds variable is updated.

React Reducer Runs Twice

React Reducer Runs Twice

If using the react hook useReducer(reducer, state) and you notice it runs twice after dispatching an action - this is actually by design for development mode.

The reducer dispatches an action with a given state and returns a new state. It should never mutate the previous state.

If you follow this rule, you’ll never notice the reducer running twice. However if you are mutating the state and returning the new state based off that, you’ll make the mutation twice. So if you are adding something to a list in the state, you’ll see it added twice. This feature of react development keeps our functions pure. Pure functions are much easier to test.

Maintaining List Order in Jpa

Maintaining List Order in Jpa

If you want to maintain the order of a list of objects retrieve from the database using hibernate/jpa, use the @OrderColumn annotation. An additional column will be created in the database (if ddl is set to update) that will keep track of the order/position of an item in a list.

CAVEAT: If you change the position of an item in a list OR delete an item besides the last one, it will cause a multi update across the list to update all other positions. Be aware of this intensive operation for large lists.

Postgres: Useful PSQL Commands

Postgres: Useful PSQL Commands

Connect to a database

psql -d dbname -U password

Create a database

CREATE DATABASE mydb;

Create a user

create user myuser with encrypted password 'mypasswd';

Grant Privileges

grant all privileges on database mydb to myuser;

To list databases

\l

To list users

\du

List all tables

\dt

Describe tables

\d

List schemas

\dn

Switch database

\c dbName

Run psql commands from file \i fileName

Check version

SELECT VERSION();

Quit

\q

SQL Injection

SQL Injection

SQL injection occurs when SQL code can be injected into API input. In this injection attack, valid input has SQL commands concatened with SQL execution commands. When the SQL code is executed, the commands are run. In this process data can be mutated and returned to the attacker.

Mitigation Tips:

  • Use prepared statements instead of concatenated SQL statements. This seperates inputs from the command.
  • Restrict the user account that the SQL command is executed with to only allowable actions.
  • Always sanitize input on the server.
  • Never trust the client input to have sanitized input, it can be exploited by an attacker.
  • Use mature libraries for data sanitization, there are too many variants to look for to write custom sanitation code.

API Security

API Security

Always remember the CIA triad when securing API’s:

  • C: Confidentiality - Only intended audience can access information.
  • I: Integrity - Prevent unathorized mutation of data.
  • A: Availability - API can be reached by legitimate users.

Common API Threats: STRIDE

  • S: Spoofing - pretending to be someone else
  • T: Tampering - altering data
  • R: Repudiation - denying authorship
  • I: Information disclosure - revelaing private information
  • D: Denial of Service - preventing access
  • E: Elevation of Privilige - gaining access to unauthorized information

React Hook Example: useState

React Hook Example: UseState

Below is an example of React hook useState to change the state of a boolean.


const MyCustomButton: React.FC<Props> = props => {
    // first argument defines the variable
    // second argument defines the funtion that changes the state
    // third - the assignment sets initial state
    const [open, setOpen] = React.useState<boolean>(false);

    return (
        <Button
        onClick={() => setOpen(true)}  // calls the function that will set the state
        >
    );
};

Auditing With Envers

Auditing With Envers

You can audit any changes to any entity using envers.

Dependency and configuration found at: https://hibernate.org/orm/envers/

Then annnotate entities to audit:

@Entity
@Audited
public class Employee { ... }

Now when you make changes to an entity an audit entry will be created automatically.

Employee emp = employeeRepo.findById(1L);
emp.setSalary(75000);
employeeRepo.save(emp); // audit table will be updated here automatically to an audit table

Audit tables can be created automatically by Spring/Hibernate with hibernate.hbm2ddl.auto=update

Envers is a useful library for building in auditing into your existing Hibernate application.