SSL/TLS - Secure Sockets Layer/Transport Layer Security

December 22, 2020 |

 

SSL - Secure Socket Layer

Descriptionwiki

Transport Layer Security (TLS), and its now-deprecated predecessor, Secure Sockets Layer (SSL), are cryptographic protocols designed to provide communications security over a computer network. Several versions of the protocols are widely used in applications such as web browsing, email, instant messaging, and voice over IP (VoIP). Websites can use TLS to secure all communications between their servers and web browsers

Versions of SSL/TLS

SSL 1.0 >  SSL 2.0 > SSL 3.0 > TLS 1.0 > TLS 1.1 > TLS 1.2 > TLS 1.3

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

Setup Environment

1. Keytool in JDK

Windows:

JAVA_HOME=<jdk_dir>

$keytool

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

Creating the JKS keystore
Ref: Create Keystore

$keytool -genkey -alias <alias_name> -validity <days of valid> -keyalg RSA -keystore keystore
ex: keytool -genkey -alias server -validity 365 -keyalg RSA -keystore keystore

Enter keystore password: strongKeystorePassword

Re-enter new password: strongKeystorePassword

Or

What is your first and last name?

  [Unknown]:  app23.example.com

Note: 
The Common Name is typically composed of Host + Domain Name. 
The Common Name must be the same as the Web address you will be accessing when connecting to a secure site.
For the Endeca Server certificate, you can use the name of the server, including its full domain name. This procedure will use
app23.example.com as the Common Name. After enabling SSL, you can specify the same Common Name with the --host option of the endeca-cmd commands. 

What is the name of your organizational unit?

  [Unknown]:  Apps Department

What is the name of your organization?

  [Unknown]:  example.com

What is the name of your City or Locality?

  [Unknown]:  Cambridge

What is the name of your State or Province?

  [Unknown]:  Massachusetts

What is the two-letter country code for this unit?

  [Unknown]:  US

Is CN=app23.example.com, OU=Apps Department, O=example.com, L=Cambridge, 

ST=Massachusetts, C=US correct?

  [no]:  yes

Enter key password for <server>

        (RETURN if same as keystore password): <RETURN>

When you answer the last prompt, keytool writes the keystore file in the current directory. The keystore contains a private key and a self-signed public key.


Generate a Certificate Signing Request (CSR)

$ keytool -certreq -alias server -keyalg RSA -file endeca.csr -keystore keystore

Send endeca.csr to CA for signing.

Import sign certificate to keystore.

$ keytool -import -file rootCA.pem -keystore keystore -trustcacerts

List all keys on keystore

$ keytool -list -v -keystore path_to_keystore_file

Creating a Self-Signed Certificate

$ keytool -genkeypair -alias alias_name -keyalg RSA -validity #_of_days -keysize 2048 -keystore path_to_keystore_file

Export certificate to another one use

$ keytool -export -alias alias_name -keystore path_to_keystore_file -rfc -file path_to_certificate_file

Installing the Self-Signed Certificate on the Client

$ keytool -importcert -alias alias_name -file path_to_certificate_file -keystore truststore_file

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

Tips:

1. Install Self-Sign for Nginx
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /vicare/programz/ssl/nginx-selfsigned.key -out /vicare/programz/ssl/nginx-selfsigned.crt

2. Check CA SSL correct or not

Ref: https://www.namecheap.com/support/knowledgebase/article.aspx/9771/2238/apache-error-x509_check_private_keykey-values-mismatch/

$ openssl x509 -in /path/to/certificate.crt -noout -modulus | openssl sha1

$ openssl rsa -in /path/to/private.key -noout -modulus | openssl sha1

Check output between private key/public key same or not.



Read more…

MySQL/MariaDB - Collection

December 10, 2020 |

 

MYSQL

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

INSTALLATION

1. CentOS

Ref: https://www.hostinger.com/tutorials/how-to-install-mysql-on-centos-7

 // get update
# yum update

//download repository
 # wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm

// Install
# rpm -Uvh mysql80-community-release-el7-3.noarch.rpm

// Install mysql server
# yum install mysql-server

#Uninstall MySQL
$ sudo service mysql stop
$ sudo killall -KILL mysql mysqld_safe mysqld

$ sudo yum remove mysql-client mysql-server -y

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

MYSQL UNINSTALLATION

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

