Debian Server Useful Commands (Dynamic Post, updated very frequently, for notes use)

For System Restart: sudo reboot

============================================

For Using 7z:

To install 7z-full:

sudo apt-get update
sudo apt-get install p7zip-full

To add a files file to 7z archive:

7z a <7z-archive-file-name>.7z {files to be archived}

e.g 7z a Apache-NetBeans-12.0-bin-windows-x64.exe.7z Apache-NetBeans-12.0-bin-windows-x64.exe


==============================================

To send a running process in background in terminal

Ctrl+z
bg

Now to bring back that process in forground

fg

To start a command directly in background

Type command &
e.g 7z a Apache-NetBeans-12.0-bin-windows-x64.exe.7z Apache-NetBeans-12.0-bin-windows-x64.exe &

To view processes running in background

jobs


How to do settings for Mobile Device Compatibility in Blogger / Fix Blogger Issue "Viewport not set to "device-width"

Steps:

1> Go to blogger.com (login to your account)
2> Select themes -> There in MyThemes, in click three dots
3> Click Mobile Device Settings
4> In <Do you want to show Desktop or Mobile theme on mobile devices?>, choose Mobile Device
5> In configure Mobile View, select your appropriate Theme Category of your choice -> Then choose desired theme
6> Thats all, Your Blogger is now compatible in Mobile Devices and Your Shouldn't Get any Error Message from Google Search Console as below:

Top Issues

The following issues were found on your site:

Viewport not set to "device-width"

Text too small to read

Clickable elements too close together

How to add your domain / url / blog to Google Search Engine or console

Hey, I would like to discuss how to add your domain / url / blog to Google Search Engine or console:

2> verify your domain/url/blog that you are actual owner of it
3> in inpect your url box in the top centre of page, add your url, and press enter
4> then you can press <Test Live Url> button to check if URL is accessable in internet
5> you can then press <Request Indexing> link to get your URL indexed in google search engine
6> upon submittion of submitting request, your URL will be verified to exist, and queued in Google Search Engine indexing task (i.e crawl queue) which may take from sometime to somedays.
7> After your URL is indexed in Google Search Engine, more your site gets visited, more the chance that it will appare in Google Search.
8> For enhanced search you can also try paid service of Google Search

Series: My Database Concepts - JDBC vs JPA / Hibernate

Lot of times questions arise in mind that what to use pure JDBC or JPA/Hibernate.

Well, if performance is compared JDBC is much faster and uses less memory than Hibernate.

But if you plan to work safely, in a less error prone manner while writing Database code, you will need to you Hibernate.

So, finally in my opinion, if you are confidence enough that if you can write JDBC codes properly, have good knowledge of JDBC, you should use JDBC.
Also, if you think you will be able to learn SQL / JDBC properly if you don't know yet, and want to create some JAVA Database project, in this case also you can use JDBC.

But if you don't want to waste too much of time in learning JDBC and writing proper codes and spend time upon testing those codes, use JPA/ Hibernate. But in this case you will need few byes of memory extra, and also performance will be downgraded by a bit in comparison with JDBC.

Note: when these points are considered, following points are important to note:
1> In JDBC you can use DBCP or any other .jar file for connection pooling.
2> You are always using prepared statements / callable statements while using JDBC.
3> When using JPA / Hibernate, it also converts JPQL / HQL to relevant SQL codes for executing SQL statements.

Draft of Java code to save NSE Historical Data in file System instead of Database, Just For TRY! Not yet tested at all

package entitity;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Stream;

