Ruby on Rails installation windows 10 or 11 basic commands

install ruby on rails on windows 10

  1. go to https://nodejs.org/en/ and download LTS (long time support) nodejs and install it
  2. https://classic.yarnpkg.com/en/docs/install#windows-stable – install yarn packages
  3. https://www.sqlite.org/download.html – donwload “64-bit DLL (x64) for SQLite” and “A bundle of command-line tools for managing SQLite database files, including the command-line shell program, the sqldiff.exe program, and the sqlite3_analyzer.exe program.” extract and copy files to “windows/system32 folder”. Edit environment variables and add sqlite3 there.
  4. https://rubyinstaller.org – download and install it on windows
  5. open command line and run “gem install sqlite3”
  6. open command line and run “gem install rails”
  7. Installation is complete. now check versions ruby –version sqlite3 –version node –version yarn –version gem –version rails –version

run ruby file ruby ./hello.rb

###create new rails project rails new

###start rails server rails server

###some rails commands rails server (rails s) rails console (rails c) rails generate (rails g)

rails generate controller root

run your database migrations: rails db:migrate

rails generate controller home index

yarn add bootstrap jquery popper.js

add bootstrap css and js – https://getbootstrap.com/docs/5.2/getting-started/introduction/ in application.html.erb – app/views/layout/application.html.erb

create model

rails g model Post title:string description:text

the schema will be found in test/fixtures/posts.yml. the following command will execute db migration rails db:migrate

command to run -rails console -Post.connection -a=Post -a=Post.new -a.title=”hello” -a.description=”world” -a.save -a -Post.find(1) -Post.find(1).destroy

use “bundle” command when you are uncomment gemfile line.

#rails g controller sessions

#rails g controller users

#rails g model User email:uniq password:digest

#rails db:migrate

Purab’s IntelliJ IDEA File and Code Templates for Productive SpringBoot development

For devlopment I am using Intellij IDE. I found “File and Code Templates” and “Live Templates” very useful, It is beneficial while doing day-to-day development. It saves some time and be more productive.

github link: https://github.com/purab/IntelliJ-IDEA-File-Templates

Mostly we work on Rest APIs. So I created the following File Templates

  1. Spring Controller
  2. Spring Entity
  3. Spring Repository
  4. Spring Service
  5. Spring Static Service

Go to file-> setting and search for “File Templates”. 

Spring Controller

  • On Files tab click on + (Create Template)
  • Enter Name as : “SpringController”, and leave Extension as java
  • In the Content text box add the following content
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#set( $CamelCaseName = "$NAME.substring(0,1).toLowerCase()$NAME.substring(1)" )

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ${NAME}Controller {
	
	@GetMapping("/${CamelCaseName}s")
	public List<${NAME}> getAll${NAME}s() {
		return ${NAME}Service.getAll${NAME}s();
	}
	
	@GetMapping("/${CamelCaseName}/{${CamelCaseName}Id}")
	public ${NAME} get${NAME}Details(@PathVariable Long ${CamelCaseName}Id) {
		return ${NAME}Service.get${NAME}Details(${CamelCaseName}Id);
	}

	@PostMapping("/add${NAME}")
	public ${NAME} add${NAME}(@RequestBody ${NAME} ${CamelCaseName}) {
		return ${NAME}Service.add${NAME}(${CamelCaseName});
	}
	
	@PutMapping("/update${NAME}/{${CamelCaseName}Id}")
	public ${NAME} update${NAME}(@PathVariable Long ${CamelCaseName}Id, @RequestBody ${NAME} ${CamelCaseName}) {
		return ${NAME}Service.update${NAME}(${CamelCaseName}Id, ${CamelCaseName});
	}
	
	@DeleteMapping("/delete${NAME}/{${CamelCaseName}Id}")
	public ${NAME} delete${NAME}(@PathVariable Long ${CamelCaseName}Id) {

		return ${NAME}Service.delete${NAME}(${CamelCaseName}Id);
	}
}
  • Click Ok Button

