Tuesday, September 22, 2026

Decoding Unicode Texts

Web & URL Reserved Characters
Hex Code Unicode Escape Character Usage
0020\u0020 Space
0022\u0022"Double quote
0023\u0023#Hash / Fragment identifier
0025\u0025%Percent sign
0026\u0026&Ampersand (URL parameter joiner)
002B\u002B+Plus sign
002F\u002F/Forward slash
003A\u003a:Colon
003B\u003b;Semicolon
003C\u003c<Less-than sign
003D\u003d=Equals sign (Key-value / Base64)
003E\u003e>Greater-than sign
003F\u003f?Question mark
0040\u0040@At sign
Punctuation & Enclosures
Hex Code Unicode Escape Character Usage
0021\u0021!Exclamation mark
0024\u0024$Dollar sign
0027\u0027'Single quote
0028\u0028(Left parenthesis
0029\u0029)Right parenthesis
002A\u002a*Asterisk
002C\u002c,Comma
005B\u005b[Left square bracket
005C\u005c\Backslash
005D\u005d]Right square bracket
005E\u005e^Caret
0060\u0060`Backtick
007B\u007b{Left curly brace
007C\u007c|Vertical bar / Pipe
007D\u007d}Right curly brace
007E\u007e~Tilde
Control & Whitespace Characters
Hex Code Unicode Escape Character Description
0009\u0009\tHorizontal Tab
000A\u000a\nLine Feed (Newline)
000D\u000d\rCarriage Return
00A0\u00a0 Non-breaking space (NBSP)

Monday, January 3, 2022

CPU Memory Utilization Commands Ubuntu


CPU Commands in Linux:

top  ==> Press c
top  ==> Press shift+m

Show Processes in Descending order of Memory in Linux:
ps aux | head -1; ps aux | sort -rnk 4 | head

ps -eo pid,ppid,%mem,%cpu,cmd --sort=-%cpu | head



Show Processes in Descending order of CPU in Linux:
ps aux | head -1; ps aux | sort -rnk 3 | head

ps -eo pid,ppid,%mem,%cpu,cmd --sort=-%mem | head

Monday, June 28, 2021

Types of HTTP Clients

Postman:
        https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push
        Headers:
        X-Caller-Id:IN_XX_QCO2
        X-Caller-Auth-Token:3hS4qU8rM3
        Content-Type:application/json
        X-User-Mobile:9916473300
        {
            "ticker": "Test PN",
            "title": "Money Received",
            "detail": "100 Received",
            "time": "20210628",
            "timeToLive" : 120
        }

OKHttp:
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n    \"ticker\": \"Test PN\",\n    \"title\": \"Money Received\",\n    \"detail\": \"100 Received\",\n    \"time\": \"20210628\",\n    \"timeToLive\" : 120\n}");
        Request request = new Request.Builder()
          .url("https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push")
          .post(body)
          .addHeader("x-caller-id", "IN_MW_QCO2")
          .addHeader("x-caller-auth-token", "3hS4qU8rM3")
          .addHeader("content-type", "application/json")
          .addHeader("x-user-mobile", "9916473353")
          .addHeader("cache-control", "no-cache")
          .addHeader("postman-token", "1629e893-9d51-0433-22a9-31fc9ef8d408")
          .build();
        Response response = client.newCall(request).execute();


java.net.Http
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://face-detection6.p.rapidapi.com/img/face-age-gender"))
                .header("content-type", "application/json")
                .header("x-rapidapi-host", "face-detection6.p.rapidapi.com")
                .method("POST", HttpRequest.BodyPublishers.ofString("{\r\n    \"url\": \"https://inferdo.com/img/face-3.jpg\",\r\n    \"accuracy_boost\": 3\r\n}"))
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());

AsyncHttp
        AsyncHttpClient client = new DefaultAsyncHttpClient();
        client.prepare("POST", "https://face-detection6.p.rapidapi.com/img/face-age-gender")
            .setHeader("content-type", "application/json")
            .setHeader("x-rapidapi-host", "face-detection6.p.rapidapi.com")
            .setBody("{\r
            \"url\": \"https://inferdo.com/img/face-3.jpg\",\r
            \"accuracy_boost\": 3\r
        }")
            .execute()
            .toCompletableFuture()
            .thenAccept(System.out::println)
            .join();
        client.close();
    
NodeJS Request:
        var request = require("request");
        var options = { method: 'POST',
          url: 'https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push',
          headers: 
           { 'postman-token': 'f3a011c2-63e5-746e-c9ee-136059cc0b7e',
             'cache-control': 'no-cache',
             'x-user-mobile': '9916473353',
             'content-type': 'application/json',
             'x-caller-auth-token': '3hS4qU8rM3',
             'x-caller-id': 'IN_MW_QCO2' },
          body: 
           { ticker: 'Test PN',
             title: 'Money Received',
             detail: '100 Received',
             time: '20210628',
             timeToLive: 120 },
          json: true };
        request(options, function (error, response, body) {
          if (error) throw new Error(error);
          console.log(body);
        });

NodeJS Native:
        var http = require("https");
        var options = {
          "method": "POST",
          "hostname": "127.0.0.1",
          "port": "8443",
          "path": "/internal/in/user/alert/6019/generic/push",
          "headers": {
            "x-caller-id": "IN_MW_QCO2",
            "x-caller-auth-token": "3hS4qU8rM3",
            "content-type": "application/json",
            "x-user-mobile": "9916473353",
            "cache-control": "no-cache",
            "postman-token": "657200ee-90d5-b612-856e-493477f98309"
          }
        };
        var req = http.request(options, function (res) {
          var chunks = [];
          res.on("data", function (chunk) {
            chunks.push(chunk);
          });
          res.on("end", function () {
            var body = Buffer.concat(chunks);
            console.log(body.toString());
          });
        });
        req.write(JSON.stringify({ ticker: 'Test PN',
          title: 'Money Received',
          detail: '100 Received',
          time: '20210628',
          timeToLive: 120 }));
        req.end();


Python http
        import http.client
        conn = http.client.HTTPSConnection("127.0.0.1:8443")
        payload = "{\n    \"ticker\": \"Test PN\",\n    \"title\": \"Money Received\",\n    \"detail\": \"100 Received\",\n    \"time\": \"20210628\",\n    \"timeToLive\" : 120\n}"
        headers = {
            'x-caller-id': "IN_MW_QCO2",
            'x-caller-auth-token': "3hS4qU8rM3",
            'content-type': "application/json",
            'x-user-mobile': "9916473353",
            'cache-control': "no-cache",
            'postman-token': "68851f89-d87e-7ccd-ee64-130e0cf519fe"
            }
        conn.request("POST", "/internal/in/user/alert/6019/generic/push", payload, headers)
        res = conn.getresponse()
        data = res.read()
        print(data.decode("utf-8"))


wget:
        wget --quiet \
          --method POST \
          --header 'x-caller-id: IN_MW_QCO2' \
          --header 'x-caller-auth-token: 3hS4qU8rM3' \
          --header 'content-type: application/json' \
          --header 'x-user-mobile: 9916473353' \
          --header 'cache-control: no-cache' \
          --header 'postman-token: 1650c649-5ae2-09ed-b6f7-39fef6bcef9c' \
          --body-data '{\n    "ticker": "Test PN",\n    "title": "Money Received",\n    "detail": "100 Received",\n    "time": "20210628",\n    "timeToLive" : 120\n}' \
          --output-document \
          - https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push
  

curl 
curl is a command line tool to transfer data to or from a server, using any of the supported protocols (HTTP, FTP, IMAP, POP3, SCP, SFTP, SMTP, TFTP, TELNET, LDAP or FILE). 
curl is powered by Libcurl. This tool is preferred for automation, since it is designed to work without user interaction. curl can transfer multiple file at once.

	curl https://www.geeksforgeeks.org
	curl http://site.{one, two, three}.com      URLs with multiple sequence
	curl ftp://ftp.example.com/file[1-20].jpeg

curl displays a progress meter during use to indicate the transfer rate, amount of data transferred, time left etc.
	curl -# -o ftp://ftp.example.com/file.zip
	curl --silent ftp://ftp.example.com/file.zip

curl -o hello.zip ftp://speedtest.tele2.net/1MB.zip    -o : saves the downloaded file on the local machine with the name provided in the parameters.

curl -O ftp://speedtest.tele2.net/1MB.zip        -O : This option downloads the file and saves it with the same name as in the URL.

curl -C - -O ftp://speedtest.tele2.net/1MB.zip   -C – : This option resumes download which has been stopped due to some reason. This is useful when downloading large files and was interrupted.

curl --limit-rate 1000K -O ftp://speedtest.tele2.net/1MB.zip   
–limit-rate : This option limits the upper bound of the rate of data transfer and keeps it around the given value in bytes.

curl -u demo:password -O ftp://test.rebex.net/readme.txt   
-u : curl also provides options to download files from user authenticated FTP servers.

curl -u {username}:{password} -T {filename} {FTP_Location}  
-T : This option helps to upload a file to the FTP server. If you want to append a already existing FTP file you can use the -a or –append option.


curl https://www.geeksforgeeks.org > log.html --libcurl code.c   
–libcurl :This option is very useful from a developers perspective. If this option is appended to any cURL command, it outputs the C source code 
that uses libcurl for the specified option. It is the code similar to the command line implementation. The above example downloads the HTML and 
saves it into log.html and the code in code.c file. 

curl -u [user]:[password] -x [proxy_name]:[port] [URL...]        -x, –proxy : curl also lets us use a proxy to access the URL.

Sending mail : As curl can transfer data over different protocols, including SMTP, we can use curl to send mails.
curl –url [SMTP URL] –mail-from [sender_mail] –mail-rcpt [receiver_mail] -n –ssl-reqd -u {email}:{password} -T [Mail text file]


curl --request POST \
          --url https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push \
          --header 'cache-control: no-cache' \
          --header 'content-type: application/json' \
          --header 'postman-token: ee5f1533-7177-a53c-5710-e209a4964d8e' \
          --header 'x-caller-auth-token: 3hS4qU8rM3' \
          --header 'x-caller-id: IN_MW_QCO2' \
          --header 'x-user-mobile: 9916473353' \
          --data '{\n    "ticker": "Test PN",\n    "title": "Money Received",\n    "detail": "100 Received",\n    "time": "20210628",\n    "timeToLive" : 120\n}'

curl -X POST \
          https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push \
          -H 'cache-control: no-cache' \
          -H 'content-type: application/json' \
          -H 'postman-token: 10066716-e451-e635-bc32-50582471623a' \
          -H 'x-caller-auth-token: 3hS4qU8rM3' \
          -H 'x-caller-id: IN_MW_QCO2' \
          -H 'x-user-mobile: 9916473353' \
          -d '{
            "ticker": "Test PN",
            "title": "Money Received",
            "detail": "100 Received",
            "time": "20210628",
            "timeToLive" : 120
        }'

Java Script: Ajax
        var settings = {
          "async": true,
          "crossDomain": true,
          "url": "https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push",
          "method": "POST",
          "headers": {
            "x-caller-id": "IN_MW_QCO2",
            "x-caller-auth-token": "3hS4qU8rM3",
            "content-type": "application/json",
            "x-user-mobile": "9916473353",
            "cache-control": "no-cache",
            "postman-token": "9e0d19ed-6525-0fa3-e978-f34823c861a4"
          },
          "processData": false,
          "data": "{\n    \"ticker\": \"Test PN\",\n    \"title\": \"Money Received\",\n    \"detail\": \"100 Received\",\n    \"time\": \"20210628\",\n    \"timeToLive\" : 120\n}"
        }
        $.ajax(settings).done(function (response) {
          console.log(response);
        });

PHTP:
        <?php
        $request = new HttpRequest();
        $request->setUrl('https://127.0.0.1:8443/internal/in/user/alert/6019/generic/push');
        $request->setMethod(HTTP_METH_POST);
        $request->setHeaders(array(
          'postman-token' => '5c0297c0-6f96-3731-d7b6-a9bc9869ce98',
          'cache-control' => 'no-cache',
          'x-user-mobile' => '9916473353',
          'content-type' => 'application/json',
          'x-caller-auth-token' => '3hS4qU8rM3',
          'x-caller-id' => 'IN_MW_QCO2'
        ));
        $request->setBody('{
            "ticker": "Test PN",
            "title": "Money Received",
            "detail": "100 Received",
            "time": "20210628",
            "timeToLive" : 120
        }');
        try {
          $response = $request->send();

          echo $response->getBody();
        } catch (HttpException $ex) {
          echo $ex;
        }

Friday, February 19, 2021

Windows commands to start and stop multiple processes

Windows Command Prompt:

Open multiple command prompt in one go:
    start cmd DIRECTORY1
    start cmd DIRECTORY2

Start multiple processes in one go:
    start java -jar DIRECTORY1\target\zipkin-service-1-0.0.1-SNAPSHOT.jar
    start java -jar DIRECTORY2\target\zipkin-service-2-0.0.1-SNAPSHOT.jar

Find and Kill multiple processes in one go (8081, 8082 are port numbers where server is running):
    FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8081') DO TaskKill.exe /PID %%P
    FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8082') DO TaskKill.exe /PID %%P

Friday, September 25, 2020

Sample Dummy Queries for Testing

use temp;
CREATE TABLE IF NOT EXISTS BOOKS (
  BOOK_ID INT(5) NOT NULL AUTO_INCREMENT,
  CATEGORY VARCHAR(30) NOT NULL,
  TITLE VARCHAR(80) NOT NULL,
  DESCRIPTIONS VARCHAR(200) NOT NULL,
  PRIMARY KEY (BOOK_ID)
);

INSERT INTO BOOKS (BOOK_ID, CATEGORY, TITLE, DESCRIPTIONS) VALUES(1, 'Java', 'Concurrency in Practice', 'Java Concurrency Book');
INSERT INTO BOOKS (BOOK_ID, CATEGORY, TITLE, DESCRIPTIONS) VALUES(2, 'Hibernate', 'Hibernate In Action', 'Hibernate In Action Learning');
INSERT INTO BOOKS (BOOK_ID, CATEGORY, TITLE, DESCRIPTIONS) VALUES(3, 'Spring', 'Spring In Action', 'Spring In Action Learning'); 
INSERT INTO BOOKS (BOOK_ID, CATEGORY, TITLE, DESCRIPTIONS) VALUES(4, 'C','Let Us C','C Programming Book');
INSERT INTO BOOKS (BOOK_ID, CATEGORY, TITLE, DESCRIPTIONS) VALUES(5, 'Java','Java for Advanced Learners', 'Java for Advanced Learners by Deepak Modi');
commit;
select * from BOOKS;

use temp;
CREATE TABLE DEPARTMENT(
    DID INTEGER(3) PRIMARY KEY, 
    DNAME VARCHAR(25)
);
CREATE TABLE JOB(
    JOBID INTEGER(3) PRIMARY KEY, 
    DESIGNATION VARCHAR(25)
);

CREATE TABLE EMPLOYEE(
    EID INTEGER(3) PRIMARY KEY, 
    ENAME VARCHAR(25), 
    SALARY INTEGER(8), 
    JOBID INTEGER(3) REFERENCES JOB(JOBID), 
    DID INTEGER(3) REFERENCES DEPARTMENT(DID) ON DELETE SET NULL
);

CREATE TABLE PROJECTS(
    PID INTEGER(3) PRIMARY KEY, 
    TITLE VARCHAR(25), 
    EID INTEGER(3) REFERENCES EMPLOYEE(EID) ON DELETE SET NULL
);

insert into DEPARTMENT values(1, 'MobilePayments');
insert into DEPARTMENT values(2, 'FRM');
insert into DEPARTMENT values(3, '3DS');
insert into DEPARTMENT values(4, 'OPERATIONS');
insert into DEPARTMENT values(5, 'BIZOPS');
insert into DEPARTMENT values(6, 'L1');
insert into DEPARTMENT values(7, 'DBA');
insert into DEPARTMENT values(8, 'PSE');

insert into JOB values(1, 'Developer');
insert into JOB values(2, 'Tester');
insert into JOB values(3, 'ProductionSupport');
insert into JOB values(4, 'Finance');
insert into JOB values(5, 'Banking');
insert into JOB values(6, 'Sales');
insert into JOB values(7, 'Marketing');
insert into JOB values(8, 'PSE');
insert into JOB values(9, 'REPORTS');

insert into EMPLOYEE values(1, 'Deepak Kumar Modi', 125000, 1, 1);
insert into EMPLOYEE values(2, 'Ajay Mahto', 80000, 1, 1);
insert into EMPLOYEE values(3, 'Ajay Ramu', 100000, 9, 4);
insert into EMPLOYEE values(4, 'Navaneeth Kumar', 130000, 9, 5);
insert into EMPLOYEE values(6, 'Manjunath S', 85000, 9, 5);
insert into EMPLOYEE values(7, 'Abhilash', 95000, 9, 4);
insert into EMPLOYEE values(8, 'Pavan K', 145000, 1, 1);
insert into EMPLOYEE values(9, 'Imran Khan', 75000, 8, 3);

insert into PROJECTS values(1, 'PayZapp_Project', 1);
insert into PROJECTS values(2, 'PayApt_Project', 2);
insert into PROJECTS values(3, 'Management_Project', 1);
insert into PROJECTS values(4, 'Report_Sharing_Project', 7);
insert into PROJECTS values(5, 'Prod_Support_Project', 9);

select * from temp.DEPARTMENT;
select * from temp.JOB;
select * from temp.EMPLOYEE;
select * from temp.PROJECTS;

Tuesday, September 8, 2020

ConnectTimeout ReadTimeout WriteTimeout

Message Hash Generation Code: public class HashGenerator { public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest messageDigest = java.security.MessageDigest.getInstance("SHA-256"); String raw="IN656912225942"; String x = new String(Base64.encode(messageDigest.digest(raw.getBytes("UTF-8")))); System.out.println(raw+" "+x); } } ConnectTimeout: 5 Seconds (Finding Host, who is the server) ReadTimeout: 5 Seconds (Reading the value from Server, Server is processing) WriteTimeout: 5 Seconds (Posting the request to Server like posting JSON, File Upload, depends on bandwidth)

Thursday, May 28, 2020

Split Column Data from Mysql


DROP TABLE W2A_FEE;

CREATE TABLE W2A_FEE (CSV_VALUE VARCHAR(100));

INSERT INTO W2A_FEE VALUES('2.85,9,9');

INSERT INTO W2A_FEE VALUES('2.00,9,9');

INSERT INTO W2A_FEE VALUES('2.00,9,9');

INSERT INTO W2A_FEE VALUES('3.5,9,9');

 

SELECT CSV_VALUE FROM W2A_FEE;

 

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CSV_VALUE, ',', 1), ',', -1) AS Fee,
       SUBSTRING_INDEX(SUBSTRING_INDEX(CSV_VALUE, ',', 2), ',', -1) AS CGST,
       SUBSTRING_INDEX(SUBSTRING_INDEX(CSV_VALUE, ',', 3), ',', -1) AS SGST
FROM   W2A_FEE;

Wednesday, February 27, 2019

Nginx Key and Certificate Creation

SSL Key and Certificate creation in Nginx:

Ubuntu@Server:/etc/nginx$ mkdir ssl
Ubuntu@Server:/etc/nginx$ cd ssl

//Below commands are explained at the end of this....

Ubuntu@Server:/etc/nginx/ssl$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/dmodi_nginx.key -out /etc/nginx/ssl/dmodi_nginx.crt
[sudo] password for wibmoapp:
    Generating a 2048 bit RSA private key
    ...................................+++
    .....................................+++
    writing new private key to '/etc/nginx/ssl/dmodi_nginx.key'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [AU]:IN
    State or Province Name (full name) [Some-State]:Karnataka
    Locality Name (eg, city) []:Bengaluru
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Wibmo
    Organizational Unit Name (eg, section) []:Payzapp Team
    Common Name (e.g. server FQDN or YOUR name) []:www.deepakmodi.com
    Email Address []:deepak.modi@wibmo.com
    
Ubuntu@Server:/etc/nginx/ssl$ ls -lrth
total 8.0K
-rw-r----- 1 root root 1.7K Feb 27 18:53 dmodi_nginx.key
-rw-r----- 1 root root 1.5K Feb 27 18:53 dmodi_nginx.crt
Ubuntu@Server:/etc/nginx/ssl$


Now modify the nginx.conf file:
server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        listen 443 ssl;

        root /usr/share/nginx/html;
        index index.html index.htm;

        server_name your_domain.com;
        ssl_certificate /etc/nginx/ssl/dmodi_nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/dmodi_nginx.key;

        location / {
                try_files $uri $uri/ =404;
        }
}

Restart the Nginx:
service nginx restart

Now Try:
http://server_domain_or_IP
and
https://server_domain_or_IP

Command Explanation:
openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.

req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The "X.509" 
    is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. 
    We want to create a new X.509 cert, so we are using this subcommand.
    
-x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed 
    certificate instead of generating a certificate signing request, as would normally happen.
    
-nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Nginx to be 
        able to read the file, without user intervention, when the server starts up. A passphrase would prevent 
        this from happening because we would have to enter it after every restart.
        
-days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.

-newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did 
    not create the key that is required to sign the certificate in a previous step, so we need to create it along 
    with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
    
-keyout: This line tells OpenSSL where to place the generated private key file that we are creating.

-out: This tells OpenSSL where to place the certificate that we are creating.

Squid Proxy Installation and Configuration

Squid

Squid is a most popular caching and forwarding HTTP web proxy server. It is used to cache web pages from 
a web server to improve web server speed, reduce response times and reduce network bandwidth usage.

Installation of Squid in Ubuntu:
sudo apt update    --To update ubuntu.
sudo apt -y install squid
sudo systemctl start squid
sudo systemctl enable squid
sudo systemctl status squid

Squid configuration file: /etc/squid/squid.conf
Squid Access log: /var/log/squid/access.log
Squid Cache log: /var/log/squid/cache.log

Configure Squid:
vi /etc/squid/squid.conf

http_port : This is the default port for the HTTP proxy server, by default it is 3128, you may change 
            it to any other port that you want, you may also add the “transparent” tag to the end of 
            the line like http_port 8888 transparent to make Squid proxy act like a transparent proxy if you want.
            
http_access deny all : This line won’t let anybody to access the HTTP proxy server, that’s why you need to change 
            it to http_access allow all to start using your Squid proxy server.
            
visible_hostname : This directive is used to set the specific hostname to a squid server. You can give any hostname to squid.


Restart Squid:
sudo systemctl restart squid


Configure squid as an HTTP proxy using only the client IP address for authentication. To allow only one IP address to 
access the internet through your new proxy server, you will need to define new acl (access control list) in the configuration file.

vi /etc/squid/squid.conf
acl localnet src XX.XX.XX.XX
Where XX.XX.XX.XX is the IP address of client machine. This acl should be added in the beginning of the ACL’s section.
Example: acl localnet src 192.168.0.102  #Boss IP address, Some comments

You will need to restart Squid service to take the new changes into effect.
$ sudo systemctl restart squid

Open Ports in Squid Proxy. By default, only certain ports are allowed in the squid configuration, add like below: 
acl Safe_ports port XXX    --Where XXX is the port number that you wish to allow. 


Block Websites:
sudo touch /etc/squid/blacklisted_sites.acl    --Create a file
.badsite1.com    --File content
.badsite2.com    --File content
Squid will block all references to that sites including www.badsite1, subsite.badsite1.com etc. 

acl bad_urls dstdomain "/etc/squid/blacklisted_sites.acl"
http_access deny bad_urls



Block Specific Keyword with Squid
sudo touch /etc/squid/blockkeywords.lst
    facebook
    instagram
    gmail

acl blockkeywordlist url_regex "/etc/squid/blockkeywords.lst"
http_access deny blockkeywordlist

sudo systemctl restart squid

Configure Proxy in Browser now to hit Squid:
Open Firefox and go to Edit –> Preferences –> Advanced –> Network –> Settings and select “Manual proxy configuration”.

Hint: https://www.tecmint.com/install-squid-in-ubuntu/

Thursday, January 31, 2019

Searching Table Name, Schema name from Mysql Database

Search a Table name, Schema name where table is created in mysql:

SELECT table_schema DBase, table_name TableName FROM information_schema.tables WHERE table_name LIKE '%PARAMETERS%';

Thursday, December 27, 2018

Card Frauds

Debit Cards are perfect plastic. Debit card fraud can be sophisticated or old types. Thieves use techniques including:

Hacking: When you bank or shop on public Wi-Fi networks, hackers can use keylogging software to capture everything 
you type, including your name, debit card account number and PIN.

Phishing: Emails can look like they’re from legitimate sources but actually be from scammers. If you click on an 
embedded link and enter your personal information, that data can go straight to criminals.

Skimming: Identity thieves can retrieve account data from your card’s magnetic strip using a device called a skimmer, 
which they can stash in ATMs and store card readers. They can then use that data to produce counterfeit cards. 
EMV chip cards, which are replacing magnetic strip cards, can reduce this risk.

Spying: Plain old spying is still going strong. Criminals can plant cameras near ATMs or simply look over your shoulder 
as you take out your card and enter your PIN. They can also pretend to be good Samaritans, offering to help you remove 
a stuck card from an ATM slot.

Fraudsters either steal your physical card by pick-pocketing, distraction thefts or Clone your card by Skimming.
Social media has all details full names, birthdays, addressess, parent's name and even pets name. Fraudsters befriend you 
and get answer of bank's security question. So keep your privacy settings checked. Using stolen, discarded, fake documents 
open an account in someone's name. Then request changes to the account or ask for a new card to be issued.
Card stolen in transit between card issuer and card holder.
Getting card details from contact less cards.

Payment Processing via Payment Gateway

A Payment Gateway is a service that authenticate & process the payment between customer and merchant. 
The payment process is as below:

1) Buyer selects the product, clicks on BUY Button in Desktop/Mobile initiating the payment from the merchant's 
   website where user info is collected.
2) This info is sent to the Payment Gateway / Payment Aggregator.

3) Payment Aggregator collects card info in a secure server and passes this through its Acquiring Bank 
   (Payment aggregator's bank) to the Card networks like VISA, MasterCard, American Express etc.
4) The Card Network checks with the Issuing bank (Customer Bank) whether the transaction can be authenticated or not. 
   If Yes, the 3DS URL is sent to the customer where he fills all the details for Authentication.
   
5) If Authenticated successfully, Consumer a/c or card is debited by the Issuing bank.
6) Issuer bank sends confirmation to the card network.
7) This is further notified to the Acquiring bank and then to the payment aggregator.

8) Payment aggregator now send a confirmation to the Merchant, who further informs the consumer.
9) The consumer also gets notified by his bank (Issuing bank) about the transaction.

Payment Gateway Examples in India are: PAYU, RAZORPAY, CCAVENUE, TRAK N PAY, Citrus Pay, HDFC BANK PAYMENT GATEWAY, PayPal, AmazonPayments, BillDesk etc.

Authentication vs Authorization

Authentication:
Authentication is about validating your credentials like User Name/User ID and password to verify your identity. 
The system determines whether you are what you say you are using your credentials. In public and private networks, 
the system authenticates the user identity via login passwords. Authentication is usually done by a username and 
password, and sometimes in conjunction with factors of authentication, which refers to the various ways to be 
authenticated. Authentication factors determine the various elements the system use to verify one’s identity prior 
to granting him access to anything from accessing a file to requesting a bank transaction. 
Sending Users to 3DS page is Authentication.

Types of Authentication:
Single-Factor Authentication – Simplest authentication method which relies on a simple password to grant user access 
to a website or a network. UserName and Password.

Two-Factor Authentication – It is a two-step verification process which not only requires a username and password, but 
also something only the user knows, to ensure an additional level of security, such as an ATM pin, which only the user 
knows. OTP too is an added level of security. This also comes under multi-factor authentication. ATM Card and PIN. 
Static Question and Answers after successful login/password. 

Multi-Factor Authentication – Most advanced method of authentication which uses two or more levels of security from 
independent categories of authentication to grant user access to the system. All the factors should be independent of 
each other to eliminate any vulnerability in the system. Financial organizations, banks, and law enforcement agencies use 
multiple-factor authentication to safeguard their data and applications from potential threats. UserName and Password and 
OTP. UserName, Password, Biometrics (fingerprint or thumbprint, palm, handprint, retina, iris, voice and face), RSA SecurID/Token. 
Sometimes it sends some basic question with answers in registered mobile and once user clicks the answer then only login is allowed. 
Also Personal Identity Verification (PIV) Card is like smart card given to employees, citizens. A smart card is a physical card that 
has an embedded integrated chip that acts as a security token. Captcha/Basic maths questions/Picture puzzle along with UserName/Password.


Authorization:
Authorization occurs after your identity is successfully authenticated by the system, which ultimately gives you full permission to 
access the resources such as information, files, databases, funds, locations, almost anything. Authorization determines what user can 
and cannot access. Once your identity is verified by the system after successful authentication, you are then authorized to access the 
resources of the system like Debiting Card. Authorization comes only after successful authentication.

Other examples of Authentication:
    One of the most common methods of detecting a user’s location is via Internet Protocol (IP) addresses. For instance, suppose that 
    you use a service which has Geolocation security checks. When you configure your account, you might say that you live in the 
    United States. If someone tries to log in to your account from an IP address located in Germany, the service will probably notify 
    you saying that a login attempt was made from a location different than yours. That is extremely useful to protect your account 
    against hackers. IP addresses, however, are not the only information that can be used for the somewhere you are factor. It is 
    also possible to use Media Access Control (MAC) addresses. An organization might set up its network so only specific computers 
    can be used to log in (based on MAC addresses). If an employee is trying to access the network from a different computer, the 
    access will be denied. An example, Monzo Bank Ltd., a mobile-only bank based in the United Kingdom, uses Geolocation to detect 
    possible payment frauds. If your last known location was, say, in France and then four minutes later your card is used in Japan, 
    that could be an indication that you are not in the same location as your card.

    Windows 8 users might know about a feature called Picture Password. This feature allows the user to set up gestures and touches on 
    a picture as a way to authenticate themselves. Even HDFC netbanking login asks you to touch picture password apart from login/password.

Wednesday, November 21, 2018

Memory Leak in Java

Memory Leak Creation in Java

Memory leak happens when memory can't be claimed by GC as some areas are unreachable from JVM's garbage collector, 
such as memory allocated through native methods. It gets worse over time. Below are samples of memory leak creation.

1) Create Static field holding object reference esp final fields.
    class MemorableClass {
        static final ArrayList list = new ArrayList(100);
    }

2) Calling String.intern() on lengthy String.
    String str=readString(); //Read lengthy string any source db,textbox/jsp etc..
    str.intern(); //This will place the string in memory pool from which you can't remove.
    
    Ex:
    public class StringLeaker {
        private final String smallString;
        public StringLeaker() {
            String veryLongString = "We hold these truths to be self-evident...";
            this.smallString = veryLongString.substring(0, 1); //The substring maintains a reference to internal char[] representation of the original string.
        }
    }
    Because the substring refers to the internal representation of the original, very long string, the original stays in memory. 
    Thus, as long as you have a StringLeaker in play, you have the whole original string in memory. 
    
    Worse:
    this.smallString = veryLongString.substring(0, 1).intern(); //Both will be in memory even after Class is discarded.
    
    Want to avoid this, use this:
        this.smallString = new String(veryLongString.substring(0, 1));
        
3) Unclosed open streams (file, network etc...)
    try {
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        ...
        ...
    } catch (Exception e) {
        e.printStacktrace();
    }
    
    AND
    
    public class Main {
        public static void main(String args[]) {
            Socket s = new Socket(InetAddress.getByName("google.com"),80);
            s=null; //at this point, because you didn't close the socket properly, you have a leak of a native descriptor, which uses memory. 
        }
    }

4) Unclosed connections. However Closeable is introduced recently.
    try {
        Connection conn = ConnectionFactory.getConnection();
        ...
        ...
    } catch (Exception e) {
        e.printStacktrace();
    }
    
5) Incorrect or inappropriate JVM options, such as the "noclassgc" option prevents unused class garbage collection.

6) Creating, but not starting, a Thread. Creating a thread inherits the ContextClassLoader and AccessControlContext, 
   plus the ThreadGroup and any InheritedThreadLocal, all those references are potential leaks, along with the entire class 
   loaded by the classloader and all static references. Such threads get added to ThreadGroup. It increases the unstarted 
   thread count, also ThreadGroup can't destroy unstarted threads. 
   
7) Calling ThreadGroup.destroy() when the ThreadGroup has no threads itself, but it still keeps child ThreadGroups. 
   A bad leak that will prevent the ThreadGroup to remove from its parent.

8) Keep growing a Queue, without clearing...   

Thursday, August 30, 2018

Ubuntu System Hardware Details

Know Ubuntu System Hardware details:

OS Details:
uname -a
    Linux stg-wib-app32 3.19.0-25-generic #26~14.04.1-Ubuntu SMP Fri Jul 24 21:16:20 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux


RAM Memory Details:
free -m
                 total       used       free     shared    buffers     cached
    Mem:         32175      18520      13655          0        248       4840
    -/+ buffers/cache:      13430      18745
    Swap:        32765         64      32701

Core and CPU:
lscpu
    Architecture:          x86_64
    CPU op-mode(s):        32-bit, 64-bit
    Byte Order:            Little Endian
    CPU(s):                8
    On-line CPU(s) list:   0-7
    Thread(s) per core:    1
    Core(s) per socket:    4
    Socket(s):             2
    NUMA node(s):          1
    Vendor ID:             GenuineIntel
    CPU family:            6
    Model:                 79
    Stepping:              1
    CPU MHz:               2097.570
    BogoMIPS:              4195.14
    Hypervisor vendor:     VMware
    Virtualization type:   full
    L1d cache:             32K
    L1i cache:             32K
    L2 cache:              256K
    L3 cache:              40960K
    NUMA node0 CPU(s):     0-7


Processor Details:
cat /proc/cpuinfo

    processor       : 0
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 0
    siblings        : 4
    core id         : 0
    cpu cores       : 4
    apicid          : 0
    initial apicid  : 0
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 1
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 0
    siblings        : 4
    core id         : 1
    cpu cores       : 4
    apicid          : 1
    initial apicid  : 1
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 2
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 0
    siblings        : 4
    core id         : 2
    cpu cores       : 4
    apicid          : 2
    initial apicid  : 2
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 3
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 0
    siblings        : 4
    core id         : 3
    cpu cores       : 4
    apicid          : 3
    initial apicid  : 3
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 4
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 1
    siblings        : 4
    core id         : 0
    cpu cores       : 4
    apicid          : 4
    initial apicid  : 4
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 5
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 1
    siblings        : 4
    core id         : 1
    cpu cores       : 4
    apicid          : 5
    initial apicid  : 5
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 6
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 1
    siblings        : 4
    core id         : 2
    cpu cores       : 4
    apicid          : 6
    initial apicid  : 6
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

    processor       : 7
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 79
    model name      : Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz
    stepping        : 1
    microcode       : 0xb00002a
    cpu MHz         : 2097.570
    cache size      : 40960 KB
    physical id     : 1
    siblings        : 4
    core id         : 3
    cpu cores       : 4
    apicid          : 7
    initial apicid  : 7
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 20
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt
    bugs            :
    bogomips        : 4195.14
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 42 bits physical, 48 bits virtual
    power management:

Thursday, July 26, 2018

Add 1 to Big Number

//This given code will add value "1" to a number represented as String to accomodate the huge number (can be 100/1000 digits).


package ssl;
public class AddOneToNumber {
    public static void main(String[] args) {
        System.out.println(getMeAddedValue("9"));
        System.out.println(getMeAddedValue("23"));
        System.out.println(getMeAddedValue("49"));
        System.out.println(getMeAddedValue("99"));
        System.out.println(getMeAddedValue("9999"));        
        System.out.println(getMeAddedValue("789"));
        System.out.println(getMeAddedValue("78999999999999999999999999999999"));
    }
    public static String getMeAddedValue(String str){
        boolean flag=true;
        int zeroCount = 0;
        int i=str.length();
        
        while(flag){
            int num = Integer.parseInt(str.substring(i-1, i));
            if(num+1 < 10) {
                str = str.substring(0, i-1) + (num+1);
                break;
            }
            else{
                i--;
                zeroCount++;
                if(zeroCount==str.length()){
                    str = "1";
                    break;
                }
                    
            }
        }
        if(zeroCount>0){
            for(int k=0; k < zeroCount; k++)
                str=str+"0";
        }
        return str;
    }
}

//Output:
10
24
50
100
10000
790
79000000000000000000000000000000

Wednesday, July 4, 2018

Choose JVM / Java Version in Ubuntu

Choose JVM Version while running an application in Ubuntu. 
Assumption: There are multiple JVM versions installed in system and for few processes we want JDK1.7, for few we want JDK1.8.

Ubunut$   update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).  
 
  Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      auto mode
  1            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode
  2            /usr/lib/jvm/jdk1.8.0_161/bin/java               1         manual mode
  3            /usr/lib/jvm/jdk1.7.0_160/bin/java               1         manual mode

Press <enter> to keep the current choice[*], or type selection number:  3   Press Enter (For using JDK1.7)

Wednesday, June 20, 2018

ISO 8583 Message Fields

ISO 8583 Message Fields:
<IsoDataField No="0" length="4" name="MESSAGE TYPE INDICATOR"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="1" length="16" name="BIT MAP"   class="org.jpos.iso.IFA_BITMAP"/>
<IsoDataField No="2" length="19" name="SECRET_ID/PAN"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="3" length="6" name="PROCESSING CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="4" length="12" name="AMOUNT, TRANSACTION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="5" length="12" name="AMOUNT, SETTLEMENT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="6" length="12" name="AMOUNT, CARDHOLDER BILLING"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="7" length="10" name="TRANSMISSION DATE AND TIME"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="8" length="8" name="AMOUNT, CARDHOLDER BILLING FEE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="9" length="8" name="CONVERSION RATE, SETTLEMENT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="10" length="8" name="CONVERSION RATE, CARDHOLDER BILLING"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="11" length="6" name="SYSTEM TRACE AUDIT NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="12" length="6" name="TIME, LOCAL TRANSACTION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="13" length="4" name="DATE, LOCAL TRANSACTION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="14" length="4" name="DATE, EXPIRATION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="15" length="4" name="DATE, SETTLEMENT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="16" length="4" name="DATE, CONVERSION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="17" length="4" name="DATE, CAPTURE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="18" length="4" name="MERCHANTS TYPE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="19" length="3" name="ACQUIRING INSTITUTION COUNTRY CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="20" length="3" name="PAN EXTENDED COUNTRY CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="21" length="3" name="FORWARDING INSTITUTION COUNTRY CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="22" length="3" name="POINT OF SERVICE ENTRY MODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="23" length="3" name="CARD SEQUENCE NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="24" length="3" name="NETWORK INTERNATIONAL IDENTIFIEER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="25" length="2" name="POINT OF SERVICE CONDITION CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="26" length="2" name="POINT OF SERVICE PIN CAPTURE CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="27" length="1" name="AUTHORIZATION IDENTIFICATION RESP LEN"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="28" length="9" name="AMOUNT, TRANSACTION FEE"   class="org.jpos.iso.IFA_AMOUNT"/>
<IsoDataField No="29" length="9" name="AMOUNT, SETTLEMENT FEE"   class="org.jpos.iso.IFA_AMOUNT"/>
<IsoDataField No="30" length="9" name="AMOUNT, TRANSACTION PROCESSING FEE"   class="org.jpos.iso.IFA_AMOUNT"/>
<IsoDataField No="31" length="9" name="AMOUNT, SETTLEMENT PROCESSING FEE"   class="org.jpos.iso.IFA_AMOUNT"/>
<IsoDataField No="32" length="11" name="ACQUIRING INSTITUTION IDENT CODE"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="33" length="11" name="FORWARDING INSTITUTION IDENT CODE"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="34" length="28" name="PAN EXTENDED"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="35" length="37" name="TRACK 2 DATA"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="36" length="104" name="TRACK 3 DATA"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="37" length="12" name="RETRIEVAL REFERENCE NUMBER"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="38" length="6" name="AUTHORIZATION IDENTIFICATION RESPONSE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="39" length="2" name="RESPONSE CODE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="40" length="3" name="SERVICE RESTRICTION CODE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="41" length="8" name="CARD ACCEPTOR TERMINAL IDENTIFICACION"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="42" length="15" name="CARD ACCEPTOR IDENTIFICATION CODE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="43" length="40" name="CARD ACCEPTOR NAME/LOCATION"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="44" length="25" name="ADITIONAL RESPONSE DATA"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="45" length="76" name="TRACK 1 DATA"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="46" length="999" name="ADITIONAL DATA - ISO"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="47" length="999" name="ADITIONAL DATA - NATIONAL"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="48" length="999" name="ADITIONAL DATA - PRIVATE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="49" length="3" name="CURRENCY CODE, TRANSACTION"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="50" length="3" name="CURRENCY CODE, SETTLEMENT"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="51" length="3" name="CURRENCY CODE, CARDHOLDER BILLING"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="52" length="16" name="PIN DATA"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="53" length="16" name="SECURITY RELATED CONTROL INFORMATION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="54" length="120" name="ADDITIONAL AMOUNTS"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="55" length="999" name="RESERVED ISO"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="56" length="999" name="RESERVED ISO"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="57" length="999" name="RESERVED NATIONAL"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="58" length="999" name="RESERVED NATIONAL"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="59" length="999" name="RESERVED NATIONAL"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="60" length="999" name="RESERVED PRIVATE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="61" length="999" name="RESERVED PRIVATE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="62" length="999" name="RESERVED PRIVATE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="63" length="999" name="RESERVED PRIVATE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="64" length="8" name="MESSAGE AUTHENTICATION CODE FIELD"   class="org.jpos.iso.IFA_BINARY"/>
<IsoDataField No="65" length="1" name="BITMAP, EXTENDED"   class="org.jpos.iso.IFA_BINARY"/>
<IsoDataField No="66" length="1" name="SETTLEMENT CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="67" length="2" name="EXTENDED PAYMENT CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="68" length="3" name="RECEIVING INSTITUTION COUNTRY CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="69" length="3" name="SETTLEMENT INSTITUTION COUNTRY CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="70" length="3" name="NETWORK MANAGEMENT INFORMATION CODE"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="71" length="4" name="MESSAGE NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="72" length="4" name="MESSAGE NUMBER LAST"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="73" length="6" name="DATE ACTION"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="74" length="10" name="CREDITS NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="75" length="10" name="CREDITS REVERSAL NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="76" length="10" name="DEBITS NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="77" length="10" name="DEBITS REVERSAL NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="78" length="10" name="TRANSFER NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="79" length="10" name="TRANSFER REVERSAL NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="80" length="10" name="INQUIRIES NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="81" length="10" name="AUTHORIZATION NUMBER"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="82" length="12" name="CREDITS, PROCESSING FEE AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="83" length="12" name="CREDITS, TRANSACTION FEE AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="84" length="12" name="DEBITS, PROCESSING FEE AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="85" length="12" name="DEBITS, TRANSACTION FEE AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="86" length="16" name="CREDITS, AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="87" length="16" name="CREDITS, REVERSAL AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="88" length="16" name="DEBITS, AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="89" length="16" name="DEBITS, REVERSAL AMOUNT"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="90" length="42" name="ORIGINAL DATA ELEMENTS"   class="org.jpos.iso.IFA_NUMERIC"/>
<IsoDataField No="91" length="1" name="FILE UPDATE CODE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="92" length="2" name="FILE SECURITY CODE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="93" length="6" name="RESPONSE INDICATOR"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="94" length="7" name="SERVICE INDICATOR"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="95" length="42" name="REPLACEMENT AMOUNTS"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="96" length="16" name="MESSAGE SECURITY CODE"   class="org.jpos.iso.IFA_BINARY"/>
<IsoDataField No="97" length="17" name="AMOUNT, NET SETTLEMENT"   class="org.jpos.iso.IFA_AMOUNT"/>
<IsoDataField No="98" length="25" name="PAYEE"   class="org.jpos.iso.IF_CHAR"/>
<IsoDataField No="99" length="11" name="SETTLEMENT INSTITUTION IDENT CODE"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="100" length="11" name="RECEIVING INSTITUTION IDENT CODE"   class="org.jpos.iso.IFA_LLNUM"/>
<IsoDataField No="101" length="17" name="FILE NAME"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="102" length="28" name="FROM ACCOUNT"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="103" length="10" name="ACCOUNT IDENTIFICATION 2"   class="org.jpos.iso.IFA_LLCHAR"/>
<IsoDataField No="104" length="100" name="TRANSACTION DESCRIPTION"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="105" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="106" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="107" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="108" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="109" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="110" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="111" length="999" name="RESERVED ISO USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="112" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="113" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="114" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="115" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="116" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="117" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="118" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="119" length="999" name="RESERVED NATIONAL USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="120" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="121" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="122" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="123" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="124" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="125" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="126" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="127" length="999" name="RESERVED PRIVATE USE"   class="org.jpos.iso.IFA_LLLCHAR"/>
<IsoDataField No="128" length="8" name="MAC 2"   class="org.jpos.iso.IFA_BINARY"/>

Wednesday, April 18, 2018

Socket Programming in Java

Socket Programming in Java:

Steps:
1) Run the Server program.
2) Run the Client program.
3) Type anything on Client to Send. Type type Over to exit.

//Socket for Server
package socket;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(1101);  //Server makes a new Socket to communicate with the client and starts Listening.
        System.out.println("Server started.");
        Socket sk = server.accept();  //accept() method blocks(just sits) until a client connects to the server.
        System.out.println("Client connected to Server Socket.");
        
        //Takes input from the client socket
        InputStream is = sk.getInputStream();
        DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
        //DataInputStream dis = new DataInputStream(is);  //This will also work. BufferedInputStream is not required here.

        //String line = dis.readLine();  //readLine() displays some junk too
        String line = dis.readUTF();   //No junk
        System.out.println("Server received: "+line);
        
        
        //Reads message from client until "Over" is sent.
        while (!line.equals("Over")) {
            try {
                line = dis.readUTF();
                System.out.println("Server Received: "+line);
            }
            catch(IOException ioe) {
                ioe.printStackTrace();
            }
        }
        
        //Close connection
        sk.close();
        dis.close();    
    }
}


//Socket for Client
package socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketClient {
    public static void main(String[] args) throws IOException {
        Socket sk = new Socket("127.0.0.1", 1101);    //If wrong config: java.net.ConnectException: Connection refused    
        System.out.println("Client got connected to Server.");

        String msg = "Hello Socket";

        DataOutputStream out = new DataOutputStream(sk.getOutputStream());
        out.writeUTF(msg);  //Sends out to the socket

        out.flush();  //This says, I have no more data.
        System.out.println("Client Sent: "+msg);

        String line="";
        DataInputStream dis = new DataInputStream(System.in); 
        while (!line.equals("Over")) {
            try {
                line = dis.readLine();
                out.writeUTF(line);
                System.out.println("Client Sent: "+line);
            }
            catch(IOException i) {
                i.printStackTrace();
            }
        }
        try {
            out.close();
            sk.close();
        } catch(IOException i) {
            System.out.println(i);
            i.printStackTrace();
        }
    }   
}

NOTE:
Run Server, Run Client--> Works fine.
Run Server, Run Multiple Clients..... --> type messages in all clients, Server will receive msges from first Connected Client Only. 
Server will ignore other clients than the first connected clients. This shows Socket is one-to-one connectivity only.

Thursday, April 5, 2018

BlockingQueue Example Producer Consumer Basic

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
    static Queue queue = new LinkedList();
    static int capacity=3;

    public static void main(String[] args) {
        final Worker work = new Worker();
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                try {
                    work.produce();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable(){
            public void run(){
                try {
                    work.consume();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    } 
    static class Worker {
        int number=0;
        public void produce() throws Exception {

            while(true){
                synchronized(this){
                    while(queue.size()==capacity){
                        System.out.println("Waiting to get Removed...");
                        wait();
                    }
                    number++;
                    queue.add(number);
                    System.out.println("Added: "+number);
                    notifyAll();
                    Thread.sleep(500);
                }
            }

        }
        public void consume() throws Exception {
            while(true){
                synchronized(this){
                    while(queue.isEmpty()){
                        System.out.println("Waiting to get Added...");
                        wait();
                    }
                    Object t = queue.remove();
                    System.out.println("Removed: "+t);
                    notifyAll();
                    Thread.sleep(500);
                }
            }
        }    
    }
}


//Output
Added: 1
Added: 2
Added: 3
Removed: 1
Added: 4
Waiting to get Removed...
Removed: 2
Removed: 3
Removed: 4
Waiting to get Added...
Added: 5
Added: 6
Removed: 5
Removed: 6
Waiting to get Added...
Added: 7