public class HD implements Serializable {
public static void main(String args[]) {
String csvFilePath = "D:\\nseEquityHistoricalDataCsv\\20200116\\"
+ "Quote-Equity-INFRATEL-EQ-14-03-2020-to-14-06-2020.csv";
String dbPath = "D:\\javaWebServers\\ApacheTomEE\\nseeq\\";
String hdTablePath = dbPath + "hd.tb", hdLogPath = dbPath + "hd.lg";

try (Stream<String> stream1 = Files.lines(Paths.get(csvFilePath));
Stream<String> stream2 = Files.lines(Paths.get(csvFilePath))) {
String[] headerLineArr = stream1.findFirst().get().toString().replaceAll("\"", "").split(",");
for (Integer i = 0; i < headerLineArr.length; i++) {
headerLineArr[i] = headerLineArr[i].trim();
}
stream2.skip(1).forEach(e -> {
HD hd = new HD("INFRATEL", headerLineArr, e.replaceAll("\"", ""));
System.out.println(hd.toString());
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

LocalDate d;
String s;
String series;
Double pc, o, h, l, ltp, c;
Long v;
Double turnover;
Double _52WH, _52WL;
Long noOfTrades;
Boolean delFlag = false;

private static final DateTimeFormatter dft = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
private static final Integer logFileHeapSize = 512;

public HD(String s, String[] headerLineArr, String line) {
String[] lineArr = line.replaceAll("\"\"", "").split(",");
HashMap<String, String> row = new HashMap<String, String>();
for (Integer i = 0; i < headerLineArr.length; i++) {
row.put(headerLineArr[i], lineArr[i].trim());
}
// this.d=LocalDate.parse(row.get("Date"),dft);
this.d = LocalDate.parse(lineArr[0], dft);
this.s = s;
this.series = row.get("series");
this.pc = Double.valueOf(row.get("PREV. CLOSE"));
this.o = Double.valueOf(row.get("OPEN"));
this.h = Double.valueOf(row.get("HIGH"));
this.l = Double.valueOf(row.get("LOW"));
this.ltp = Double.valueOf(row.get("ltp"));
this.c = Double.valueOf(row.get("close"));
this.v = Long.valueOf(row.get("VOLUME"));
this.turnover = Double.valueOf(row.get("VALUE"));
this._52WH = Double.valueOf(row.get("52W H"));
this._52WL = Double.valueOf(row.get("52W L"));
this.noOfTrades = Long.valueOf(row.get("No of trades"));
}
    
        //default constructor and other constructers omitted for brevity
// getters and setters omitted for brevity

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((d == null) ? 0 : d.hashCode());
result = prime * result + ((s == null) ? 0 : s.hashCode());
result = prime * result + ((series == null) ? 0 : series.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HD other = (HD) obj;
if (d == null) {
if (other.d != null)
return false;
} else if (!d.equals(other.d))
return false;
if (s == null) {
if (other.s != null)
return false;
} else if (!s.equals(other.s))
return false;
if (series == null) {
if (other.series != null)
return false;
} else if (!series.equals(other.series))
return false;
return true;
}

@Override
public String toString() {
// omitted for brevity
}

public static void deFragmentTable(String filePath) throws IOException, ClassNotFoundException {
// set names of logFile and tmp file
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
if (Files.size(Paths.get(logFilePath)) < logFileHeapSize * 1000000) {
return;
}
String tmpPath = filePath.subSequence(0, filePath.length() - 2) + "tmp";
// read form tb file in a set
FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream ois = new ObjectInputStream(fis);
HashSet<HD> set = (HashSet<HD>) ois.readObject();
ois.close();
// update set from log file to latest values
ois = new ObjectInputStream(new FileInputStream(logFilePath));
while (true) {
try {
HD obj = (HD) ois.readObject();
set.remove(obj);
set.add(obj);
} catch (EOFException e) {
break;
}
}
// write set to tmp file
File fileTmp = new File(tmpPath, "w");
fileTmp.createNewFile();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileTmp))) {
oos.writeObject(set);
}
// deletes old table file and log file, them rename tmp file to table file
Files.delete(Paths.get(filePath));
Files.delete(Paths.get(logFilePath));
new File(tmpPath).renameTo(new File(filePath));
}
public static void insert(String filePath, HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object don't exists in filePath, write object in file path
if (prevObj==null) {
writeObjectInFilePath(filePath, prevObj);
} else {
// if object in deleated status in logPath, write object in logPath
if (prevObj.getDelFlag()) {
writeObjectInLogPath(filePath, prevObj);
} else {
// if object not in deleated status in filePath, throw onject already exists
// exception
throw new Exception("Object already exists");
}
}
}

public static void update(String filePath, HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object exists and not in deleated state
if(prevObj!=null && !prevObj.getDelFlag()) {
writeObjectInLogPath(filePath, prevObj);
}else {
// throw object not exists exception
throw new Exception("object not available for update as it don't exists");
}
}
public static void delete(String filePath,HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object exists and not in deleated state
if(prevObj!=null && !prevObj.getDelFlag()) {
prevObj.setDelFlag(true);
writeObjectInLogPath(filePath, prevObj);
}else {
// throw object not exists exception
throw new Exception("object not available for deletion as it don't exists");
}
}

public static HD findObjectInFilePath(String filePath, HD obj) throws IOException, ClassNotFoundException {
HD prevObj = null;
// check if object already exists in filePath
Boolean objectFoundInFilePath = false;
File file = new File(filePath);
file.createNewFile();
ObjectInputStream isFilePath = new ObjectInputStream(new FileInputStream(file));
while (!objectFoundInFilePath) {
try {
HD obj2 = (HD) isFilePath.readObject();
if (obj.equals(obj2)) {
prevObj = obj2;
objectFoundInFilePath = true;
}
} catch (EOFException e) {
break;
}
}
isFilePath.close();
return prevObj;
}

public static void updateLatestObjectInLogPath(String filePath, HD prevObj)
throws IOException, ClassNotFoundException {
// if object exists in filePath, get this final object in logPath
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
File logFile = new File(logFilePath);
logFile.createNewFile();
ObjectInputStream isLogPath = new ObjectInputStream(new FileInputStream(logFilePath));
while (true) {
try {
HD obj2 = (HD) isLogPath.readObject();
if (prevObj.equals(obj2)) {
prevObj = obj2;
}
} catch (EOFException e) {
break;
}
}
isLogPath.close();
}

public static HD getLatestPrevObject(String filePath, HD obj) throws ClassNotFoundException, IOException {
HD prevObj = findObjectInFilePath(filePath, obj);
if (prevObj == null) {
return null;
} else {
updateLatestObjectInLogPath(filePath, prevObj);
return prevObj;
}
}
public static void writeObjectInFilePath(String filePath,HD obj) throws FileNotFoundException, IOException {
File file=new File(filePath);
ObjectOutputStream osFilePath = new ObjectOutputStream(new FileOutputStream(file));
osFilePath.writeObject(obj);
osFilePath.close();
}
public static void writeObjectInLogPath(String filePath,HD obj) throws IOException, ClassNotFoundException {
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
ObjectOutputStream osLogPath = new ObjectOutputStream(new FileOutputStream(logFilePath));
osLogPath.writeObject(obj);
osLogPath.close();
deFragmentTable(filePath);
}
}

How to Add Free SSL Certificate from LetsEncrypt via Certbot in your Java Tomcat / Tomee website?

Assumptions:
1. You are using Linux / Debian Server
2. You are using Compute Engine
3. You are using Google Domains
4. Set $JAVA_HOME=<path to your java base directory>
5. Set $CATALINA_BASE=<path to your Tomcat / Tomee base directory>

-------------------------------------------------------------------------------------

Procedure:
2. In selection option, 
    a) My website running on <none of the above>
    b) Operating system using <as per your operating system>, <Debian 10 in my case>
