Generate and Prepare a new GPG key for Github

Generating a GPG key

gpg --full-generate-key
gpg --list-secret-keys --keyid-format=long

From the list of GPG keys, copy the long form of the GPG key ID you’d like to use. In this example, the GPG key ID is 3AA5C34371567BD2:

$ gpg --list-secret-keys --keyid-format=long
/Users/hubot/.gnupg/secring.gpg
------------------------------------
sec   4096R/3AA5C34371567BD2 2016-03-10 [expires: 2017-03-10]
uid                          Hubot 
ssb   4096R/42B317FD4BA89E7A 2016-03-10
gpg --armor --export 3AA5C34371567BD2
# Prints the GPG key ID, in ASCII armor format

Copy your GPG key, beginning with -----BEGIN PGP PUBLIC KEY BLOCK----- and ending with -----END PGP PUBLIC KEY BLOCK-----.

References
https://docs.github.com/en/authentication/managing-commit-signature-verification/generating-a-new-gpg-key

Export and Import GPG private key

gpg --list-secret-keys --keyid-format LONG

Example output:

pub   4096R/ABC12345 2020-01-01 [expires: 2025-12-31]
uid                  Your Name <user@example.com>
sub   4096R/DEF67890 2020-01-01 [expires: 2025-12-31]

Remember the ID of your key (second column, after the slash, e.g. “ABC12345”). If you have a “sub” entry, you can ignore it.

Run this command to export your key:

gpg --export-secret-keys YOUR_ID_HERE > private.key

Run this command to import your key:

gpg --import private.key

References
https://makandracards.com/makandra-orga/37763-gpg-extract-private-key-and-import-on-different-machine

Run Code after React Component using Effect Hook

Effects Without Cleanup
we can run them and immediately forget about them.

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Effects with Cleanup

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

We don’t have to return a named function from the effect. We called it cleanup here to clarify its purpose, but you could return an arrow function or call it something different.

Use Multiple Effects to Separate Concerns

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });
  // ...
}

Optimizing Performance by Skipping Effects

You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

make sure the array includes all values from the component scope (such as props and state) that change over time and that are used by the effect. Otherwise, your code will reference stale values from previous renders.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

Always add everything you refer to inside of useEffect() as dependency.

References
https://reactjs.org/docs/hooks-effect.html

HTML Form Elements in React

import React, {useState} from "react";

function Info() {
    const [name, setName] = useState("");

    return (
        <div>
            <div>
                <label>
                    Name:
                    <input type="text" placeholder="Enter your name" value={name}
                           onChange={event => {
                               setName(event.target.value)
                           }}/>
                </label>

            </div>
            <div>
                Result : Hello {name}
            </div>

        </div>
    );
}

export default Info;

In most cases, it’s recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

References
https://reactjs.org/docs/forms.html
https://reactjs.org/docs/uncontrolled-components.html
https://reactjs.org/docs/refs-and-the-dom.html

Install Tailwind CSS in React

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Add the paths to all of your template files in your tailwind.config.js file.

module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the @tailwind directives for each of Tailwind’s layers to your ./src/index.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

Run your build process with npm run start.

npm run start

References
https://tailwindcss.com/docs/guides/create-react-app

Read a configuration file in Java

app.config

app.name=Properties Sample Code
app.version=1.09
Properties prop = new Properties();
String fileName = "app.config";
try (FileInputStream fis = new FileInputStream(fileName)) {
    prop.load(fis);
} catch (FileNotFoundException ex) {
    ... // FileNotFoundException catch is optional and can be collapsed
} catch (IOException ex) {
    ...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));

References
https://stackoverflow.com/questions/16273174/how-to-read-a-configuration-file-in-java

Logging in Spring Boot

When using starters, Logback is used for logging by default.

@RestController
public class LoggingController {

    Logger logger = LoggerFactory.getLogger(LoggingController.class);

    @RequestMapping("/")
    public String index() {
        logger.trace("A TRACE Message");
        logger.debug("A DEBUG Message");
        logger.info("An INFO Message");
        logger.warn("A WARN Message");
        logger.error("An ERROR Message");

        return "Howdy! Check out the Logs to see the output...";
    }
}

the default logging level of the Logger is preset to INFO, meaning that TRACE and DEBUG messages are not visible.

References
https://www.baeldung.com/spring-boot-logging

Controlling Bean Creation Order with @DependsOn Annotation in Spring Boot

Spring, by default, manages beans’ lifecycle and arranges their initialization order.

But, we can still customize it based on our needs. We can choose either the SmartLifeCycle interface or the @DependsOn annotation for managing initialization order.

@Configuration
@ComponentScan("com.baeldung.dependson")
public class Config {
 
    @Bean
    @DependsOn({"fileReader","fileWriter"})
    public FileProcessor fileProcessor(){
        return new FileProcessor();
    }
    
    @Bean("fileReader")
    public FileReader fileReader() {
        return new FileReader();
    }
    
    @Bean("fileWriter")
    public FileWriter fileWriter() {
        return new FileWriter();
    }   
}

Finally, there are few points which we should take care of while using @DependsOn annotation:

  • While using @DependsOn, we must use component-scanning
  • If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored

DependsOnDatabaseInitialization Annotation

Indicate that a bean’s creation and initialization depends upon database initialization having completed. May be used on a bean’s class or its @Bean definition.

References
https://www.baeldung.com/spring-depends-on

Create Events for React Component

Counter.tsx

import {useState} from "react";

function Counter(props: CounterProp) {
    const [count, setCount] = useState(0)

    const buttonClicked = () => {
        setCount(prevState => {

            var result = prevState + 1;

            if (props.onCounterChanged != null) {
                props.onCounterChanged(result);
            }

            return result;
        })
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={buttonClicked}>Next
            </button>
        </div>
    );
}

export interface CounterProp {
    onCounterChanged?: (value: number) => void;
}

export default Counter;

App.tsx

import React from 'react';
import Counter from "./components/Counter";

function App() {
    return (
        <div className={"px-1"}>
            <Counter onCounterChanged={(value => console.log(value))}></Counter>
        </div>

    );
}

export default App;

References
https://www.tutorialsteacher.com/typescript/typescript-interface
https://stackoverflow.com/questions/39713349/make-all-properties-within-a-typescript-interface-optional