MARIA DB INSTALLATION (CENTOS)

$ yum install mariadb-server

$ systemctl start mariadb

$ systemctl enable mariadb

$ mysql_secure_installation

MARIA DB INSTALLATION (Amazon Linux 2)

Note: Default Mariadb on this repository is 5.3 which older version. If we want to install higher version, do that:

Enable extras repository: 

$ sudo amazon-linux-extras enable lamp-mariadb10.2-php7.2=latest
$ sudo yum install mariadb mariadb-server

Disabled after installing completed.
$ sudo amazon-linux-extras disable lamp-mariadb10.2-php7.2=latest

Ref: https://stackoverflow.com/questions/63069237/mariadb-installation-on-amazon-linux-2

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

MARIAB UNINSTALLATION

$ rpm -qa | grep mariadb

Remove packages show as above:

rpm -e --nodeps "mariadb-errmsg-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-server-utils-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-connector-c-config-3.1.11-2.el8_3.noarch"

rpm -e --nodeps "mariadb-connector-c-3.1.11-2.el8_3.x86_64"

rpm -e --nodeps "mariadb-server-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-common-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-backup-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

rpm -e --nodeps "mariadb-gssapi-server-10.3.28-1.module_el8.3.0+757+d382997d.x86_64"

Remove config

rm -f /var/log/mariadb

rm -f /var/log/mariadb/mariadb.log.rpmsave

rm -rf /var/lib/mysql

rm -rf /usr/lib64/mysql

rm -rf /usr/share/mysql

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

MYSQL - COMMAND LINE FOR CHECK

1. Restart/Stop MYSQL service in RELHAT/CENTOS
//Start MySQL
# systemctl start mysqld

//Stop mysql
# systemctl stop mysqld

//Check mysql status
# systemctl status mysqld

 // Change password of root user
# sudo grep 'password' /var/log/mysqld.log  => get tmp password when you first install
# sudo mysql_secure_installation
The existing password for the user account root has expired. Please set a new password.
New password:
Re-enter new password:
Remember: must be restart mysql

//Check current MYSQL version
# mysql -u root -p

 //Reset root password
#sudo mysqld_safe --skip-grant-tables // restart SAFE MODE
#mysql -uroot // connect mySQL

//remove Mysql in CentOS
$ yum remove mysql mysql-server
$ mv /var/lib/mysql /var/lib/mysql_bkup

2. Command line in MYSQL terminal

2.1 Update root password
USE MYSQL;
UPDATE USER SET PASSWORD=PASSWORD(“newpassword”) WHERE USER=’root’;
FLUSH PRIVILEGES;
EXIT

 //Restart MYSQL service after update password

2.2  Show password policy
Ref: https://dev.mysql.com/doc/refman/5.6/en/validate-password-options-variables.html

# SHOW VARIABLES LIKE 'validate_password%';

Result: 

mysql> SHOW VARIABLES LIKE 'validate_password%';

+--------------------------------------+--------+

| Variable_name                        | Value  |

+--------------------------------------+--------+

| validate_password.check_user_name    | ON     |

| validate_password.dictionary_file    |        |

| validate_password.length             | 8      |

| validate_password.mixed_case_count   | 1      |

| validate_password.number_count       | 1      |

| validate_password.policy             | MEDIUM |

| validate_password.special_char_count | 1      |

+--------------------------------------+--------+

7 rows in set (0.00 sec)

We can change this policy by command line below:
# SET GLOBAL validate_password.length = 6;

2.3 Change password

#ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';

2.4 Grant priviliges

#GRANT ALL PRIVILEGE ON <databases>.* TO 'hr_admin'@'%';

#GRANT ALL PRIVILEGE ON <databases>.*TO 'hr'@'localhost';

#GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, CREATE VIEW, EVENT, TRIGGER, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EXECUTE ON  db_hr.* TO 'hr_admin'@'%';

2.5 Check Mariadb Version

$mysql -u root -p

$select @@version;

2.5 Change Mariadb Port

$ netstat -nltp | grep <your_port> // Check your port is exist or not before change

$ vi /etc/my.cnf.d/mariadb-server.cnf

[mysqld]

datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock

log-error=/var/log/mariadb/mariadb.log

pid-file=/run/mariadb/mariadb.pid

port=<enter your port here>

$systemctl restart maridb