3. Type command sudo apt-get install certbot
4. Type command sudo certbot certonly --standalone
5. Your certificate will be downloaded and installed in /etc/letsencrypt folder

6. Your certificate files are as follows:
/etc/letsencrypt/live/<your domain name>/cert.pem
/etc/letsencrypt/live/<your domain name>/chain.pem
/etc/letsencrypt/live/<your domain name>/fullchain.pem
/etc/letsencrypt/live/<your domain name>/privkey.pem

7. Change permissions of these file if needed as it have default root access only so that Tomcat/ Tomee user can acces them

8. Type command sudo nano $CATALINA_BASE/conf/server.xml

9. Provide following lines in server.xml
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="/etc/letsencrypt/live/<your domain name>/privkey.pem"
                         certificateFile="/etc/letsencrypt/live/<your domain name>/cert.pem"
                         certificateChainFile="/etc/letsencrypt/live/<your domain name>/chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>

10.  // restart tomc(at/ee) server
11. Check your working https:// website in your domain name

Work Done

How to Add Free SSL Certificate from ZeroSSL int your Java Tomcat / Tomee website?

Assumptions:
1. You are using Linux / Debian Server
2. You are using Compute Engine
3. You are using Google Domains

----------------------------------------------------------------------
Procedure:
1. Set $JAVA_HOME=<path to your java base directory>
2. Set $CATALINA_BASE=<path to your Tomcat / Tomee base directory>