Spring Entity

  • On Files tab click on + (Create Template)
  • Enter Name as : “SpringController”, and leave Extension as java
  • In the Content text box add the following content
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end

import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "${NAME}")
public class ${NAME} {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
	
	public ${NAME}() {}
	
	public ${NAME}(Long id, String name) {		
		this.id = id;
		this.name = name;		
	}

}
  • Click Ok Button

Spring Repository

  • On Files tab click on + (Create Template)
  • Enter Name as : “SpringController”, and leave Extension as java
  • In the Content text box add the following content
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#set ($index = $NAME.indexOf('Repository'))
#set ($ENTITY= $NAME.substring(0, $index))

import org.springframework.data.jpa.repository.JpaRepository;

public interface ${NAME} extends JpaRepository<$ENTITY, Long> {
}
  • Click Ok Button

Spring Service

  • On Files tab click on + (Create Template)
  • Enter Name as : “SpringController”, and leave Extension as java
  • In the Content text box add the following content
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#set( $CamelCaseName = "$NAME.substring(0,1).toLowerCase()$NAME.substring(1)" )

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Optional;

import javax.management.RuntimeErrorException;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import org.springframework.stereotype.Service;
import ${PACKAGE_NAME}.repositories.${NAME}Repository;

@Service
@Transactional
@RequiredArgsConstructor
public class ${Name}Service{

	@Autowired
	private ${Name}Repository ${CamelCaseName}Repository;
	
	
	public List<${Name}> getAll${Name}s() {
		return ${CamelCaseName}Repository.findAll();
	}

	
	public void save${Name}(${Name} ${CamelCaseName}) {		
		this.${CamelCaseName}Repository.save(${CamelCaseName});
		
	}

	
	public ${Name} get${Name}ById(long id) {
		Optional<${Name}> optional = ${CamelCaseName}Repository.findById(id);
		${Name} ${CamelCaseName} = null;
		if(optional.isPresent()) {
			${CamelCaseName} = optional.get();
		} else {
			throw new RuntimeException("${CamelCaseName} not found for id:"+id);
		}
		return ${CamelCaseName};
			
	}

	
	public void delete${Name}ById(long id) {
		this.${CamelCaseName}Repository.deleteById(id);		
	}

	
	public Page<${Name}> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
		Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() :
			Sort.by(sortField).descending();
		
		Pageable pageable = PageRequest.of(pageNo -1,pageSize);
		return this.${CamelCaseName}Repository.findAll(pageable);

	}
	
	public static ${NAME} update${NAME}(Long ${CamelCaseName}Id, ${NAME} ${CamelCaseName}) {
	
		${NAME} ${CamelCaseName} = ${CamelCaseName}Repository.findById(${CamelCaseName}Id)
                .orElseThrow(() -> new ResourceNotFoundException("${NAME} not found for this id :: " + ${CamelCaseName}Id));
	
		${CamelCaseName}.setId(${CamelCaseName}Id);
		this.${CamelCaseName}Repository.save(${CamelCaseName})
		return ${CamelCaseName};
	}
	

}
  • Click Ok Button

Spring Static Service

  • On Files tab click on + (Create Template)
  • Enter Name as : “SpringController”, and leave Extension as java
  • In the Content text box add the following content
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#set( $CamelCaseName = "$NAME.substring(0,1).toLowerCase()$NAME.substring(1)" )

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ${PACKAGE_NAME}.repositories.${NAME}Repository;

