if else condition with Java Lamba – Howto

//lambda Predicate
private static Predicate<HttpStatus> isErrorCode = (HttpStatus statusCode) -> (statusCode.is5xxServerError() || statusCode.is4xxClientError());

//your method
public static Mono<ClientResponse> getResponse(ClientResponse clientResponse) {
        if (isErrorCode.test(clientResponse.statusCode())) {

Do not forget to checkout the BiPredicate as well 😉

Java Stream Custom Collector – Howto

Sometimes the commonly available Collectors are not what we need.
Here is one example for a Singleton Custom Collector:

public static <T> Collector<T, ?, T> singleton() {
    return Collectors.collectingAndThen(
            Collectors.toList(), list -> {
                if (list.size() != 1) {
                    // or log and return nil
                    throw new CustomException();
                }
                return list.get(0);
            }
    );
}

//and use it:
        myObjectToStream.stream()
        .filter(elem -> elem.getExampleAttribute() == 0).collect(singleton());

Howto generate a new SSH key pair

ssh-keygen -t ed25519 -C "email@example.com"

Note that in this example we use an ed25519 key.

The -c is providing a comment to divide the key amongst others.

I alwas use the suggested path and just klick enter 😉

How to run eslint in Terminal / Shell

npm install && npm i -g eslint && npx eslint --ext .tsx --ext .ts ./

Please heed that npm install is used here to start my React application, which uses it as a build tool. IMportant

npm i -g eslint will install eslint, if it does not exist yet (for example a CI with Jenkins).

The npx eventually executes eslint for all files with ending .tsx or .ts recursively in the current directory. Please adapt the endings according to your needs – when you do not use TypeScript but JavaScript change it to .js

How to check Typescript Code with ESLint in IntelliJ or Webstorm

In your package.json add this example config:

 "eslintConfig": {
    "parserOptions": {
      "parser": "babel-eslint",
      "sourceType": "module"
    },
    "env": {
      "browser": true,
      "es6": true
    },
    "globals": {
      "Vue": true
    },
    "parser": "@typescript-eslint/parser",
    "plugins": [
      "@typescript-eslint"
    ],
    "extends": [
      "plugin:@typescript-eslint/recommended"
    ],
    "rules": {
      "quotes": [
        "error",
        "double",
        {
          "avoidEscape": true
        }
      ],
      "comma-dangle": [
        "error",
        {
          "arrays": "ignore",
          "objects": "always-multiline",
          "imports": "never",
          "exports": "never",
          "functions": "ignore"
        }
      ],
      "arrow-parens": 0,
      "no-tabs": 0,
      "indent": [
        "error",
        "tab",
        {
          "SwitchCase": 1
        }
      ],
      "no-console": 1,
      "generator-star-spacing": 0
    }
  }

In your IDE terminal, execute:

npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

In IntelliJ settings, add:

From now on, when you open your .ts or .tsx files, the ESLint will detect the errors.

You can open the context menu then, by clicking the right mouse tab and click on „Fix ESlint Problems“.

IntelliJ will then automatically fix the problems.

How to create an NPM Package

You want reusable components, elements? Flexible structure?
Separation of concerns, decoupling in your JS Code?

A good strategy is to create an NPM Package.

  • Identify the code you would like to decouple.
  • create a new project
  • create an src folder
  • paste the JS or TS files in that folder
  • install the missing dependencies like Typescript, TSlint, Material UI
  • Write UNIT Tests to test your code before publishing it

I use JEST and to include the relevant Code, add this to your tsconfig.json:

    "include": ["src/**/*"],
    "exclude": ["node_modules", "**/__tests__/*"] 

Before the package is published, you can test it locally:

  • In your terminal, run npm link
  • This will compile and create a symbolic link, pointing to another directory/files on your development machine.
  • Now include the new package as a dependency. In your terminal, run npm link <module_name>
  • If everything can be imported and used, the test work and you are satisfied, perform npm unlink --nosave <module_name> on your main projects directory. This will remove the symbolic link.
  • Then run npm unlink to also remove the global link.

Now you have extracted and published Code as NPM package.

JUnit Test String contained / contains String

With the Hamcrest Matchers, do this:

//imports
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;

//assert
assertThat(actualData, containsString(expectedData));

Make JavaScript Code prettier | Format your JS or Typescript Code with Prettier in IntelliJ IDEA or Webstorm

Java Developers know it as Checkstyle – JavaScript has similar things, one of them I highly recommend is prettier.

From the Marketplace PlugIns, just install Node and the Prettier PlugIn.

In your terminal or shell, type:

  • npm install --save-dev --save-exact prettier
  • npm install --global prettier
  1. In the Settings/Preferences dialog Ctrl+Alt+S
  2. go to Languages and Frameworks | JavaScript | Prettier.
  3. Choose the Node.js interpreter to use.
  4. From the Prettier package list, select the prettier installation to use.
  5. IntelliJ IDEA will locate the prettier package itself and the field is filled in automatically.
  6. To run Prettier automatically against specific files every time such file is changed and saved, select the Run on save for files checkbox.
  7. Provide a pattern that defines the set of files to be reformatted every timeon save.

Prettier will now also format your files on save.

In you package.json you can specify prettier:

In the project where Prettier is enabled, open package.json and click Yes in the pane at the top of the tab. Sometimes it is shown in the context menu, right click and bottom of the options in the list.

Config File

Example of a .prettierrc.json:

{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true,
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
},
{
"files": ["*.html", "legacy/**/*.js", "*.tsx"],
"options": {
"tabWidth": 4
}
}
]
}

Format inline

I select the lines of Code and just press CMD+ALT+SHIFT+P
The Code will be reformatted instantly.

Link to Prettier: https://prettier.io/docs/en/configuration.html

React – use CSS depending on states (change class according to a variable’s state)

For this example I use React Hooks and a Component with a stateful variable.
When the variable is changed, the CSS class is changed accordingly.
The part in the component is automatically re-rendered on the fly.

//The variable is called 'active'. 
//This is an example. Choose any name.
const [active, setActive] = useState(0);

We use the constant #getStyle to return a CSS class name based on the variable.

    const getStyle = (input) => {
        if (input === active){
            // This example is freely chosen. 
            //button-active is the CSS class' name
            return "button-active";
        } else {
            return "button-inactive";
        }
    };

The return statement returns rendered HTML.

//The hard coded value 0 can be any dynamic 
//variable from JS or React, like one from the 
//props (Properties) object
return (
  <div className={getStyle(0)}>
  </div>
);
  • Stateful variable called ‚active‘
  • Const named #getStyle with an input parameter
  • render method returning HTML with a css class name
  • Input is provided to the #getStyle const
  • If the variable ‚active‘ is changed by the application somewhere, the HTML is re-rendered
  • The input is compared to the variable and the name of the CSS class returned