3. Type command: $JAVA_HOME/bin/keytool -genkey -alias <server> -keyalg RSA -keysize <2048> -keystore <path to your keystore file.jks>
 Note: When asked for your first and last name, give your website domain name like www.mohitkrgupta.dev

4. Type command: $JAVA_HOME/bin/keytool -certreq -alias <server> -file <csr.txt> -keystore <path to your keystore file.jks>

This will generate csr.txt key file to be submitted to Certifying Authority (ZeroSSL in this case)

5. Visit ZeroSSL site and copy-pase content of csr.txt and follow processes as mentioned in website to get your SSL keys
6. Your SSL key document will be available from there in .zip format, download and unzip it.
7. It will contain following files:
    certificate.crt, and ca_bundle.crt.
8. Type Command: openssl crl2pkcs7 -nocrl -certfile <certificate.crt> -out <certificate.p7b> -certfile <ca_bundle.crt>
//(you will get certificate.p7b file in this way)
9. Type Command: JAVA_HOME/bin/keytool -import -alias <server> -file <certificate.p7b> -keystore <path to your keystore file.jks>
10. Type Command: sudo nano $CATALINA_BASE/conf/server.xml
11. Provide following lines in server.xml

<Connector port="443" maxHttpHeaderSize="8192" maxThreads="100"
           minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" disableUploadTimeout="true"
           acceptCount="100" scheme="https" secure="true"
           SSLEnabled="true" clientAuth="false"
           sslProtocol="TLS" keyAlias="server"
           keystoreFile="</home/newmkg/mohitkrgupta.dev.jks>"
           keystorePass="<*************>" />

12. // restart tomc(at/ee) server
13. Check your working https:// website in your domain name

Work Done

How to Add Self-Signed SSL Certificate in Java Apache Tomee / Tomcat Server and then launch your site in Compute Engine?

Assumptions:
  1. You already have Linux / Debian Compute Engine installed in your Google Cloud Plateform (GCP) with Java installed in the system.
  2. You have Downloaded and Installed your required version of Tomee / Tomcat Server and installed this in your Compute Engine
  3. You have an active external IP Address for your Compute Engine

Prodecure:
1. Set $JAVA_HOME path as your java home directory.
2. Set $CATALINA_BASE path as your Tomee / Tomcat server base directory
3. Type Command in terminal: $JAVA_HOME/bin/keytool -genkey -alias <tomcat> -keyalg RSA
Enter details as asked for like password, your details, etc
4. Type Command: sudo nano $CATALINA_BASE/conf/server.xml
Add following line in your server
<!-- Define an SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector
           protocol="org.apache.coyote.http11.Http11NioProtocol"
           port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="${user.home}/.keystore" keystorePass="changeit"
           clientAuth="false" sslProtocol="TLS"/>
5. Activate TCP Port Number 8443 in your Compute Engine
6. Restart Tomee / Tomcat Server
7. Type command: curl https://localhost:8443 
To see the outcome
Or visit in Browser <Your Compute Engine IP Address:8443> 
8. Now, in browser, since in https:// it is a self signed certificate, it will show unsafe, back to safety, but you can do proceed with unsafe.
Note: This is more safer than http:// but is giving warning because certificate is my self signed generated using keytool in java bin folder and is not yet certified by any Certifying Autority, hence warning

Work Done

Regarding site Free Browser Tool (https://free-browser-tools.mohitkrgupta.dev) (discussion with google search AI)

Various discussions with Google Search AI regarding site  Free Browser Tool are as below: site free-browser-tools.mohitkrgupta.dev what doe...