Tech Rocks

Developer's blog
tech knowledge base

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Sunday, October 13, 2024

Verify ISO

Download the iso and checksums (sha256sum.txt) and use the below commands to verify

CertUtil -hashfile linuxmint-22-mate-64bit.iso SHA256

grep 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' ./sha256sum.txt

References :

Wednesday, October 9, 2024

Roman Numerals in Java


package com.example.demo.utils.math;

import java.io.IOException;
import java.util.TreeMap;

public class RomanNumeral {

    private final static TreeMap map = new TreeMap();

    static {

        map.put(1000, "M");
        map.put(900, "CM");
        map.put(500, "D");
        map.put(400, "CD");
        map.put(100, "C");
        map.put(90, "XC");
        map.put(50, "L");
        map.put(40, "XL");
        map.put(10, "X");
        map.put(9, "IX");
        map.put(5, "V");
        map.put(4, "IV");
        map.put(1, "I");

    }

    public final static String toRoman(int number) {
        int l =  map.floorKey(number);
        if ( number == l ) {
            return map.get(number);
        }
        return map.get(l) + toRoman(number-l);
    }

    public static void main(String[] args) throws IOException {
        int v = 113;
        System.out.println("############################################");
        System.out.println("\t\t\t\t" + v + " = " + toRoman(v));
        System.out.println("############################################");
    }

}


References :

Friday, September 27, 2024

List of Files in Java


################################## Example 2 ##################################

package com.example.demo.utils.scan;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileScanner {
    public static void main(String[] args) throws IOException {
        Files.write(
                Paths.get("C:\\Users\\j\\Documents\\out.csv"),
                getList(new File("C:\\").listFiles(), new StringBuffer()).toString().getBytes(),
                StandardOpenOption.TRUNCATE_EXISTING);
    }

    public static StringBuffer getList(File[] listOfFiles, StringBuffer sb) {
        if (listOfFiles != null)
            for (File i : listOfFiles)
                if (i.isFile()) {
                    sb.append("\"" + i.getPath() + "\"" + "," + "\"" 
                    + i.length() + "\"" + "," + "\"" + i.lastModified() + "\"" + "\n");
                    System.out.println(i.getName());
                } else if (i.isDirectory()) getList(new File(i.getPath()).listFiles(), sb);
        return sb;
    }
}


################################## Example 1 ##################################


package org.example;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        String out = "C:\\Users\\j\\Documents\\out.txt";
        clearfile("", out);
        getList("C:\\");
        //writefile("in", "C:\\Users\\j\\Documents\\out.txt");
    }

    public static void getList(String path) throws IOException {
      //  System.out.println("Hello jeetu!");
        String out = "C:\\Users\\j\\Documents\\out.txt";
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        if (listOfFiles != null) {
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {

                    long fileSizeInBytes = listOfFiles[i].length();
                    // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
                    //long fileSizeInKB = fileSizeInBytes / 1024;
                    // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
                    //long fileSizeInMB = fileSizeInKB / 1024;

                   // System.out.println(listOfFiles[i].getName());
                    writefile(listOfFiles[i].getPath(), out);
                    writefile("," + fileSizeInBytes, out);
                    writefile("\n", out);

                    System.out.println(listOfFiles[i].getName() + ","  + fileSizeInBytes);

                } else if (listOfFiles[i].isDirectory()) {
                    //System.out.println("Directory " + listOfFiles[i].getName());
                    //System.out.println("Directory " + listOfFiles[i].getPath());
                    getList(listOfFiles[i].getPath());
                }
            }
        }
    }


    public static void writefile(String content, String path) throws IOException {


        Files.write(
                Paths.get(path),
                content.getBytes(),
                StandardOpenOption.APPEND);
    }

    public static void clearfile(String content, String path) throws IOException {


        Files.write(
                Paths.get(path),
                content.getBytes(),
                StandardOpenOption.TRUNCATE_EXISTING);
    }
}

References :

Tuesday, September 24, 2024

Kafka on Docker


### KAFKA DEV NODE - with GUI
git clone https://github.com/jeethualex/kafka-development-node.git

cd kafka-development-node