@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class ${NAME}Service {
    private final ${NAME}Repository ${CamelCaseName}Repository;
	
	
	private static Map ${CamelCaseName}s =  new HashMap<>();
	
	private static Long index=2L;
	
	static {
			${NAME} ${CamelCaseName}01 = new ${NAME}(1L, "${CamelCaseName}1");
			${NAME} ${CamelCaseName}02 = new ${NAME}(2L, "${CamelCaseName}2");
			${CamelCaseName}s.put(1L,${CamelCaseName}01);
			${CamelCaseName}s.put(2L,${CamelCaseName}02);
	};
	
	public static List<${NAME}> getAll${NAME}s() {
		return new ArrayList<>(${CamelCaseName}s.values());
	}
	
	public static ${NAME} get${NAME}Details(Long ${CamelCaseName}Id) {
		return ${CamelCaseName}s.get(${CamelCaseName}Id);
	}
	
	public static ${NAME} add${NAME}(${NAME} ${CamelCaseName}) {
		index +=1;
		${CamelCaseName}.setId(index);
		${CamelCaseName}s.put(index, ${CamelCaseName});
		return ${CamelCaseName};
	}
	
	public static ${NAME} update${NAME}(Long ${CamelCaseName}Id, ${NAME} ${CamelCaseName}) {
		${CamelCaseName}.setId(${CamelCaseName}Id);
		${CamelCaseName}s.put(${CamelCaseName}Id, ${CamelCaseName});
		return ${CamelCaseName};
	}
	
	public static ${NAME} delete${NAME}(Long ${CamelCaseName}Id) {
		return ${CamelCaseName}s.remove(${CamelCaseName}Id);
	}
    
}
  • Click Ok Button

keepass start on Windows startup

I am using keepass for keeping safe my passwords. If you want start keepass on windows startup then follow these steps.

Download and install the latest version of KeePass

After starting the software, untick all lines which start with “lock” in the “Tools / Security”. Save by pressing “OK”.

Select “File / New” to create a new database and choose carefully the location.
Note: It’s not possible to change using key file instead of password for existing databases.

Untick “Master Password”, tick the “Key file / provider”, and select “Create”. Select the location carefully. Then press “OK”.

Press Windows + R, and type the “shell:startup” command without quotes. It will open the startup folder.

Set this below as a location for the shortcut. Replace the database and key file location with yours

“C:\Program Files\KeePass Password Safe 2\KeePass.exe” “C:\PROJECTS\KeePass01.kdbx” -keyfile:”C:\PROJECTS\my-KeePass-db.key” -minimize

How to install certbot ssl certificate on nginx server

I am using centos 7.4 server. you can use following commands for installing ssl certicate.

#cd /etc/nginx/conf.d/

[root@vps147238 conf.d]# cp m.eparinay.com.conf qa.eparinay.com.conf
[root@vps147238 conf.d]# vim qa.eparinay.com.conf
[root@vps147238 conf.d]# sudo certbot --nginx -d qa.eparinay.com -d qa.eparinay.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
Attempting to parse the version 1.23.0 renewal configuration file found at /etc/letsencrypt/renewal/eparinay.com.conf with version 1.11.0 of Certbot. This might not work.
Attempting to parse the version 1.23.0 renewal configuration file found at /etc/letsencrypt/renewal/purabtech.com.conf with version 1.11.0 of Certbot. This might not work.
Attempting to parse the version 1.23.0 renewal configuration file found at /etc/letsencrypt/renewal/www.eparinay.com-0001.conf with version 1.11.0 of Certbot. This might not work.
Requesting a certificate for qa.eparinay.com
Performing the following challenges:
http-01 challenge for qa.eparinay.com
Waiting for verification…
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/conf.d/qa.eparinay.com.conf
Traffic on port 80 already redirecting to ssl in /etc/nginx/conf.d/qa.eparinay.com.conf


Congratulations! You have successfully enabled https://qa.eparinay.com


IMPORTANT NOTES:

  • Congratulations! Your certificate and chain have been saved at:
    /etc/letsencrypt/live/qa.eparinay.com/fullchain.pem
    Your key file has been saved at:
    /etc/letsencrypt/live/qa.eparinay.com/privkey.pem
    Your certificate will expire on 2022-07-31. To obtain a new or
    tweaked version of this certificate in the future, simply run
    certbot again with the "certonly" option. To non-interactively
    renew all of your certificates, run "certbot renew"
  • If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
    Donating to EFF: https://eff.org/donate-le