- Check port open.

Problems/Solution

1. Fail to start mariadb in CenTos

Error:

========

2022-11-15 11:11:48 0 [Warning] mysqld: GSSAPI plugin : default principal 'mariadb/hrapprd@' not found in keytab

2022-11-15 11:11:48 0 [ERROR] mysqld: Server GSSAPI error (major 851968, minor 2529639093) : gss_acquire_cred failed -Unspecified GSS failure.  Minor code may provide more information. Keytab FILE:/etc/krb5.keytab is nonexistent or empty. 

2022-11-15 11:11:48 0 [ERROR] Plugin 'gssapi' init function returned error.

2022-11-15 11:12:10 0 [Note] InnoDB: Using Linux native AIO

2022-11-15 11:12:10 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins

2022-11-15 11:12:10 0 [Note] InnoDB: Uses event mutexes

2022-11-15 11:12:10 0 [Note] InnoDB: Compressed tables use zlib 1.2.11

2022-11-15 11:12:10 0 [Note] InnoDB: Number of pools: 1

2022-11-15 11:12:10 0 [Note] InnoDB: Using SSE2 crc32 instructions

2022-11-15 11:12:10 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M

2022-11-15 11:12:10 0 [Note] InnoDB: Completed initialization of buffer pool

2022-11-15 11:12:10 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().

2022-11-15 11:12:10 0 [Note] InnoDB: 128 out of 128 rollback segments are active.

2022-11-15 11:12:10 0 [Note] InnoDB: Creating shared tablespace for temporary tables

2022-11-15 11:12:10 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...

2022-11-15 11:12:10 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.

2022-11-15 11:12:10 0 [Note] InnoDB: 10.3.28 started; log sequence number 1625716; transaction id 20

2022-11-15 11:12:10 0 [Note] Plugin 'FEEDBACK' is disabled.

2022-11-15 11:12:10 0 [Warning] mysqld: GSSAPI plugin : default principal 'mariadb/hrapprd@' not found in keytab

2022-11-15 11:12:10 0 [ERROR] mysqld: Server GSSAPI error (major 851968, minor 2529639093) : gss_acquire_cred failed -Unspecified GSS failure.  Minor code may provide more information. Keytab FILE:/etc/krb5.keytab is nonexistent or empty. 

2022-11-15 11:12:10 0 [ERROR] Plugin 'gssapi' init function returned error.

2022-11-15 11:12:10 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool

2022-11-15 11:12:10 0 [Note] InnoDB: Buffer pool(s) load completed at 221115 11:12:10

2022-11-15 11:12:10 0 [Note] Server socket created on IP: '::'.

2022-11-15 11:12:11 0 [Note] Reading of all Master_info entries succeeded

2022-11-15 11:12:11 0 [Note] Added new Master_info '' to hash table

2022-11-15 11:12:11 0 [Note] /usr/libexec/mysqld: ready for connections.

Version: '10.3.28-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server

=====

Solution:

rm /var/lib/mysql-files /var/lib/mysql-keyring
rm -rf /var/lib/mysql/*

2. No Result in Heidi

Refhttps://www.heidisql.com/forum.php?t=6073
Solution:

This seems to be a popular cosmetic issue in HeidiSQL. You could solve it the hard way:
- exit all heidisql.exe processes
- start regedit.exe
- go to HKEY_CURRENT_USER\Software\HeidiSQL\
- delete value "querymemoheight"
- start heidisql.exe                              

3. Create users

$ CREATE USER 'username'@'host' IDENTIFIED  BY 'password';

4. Error "#1030 - Got error 176 "Read page with wrong checksum" from storage engine Aria" 

Ref:  https://stackoverflow.com/questions/60864367/1030-got-error-176-read-page-with-wrong-checksum-from-storage-engine-aria


- Select the 'mysql' database

- Select all the tables as described in other fixes, but run a 'check tables' instead of a 'repair tables'.

- Check table is broken.

- Back to Step #1 and select this broken table and then repair tables.

 5. Change Data File of Mariadb

$ systemctl stop mariadb
$ mv /var/lib/mysql  /var/lib/mysql.bak // Backup current database
$ rsync -av /var/lib/mysql /new_place //Sync data to new location

$ vi /etc/my.cnf.d/mariadb-server.cnf
datadir=/new_place/mysql

$ vi /etc/my.cnf

[client-server]
socket=/new_place/mysql/mysql.sock
port=3370  // we can change default port also

$vi /etc/selinux/config 

$ SELINUX=enforcing => disabled // turn off SELLinux

6. Show grant of user

SHOW GRANTS FOR 'myuser'@localhost; 

7. Drop user

DROP USER 'vcare'@'%';

8. List of User

select user,host from mysql.user;

9. Backup Mariab DB Tool
-- Full Backup 
mariabackup --backup --target-dir=xxx --user=xxx --password=xxx

-- Single Table Backup
mariadb-dump --user=xxx --password =xxx --lock-tables --databases xxx> /data/backup/db1.sql

 

Read more…

[WAS] - Tomcat, Glassfish

August 26, 2020 |

How to installing Hudson on GlassFish server?

We can deploy Hudson on GlassFish, TomCat or JBoss server. This article, I only show install on GlassFish server run on Window.
Prepares:
1. GlassFish. download glassfish
2. Hudson. download hudson

I. GlassFish server

Ref:
1. http://teckchillies.com/install-remove-java-glassfish-as-a-windows-service/
2. https://javaee.github.io/glassfish/doc/5.0/quick-start-guide.pdf

1. Extract glassfish-x.x.zip
2. Go to \glassfish5\bin and open terminal.

start domain
#asadmin start-domain
#asadmin stop-domain

start/stop database
#asadmin start-database
#adadmin stop-database

4. Open web browsers
5. Access to URL to open Glassfish console.
URL localhost:4848

 Make GlasshFish as window service

#create windows service
asadmin create-service --name domain1
#Change service display name
sc config domain1 DisplayName= "GlassFish 4"



II. TOMCAT server

1. Config access tomcat home page from local network
Open apache-tomcat-8.5.61/conf/server.xml and add 'address' attribute as below:

<Connector port="8080" protocol="HTTP/1.1"
  connectionTimeout="20000"
  redirectPort="8443"
  address="0.0.0.0"
/> 
Note: Remember to check firewall on server and client.

2. Config Tomat as service in Centos
Ref:

Step 1: Install OpenJDK
$ sudo yum install java-1.8.0-openjdk
$ ll /usr/lib/jvm/jre   (check jre)

Step 2: Create tomcat user
$ groupadd tomcat
$ useradd -M -s /bin/nologin -g tomcat -d /opt/tomcat tomcat

Step 3: Install Tomcat
- Download tomcat.tar.gz for linux.  (http://tomcat.apache.org/download-80.cgi)
- Upload to /tmp
- Unzip tomcat:
$mkdir /opt/tomcat
$tar xvf apache-tomcat-8*.tar.gz -C /opt/tomcat --strip-components=1

Step 4: Update permission for /opt/tomcat
$cd /opt/tomat
$chgrp -R tomcat /opt/tomcat
$chmod -R g+r conf
$chmod g+x conf
$ chown -R tomcat webapps/ work/ temp/ logs/

Step 5: Make Systemd Unit File
#!/bin/bash
# chkconfig: 345 80 20

[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/lib/jvm/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target
$ systemctl daemon-reload
$ systemctl status tomcat
$systemctl enable tomcat

Step 6: Open browser and try to access: localhost:8080

3. Config Tomat as service in Centos
Step 1: Config tomat user
$ vi /opt/tomcat/conf/tomcat-users.xml
<tomcat-users>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="your password" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
</tomcat-users>

Step 2: Config Manager App, Host Manager App
$vi /opt/tomcat/webapps/manager/META-INF/context.xml
$vi /opt/tomcat/webapps/host-manager/META-INF/context.xml
 Change as below:
- Comment to allow all public IP can access tomcat interface
OR
- Enter allow="your ip"
<Context antiResourceLocking="false" privileged="true" >
  <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />-->
</Context>

Step 3: Restart Tomcat
$ systemctl restart tomcat

How to Enable SSL tomcat?
$ keytool -genkey -keyalg RSA -noprompt -alias tomcat -dname "CN=localhost, OU=NA, O=NA, L=NA, S=NA, C=NA" -keystore keystore.jks -validity 9999 -storepass changeme -keypass changeme

Config in conf/server.xml, find <Connector port=8443>
certificateKeyAlias="tomcat"
certificateKeystoreFile="/path/to/my/keystore.jks"
certificateKeystorePassword="changeme"

How to redirect HTTP to HTTPS

Edit server.xml




Edit web.xml


====
<security-constraint>
    <web-resource-collection>
        <web-resource-name>vcare-service</web-resource-name>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>

    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
===
=================================================================
How to restrict access, Tomcat Manager 


#1: Server status  : webapps/manager
#2: Manager App : webapps/manager
#3: Host Manager: /webapps/host-manager


If you want to restrict ip access for each apps:
$ vi /host-manager/META-INFO/context.xml

<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="x.x.x.x,y.y.y.y,z.z.z.*" />

Allow localhost to access via default port while other addresses are accessible via 1234:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
   addConnectorPort="true"
   allow="127\.\d+\.\d+\.\d+;\d*|::1;\d*|0:0:0:0:0:0:0:1;\d*|.*;1234"/>


is updating...
Read more…

[Oracle] - JAVA and another one related JAVA

June 11, 2020 |


Read more…

[React Native ] - All of things

May 29, 2020 |


React Native

==================================================================
BASIC


==================================================================
REACT REDUX 

1. Promise data in store






Data will be wrong. You can not access props.variable


==================================================================
1. Facebook Login

$ yarn add react-native-fbsdk-next
OR npm
$ npm install --save react-native-fbsdk-next

2. Change Emulated Performance - Graphics
- Go to Android > Show  on Disk:

- Open file : config.ini and edit below:
hw.gpu.enabled = yes
hw.gpu.mode = host  //Host: use Hardware 

or
hw.gpu.mode=software (or hardware)

3. How to resolve issue related FLAG_IMMUTABLE 
Decription: Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

4. Google SignIn SDK is failing by throwing error, A non-recoverable sign in failure occurred -catch error: React Native

Step 1: cd ./android && ./gradlew signingReport
Step 2: Copy  SHA1 of Task :app:signingReport, Variant: debugAndroidTest, Config: debug
Step 3: Update it the Firebase Console under Project Settings, Android app, add the SHA1



Update support email

Add fingerprint with step below







Step 4: Download the google-services.json, put it in ./android/app
Step 5: Go to Authentication, then Sign-in method, then press Google


Step 6: Take the Web client ID and use that for your GoogleSignin.configure({ webClientId: ... });
Step 7: This Web client ID should be the same as listed in https://console.developers.google.com/apis/credentials?project=<your_project_id> -> Credentials -> OAuth 2 Client ID -> Web Client

5. Check Realm DB Version for Compatible React Native


6. Enable Proguard
Run Proguard to shrink the Java bytecode in release builds.

edit in app/build.gradle
/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = true

It will be some error when enable this while run app. Add more to proguard-rules.pro :

# Add any project specific keep options here:
-keep class io.realm.**  { * ;  }
-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.hermes.unicode.** { *; }
-keep class com.facebook.jni.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }
-keep public class com.horcrux.svg.** {*;}





is updating...


Read more…

[Java] - Spring Frame A -> Z

May 24, 2020 |



Spring Boot
================================================================
================================================================
Spring solution
================================================================
This article is collection of my experience about Spring. I usually update this when I learn new knowledge.


Read more…

[ExtJS] A->Z

March 16, 2020 |
EXT JS
 Document: https://docs.sencha.com/extjs/7.1.0/

========================================================================
1. Grid
//create Grid Panel
var sm = Ext.create("Ext.grid.Panel) {...}
var me = sm.getCmp("<id of grid>"); // get grid component.
me.store.add(object); // object or json,... => add new row to Grid

//delete rows
var sml = me.getSelectionModel();
var rec = sml.getSelection()[0];
me.store.remove(rec);

//format data in cell.
Ext.create('Ext.grid.Grid', {
   title: 'tittle',
   store: Ext.data.StoreManager.lookup('sampleStore'),
   columns: [
    {text: 'Symbol', dataIndex: 'symbol', width: 100},
    {text: 'Price', dataIndex: 'price', width: 100, formatter: 'usMoney'},
    {text: 'Change', dataIndex: 'change', xtype: 'numbercolumn', format: '0.00', width: 100},
    {text: 'Change', dataIndex: 'change', xtype: 'numbercolumn', format: '0,000', width: 100},
    {text: 'Change', dataIndex: 'change', xtype: 'numbercolumn', format: '00.00%', width: 100},
   ],
})

//locked columns
add locked=true to columns.
{text: 'Change', dataIndex: 'change', xtype: 'numbercolumn', format: '0.00', width: 100, locked=true},
Ref: https://docs.sencha.com/extjs/4.1.1/extjs-build/examples/grid/locking-grid.html

//highlight a row in grid
// css
.your-selected-cls .x-grid-cell {
    background-color: red !important;
}

//js
var selNodes =  myExtGrid.getView().getSelectedNodes();
var r = Ext.get(selNodes[0]);
 
//remmove css
r.removeCls("your-selected-cls");

//add css
r.addCls("your-selected-cls");
Ref: https://forum.sencha.com/forum/showthread.php?230756-add-custom-background-color-to-individual-grid-row

//highlight a column in grid
// adding color to columns
 grid.columns[cellIndex].tdCls="your-selected-cls "; => put css there
grid.getView().refresh();

//merge two data value into one column in Grid.
{
   header: "Name",
   dataIndex: 'last_name',
   renderer: function(value, element, record) {
       return record.data['last_name'] + ', ' + record.data['first_name'];
   }
}



...is updating...
Read more…

[Javascript/Jquery/CSS] - A->Z

March 14, 2020 |
JAVASCRIPT

Find element has <id> and change value itself.
document.getElementById("<id>").innerHTML = "Hello JavaScript";
document.getElementById("<id>").style.<attribute> = "<value>";
Function:
function myFunction() {
 // return with object
 return object;
}
function myFunction() {
  // void function
}
function function1 (parameter1, parameter2, parameter3) {
    // code to be executed
}
 Document:
 document.write(<value>);

Console / alert :
// we console useful for debug a script.
console.log(message);

//alert show message to user but sometime we can use debug script.alert(message);

 Object:
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
         return this.firstName + " " + this.lastName;
  }

};

//access object 
person.firstName or person["firstName"];
 String method:
var str = "acb def abc";
str.length; // length no of String, value = 7
// returns the index of (the position of) the first occurrence of a specified textstr.indexOf("def"); //value = 4

//returns the index of the last occurrence of a specified textstr.lastIndexOf("abc"); // value = 8

// method searches a string for a specified value and returns the position of the match
str.search("def"); // value = 4

//extracts a part of a string and returns the extracted part in a new string.
str.slice(start_index, end_index);str.slice(7, 9); //value = abstr.slice(-9, -7); //value = ef

// extracts a part of a string and returns the extracted part in a new 
(NOT ACCEPTED negetive index)str.substring(start_index, end_index);Ex: str.substring(7, 9); //value = ab

// same slice but different second parameter is lengh of substring.str.substr(start, length);
Ex: str.substr(7, 2); //value = ab
str.replace(old string, new string); // Replace first search string
str.replaceAll(old string, new string); // Replacea all search string

str.toUpperCase();
str.toLowerCase(); 
str.concat("string1","string2");

Number methods:
isNaN(x); // check is number or not.

//returns a string, with the number written with a specified number of decimals
var x = 1.876;
x.toFixed(0);           // returns 2
x.toFixed(2);           // returns 1.88

//returns a string, with a number written with a specified length.
x.toPrecision();        // returns 1.876
x.toPrecision(2);       // returns 1.88
x.toPrecision(4);       // returns 1.876
x.toPrecision(6);       // returns 1.87600 

Number()  // Returns a number, converted from its argument.
parseFloat()  // Parses its argument and returns a floating point number
parseInt()  // Parses its argument and returns an integer
Collection (Array, Map):

var array= ["a", "b", 10];
var temp;
//accessarray[index];

//add element to arrayarray.push("Lemon");
for (i = 0; i < length of array; i++) {

}
//for each 1
array.forEach(myFunction);
function myFunction(value) {...} 
//for each 2
array.forEach({
   $(this) // element
});

//push()
var temp = ["a", "b"];
array.push(temp);

2. Detect select tab
<div id="tabDiv">
<ul>
<li><a href="#suspensionTab"><sm:msg code="Suspension_Activation_Replacement"/></a></li>
<li><a href="#terminationTab"><sm:msg code='Termination_Record_Master'/></a></li>
</ul>

<div id="suspensionTab">
<div id="terminationTab">
</div>

$('#tabDiv').click('tabsselect', function (event, ui) {
var activeTab = $('#tabDiv').tabs('option', 'active');
});

3. Getter/Setter in Javascript 
Ref: https://stackoverflow.com/questions/49895080/javascript-class-getter-setter
class Form{
  set foo(val){
    console.log("setting foo")
    this.fooValue = val;
  }
  
  get foo(){
     console.log("getting foo");
     return this.fooValue;
  }
}

let frm = new Form();
frm.foo = "bar";
console.log(frm.foo);

var form = {
  a: "aValue",
  b: "bValue"
}

function withGetterSetter(obj){
   var keys = Object.keys(obj);
   var result = {};
   
   for(var i=0;i<keys.length;i++){
       var key = keys[i];
       result[key+"_internal"] = obj[key];
       (function(k){
         Object.defineProperty(result,k, {
          get:function() {
            console.log("getting property:",k);
            return this[k + "_internal"];
          }, 
          set: function(x) { 
            console.log("setting property:",k);
            this[k + "_internal"] = x 
          }
         });
       })(key)
   }
   return result;
}

var setterObj = withGetterSetter(form);
console.log(setterObj.a);
setterObj.a = "updated";
console.log(setterObj.a);
4. Optional Chaining Operator

Directly use ?. inline to test for existence.
Ex: variable.properties1.properties2
if properties1 is null, the program will throw an undefined exception. Common, we usually check before used access.

if(variable.properties1 !==  undefined  && variable.properties1.properties2 !== undefined )

instead of we can use
variable.properties1?.properties2

Example:

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah',
  },
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined

=========================================================================
ExtJs
Example code: https://hoquoctri.blogspot.com/2020/03/extjs-z.html
Lib: https://docs.sencha.com/extjs/4.2.0/#!/api/Ext

is updating...

=========================================================================
Regrex
 Tool check: https://www.regextester.com/104043
1. Validate email
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;

2. Validate time
//hh:mm:ss
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;


Ex:
  console.log("isCorrectTime 23:59:59 " + isCorrectTime("23:59:59")); => true
console.log("isCorrectTime 09:36:55 " + isCorrectTime("09:36:55")); => true
console.log("isCorrectTime 24:59:59" + isCorrectTime("24:59:59"));  =>f alse

3. Format Credit Card No:
Ex: 
1111222233334444
=> 111122******4444
 Regrex:   /(?<=\d{6})(\d+?)(?=\d{4})/g

1111222233334444
=> 1111-2222-3333-4444
 Regrex:   /(\d{4})(?=\d)/gm

111122******4444
=>1111-22**-****-4444
Regrex:  /\B(?=(\S{4})+(?!\S))/g

4. Mask by Jquery
Mask Transitions: The default available mask transitions are:

‘0’: {pattern: /\d/}
‘A’: {pattern: /[a-zA-Z0-9]/}
‘9’: {pattern: /\d/, optional: true}
‘S’: {pattern: /[a-zA-Z]/}
‘#’: {pattern: /\d/, recursive: true}

The value must match the digit of the pattern.
In this example: Credit card = 16 digit correctponding  16 of "0". 

$(".selector").mask('0000-0000-0000-0000-0000');
Mask Credit Card:  1111222233334444 => 1111-2222-3333-4444

4. Remove HTML tab
const regex = /<(?:.|\n)*?>/gm;
const result = htmlContent.replace(regex, '');

5. Encode URL
If your URL has a special character such as #, ? ,... you should encode your url and decode in another side.

let uri = "car=sa#ab###";
let encoded = encodeURIComponent(uri);
let decoded = decodeURIComponent(encoded);

6. Array includes()

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // return true if existed

7. Jquery: Disable/Enable Select Box in HTML

$('#verifiedYN').removeAttr('disabled');
$('#actionType').attr('disabled', 'disabled');

// Get text from Select Box
$('#id').find(":selected").text();

//Get value from Select Box
$('#id').find(":selected").val();

#Check/Unchecked
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

#Select in SelectBox
$("#MySelectBox").val("5");

7. Get/Set value from <span>

$("#submittername").text("testing"); //get & set
$("#submittername").html("testing <b>1 2 3</b>");

8. Set img src
$("#my_image").attr("src","second.jpg");






is updating...













Read more…