docker compose up
# Check urls - http://localhost:3000/ 
# and http:/localhost:8080/ui/clusters/local/all-topics/demo/messages?limit=100&mode=LATEST

docker compose down



### BASIC KAFKA TESTS

docker run -d --name=kafka -p 9092:9092 apache/kafka
docker ps
## Start cluster
docker exec -ti kafka /opt/kafka/bin/kafka-cluster.sh cluster-id --bootstrap-server :9092

docker ps

## Publich to topic - Crtl + C to exit
## Keep entering messages using enter
docker exec -ti kafka /opt/kafka/bin/kafka-console-producer.sh --bootstrap-server :9092 --topic demo

## Consume from topic - Crtl + C to exit
## Open in new terminal
## Keep receiving messages
docker exec -ti kafka /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server :9092 --topic demo --from-beginning


References :

Wednesday, September 18, 2024

Gradle to Maven Publish

Add to build.gradle
apply plugin: 'maven-publish'

publishing {
	publications {
		customLibrary(MavenPublication) {
			from components.java
		}
	}

	repositories {
		maven {
			name = 'sampleRepo'
			url = layout.buildDirectory.dir("repo")
		}
	}
}

Spring security example 2

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests(
                auth -> auth.requestMatchers("/employees/**", "/greeting/**", "/hello/**")
                        .permitAll().anyRequest().authenticated());

        http.httpBasic(withDefaults());

        http.csrf(csrf -> csrf.disable());

        return http.build();

    }

    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {
        var authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);

        return new ProviderManager(authenticationProvider);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user1")
                .password("{noop}secret1")
                .authorities("read")
                .roles("USER")
                .build();
        UserDetails userOne = User.withUsername("admin1")
                .password("{noop}secret1")
                .authorities("read")
                .roles("ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, userOne);
    }

}


Spring security example


package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
public class SecurityConfig {

    @Bean
    public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.withUsername("user1")
                .password(passwordEncoder.encode("secret1"))
                .roles("USER")
                .build();

        UserDetails admin = User.withUsername("admin1")
                .password(passwordEncoder.encode("secret1"))
                .roles("USER", "ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(request -> request.anyRequest()
                        .authenticated())
                .httpBasic(Customizer.withDefaults())
                .build();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return encoder;
    }

}

Monday, September 16, 2024

Spring Boot Example

Clone the below repo using the commands on windows git bash

## Get the code
# Versions jdk 19 and spring boot 3.3.3
git clone https://github.com/jeethualex/spring.git

## Build project
gradle build
mvn clean install

## Local run
gradle bootRun

## Run the jar file - with gradle
java -jar .\build\libs\demo-0.0.1-SNAPSHOT.jar

## Run the jar file - with maven
java -jar .\target\demo-0.0.1-SNAPSHOT.jar

###### GREETINGS ######

## launch urls below 

# http://localhost:8080/hello
curl http://localhost:8080/greeting
curl http://localhost:8080/hello

# http://localhost:8080/hello?name=G2
curl http://localhost:8080/greeting?name=G2
curl http://localhost:8080/hello?name=G2


###### EMPLOYEES CRUD ######

## before running these commands will need a local mysql database server installed with 2 env variables
## will create a spring database with employee table
## Env variables needed to be added on windows are MYSQl_USER and MYSQL_PASS

## Create Employees
curl --location 'localhost:8080/employee' \
--header 'Content-Type: application/json' \
--data '{
    "name":"jeetu",
    "department":"IT"
}'

## Get all Employees
curl --location 'localhost:8080/employees' \
--header 'Content-Type: application/json'

## Get Employee
curl --location 'localhost:8080/employee/1' \
--header 'Content-Type: application/json'

## Delete Employee
curl --location --request DELETE 'localhost:8080/employee/4' \
--header 'Content-Type: application/json'

## Update Employee
curl --location --request PUT 'localhost:8080/employee' \
--header 'Content-Type: application/json' \
--data '{
    "id":"1",
    "name":"jeetu",
    "department":"HR"
}'

###### CUSTOMER JDBC ######
curl http://localhost:8080/customer?name=G2
# Check the logs for db queries
# Try the postman collection

References :