[root@vps147238 conf.d]# vim qa.eparinay.com.conf
[root@vps147238 conf.d]# service nginx restart
Redirecting to /bin/systemctl restart nginx.service
[root@vps147238 conf.d]#

Solved: nginx Error with Permissions-Policy header: Parse of permissions policy failed because of errors reported by structured header parser

I am using Nginx server and with that, I am using an angular application. The application is running fine but in the console, I got the following error

Error with Permissions-Policy header: Parse of permissions policy failed because of errors reported by structured header parser

To solve this error I added following code in my nginx configuration.

location ^~ / {

    proxy_pass http://127.0.0.1:4200;
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;

}

This solved my issue.

how to install micronaut on windows 10 – java

  1. install wsl on windows

run cmd as command prompt

wsl --install

Above command will enable the required optional components, download the latest Linux kernel, set WSL 2 as your default, and install a Linux distribution for you (Ubuntu by default)

  1. install sdkman – ref taken from https://sdkman.io/install
curl -s "https://beta.sdkman.io" | bash
#sdk selfupdate force
  1. install micronaut with sdkman
#sdk update
#sdk install micronaut

OR

Download the latest binary from Micronaut Website – https://github.com/micronaut-projects/micronaut-starter/releases/download/v3.2.0/micronaut-cli-3.2.0.zip

Extract the binary to appropriate location (For example: C:\PURAB\micronaut-cli-3.2.0)

Create an environment variable MICRONAUT_HOME which points to the installation directory i.e. C:\PURAB\micronaut-cli-3.2.0

Update the PATH environment variable, append %MICRONAUT_HOME%\bin.

Solved: intellij java: package javax.servlet.http does not exist

While running java web project I got following error.

java: package javax.servlet does not exist

Two solve you need to add javax.servlet-3.0.jar file in your project or ide while executing code

you can download jar from this URL:

http://www.java2s.com/Code/Jar/j/Downloadjavaxservlet30jar.htm

Solution:

File -> Project Structure->Libraries

and add javax.servlet-3.0.jar library

Detail can found in this video

java: package javax.servlet.http does not exist

java mariadb executeQuery right syntax to use near ‘? mapping exception

I was using following code

String sql = "select * from user where username=? and password=?";
PreparedStatement ps =connection.prepareStatement(sql);
ps.setString(1, username);

ps.setString(2, password);
ResultSet rs=ps.executeQuery(sql);
while (rs.next()) {
user= new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setEmail(rs.getString(3));
user.setQualification(rs.getString(5));
user.setRole(rs.getString(6));
}

I got following eror:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and password=?' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1200)

Solution and what is wrong?

for this line ResultSet rs=ps.executeQuery(sql); I do not need to add SQL query there.

I removed SQL keyword it code started working fine…

String sql = "select * from user where username=? and password=?";
PreparedStatement ps =connection.prepareStatement(sql);

ps.setString(1, username);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();

SSL certificate integration in Spring boot Project

SSL certificate integration

SSL certificate setting applied in application.properties file To generate self signed SSL certificate use following command:

cd src/main/resources
keytool -genkeypair -alias local_ssl -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore local-ssl.p12 -validity 365 -ext san=dns:localhost

Put following code into application.properties file

spring.application.name=ssl-certificate
server.port=8443
#server.port=8080
server.ssl.enabled: true
server.ssl.key-alias: local_ssl
server.ssl.key-store: classpath:local-ssl.p12
server.ssl.key-store-type: PKCS12
server.ssl.key-password: 12345678
server.ssl.key-store-password: 12345678

Open this URL:
https://localhost:8443/

For production use following command and use p12 file in application Convert .crt to .p12

openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt

Where server.key , is the server key . server.crt is cert file from CA or self sign

you can find source code here:

https://github.com/purab/ssl-certificate-spring-boot