A Complete Guide to Usage of ‘usermod’ command – 15 Practical Examples with Screenshots

In Unix/Linux distributions, the command ‘usermod‘ is used to modify or change any attributes of a already created user account via command line. The command ‘usermod‘ is similar to that ‘useradd‘ or ‘adduser‘ but the login granted to an existing user.

usermod Command Examples

15 usermod Command Examples

The command ‘useradd‘ or ‘adduser‘ is used for creating user accounts in Linux systems. To know more about on how to create system users, read our complete guide at:

  1. A Complete Guide to “useradd” Command in Linux

After creating user accounts, in some scenarios where we need to change the attributes of an existing user such as, change user’s home directory, login name, login shell, password expiry date, etc, where in such case ‘usermod’ command is used.

When we execute ‘usermod‘ command in terminal, the following files are used and affected.

  1. /etc/passwd – User account information.
  2. /etc/shadow – Secure account information.
  3. /etc/group – Group account information.
  4. /etc/gshadow – Secure group account information.
  5. /etc/login.defs – Shadow password suite configuration..

Basic syntax of command is:

usermod [options] username

Requirements

  1. We must have existing user accounts to execute usermod command.
  2. Only superuser (root) is allowed to execute usermod command.
  3. The usermod command can be executed on any Linux distribution.
  4. Must have basic knowledge of usermod command with options

Options of Usermod

The ‘usermod‘ command is simple to use with lots of options to make changes to an existing user. Let us see how to use usermod command by modifying some existing users in Linux box with the help of following options.

  1. -c = We can add comment field for the useraccount.
  2. -d = To modify the directory for any existing user account.
  3. -e = Using this option we can make the account expiry in specific period.
  4. -g = Change the primary group for a User.
  5. -G = To add a supplementary groups.
  6. -a = To add anyone of the group to a secondary group.
  7. -l = To change the login name from tecmint to tecmint_admin.
  8. -L = To lock the user account. This will lock the password so we can’t use the account.
  9. -m = moving the contents of the home directory from existing home dir to new dir.
  10. -p = To Use un-encrypted password for the new password. (NOT Secured).
  11. -s = Create a Specified shell for new accounts.
  12. -u = Used to Assigned UID for the user account between 0 to 999.
  13. -U = To unlock the user accounts. This will remove the password lock and allow us to use the user account.

In this article we will see ‘15 usermod commands‘ with their practical examples and usage in Linux, which will help you to learn and enhance your command-line skills using these options.

1. Adding Information to User Account

The ‘-c‘ option is used to set a brief comment (information) about the user account. For example, let’s add information on ‘tecmint‘ user, using the following command.

# usermod -c "This is Tecmint" tecmint

After adding information on user, the same comment can be viewed in /etc/passwd file.

# grep -E --color 'tecmint' /etc/passwd

tecmint:x:500:500:This is Tecmint:/home/tecmint:/bin/sh

Add User Information in Linux

Add Information to User

2. Change User Home Directory

In the above step we can see that our home directory is under /home/tecmint/, If we need to change it to some other directory we can change it using -d option with usermod command.

For example, I want to change our home directory to /var/www/, but before changing, let’s check the current home directory of a user, using the following command.

# grep -E --color '/home/tecmint' /etc/passwd

tecmint:x:500:500:This is Tecmint:/home/tecmint:/bin/sh

Now, change home directory from /home/tecmint to /var/www/ and confirm the home director after changing.

# usermod -d /var/www/ tecmint
# grep -E --color '/var/www/' /etc/passwd

tecmint:x:500:500:This is Tecmint:/var/www:/bin/sh

Change User Home Directory

Change User Home Directory

3. Set User Account Expiry Date

The option ‘-e‘ is used to set expiry date on a user account with the date format YYYY-MM-DD. Before, setting up an expiry date on a user, let’s first check the current account expiry status using the ‘chage‘ (change user password expiry information) command.

# chage -l tecmint

Last password change					: Nov 02, 2014
Password expires					: never
Password inactive					: never
Account expires						: Dec 01, 2014
Minimum number of days between password change		: 0
Maximum number of days between password change		: 99999
Number of days of warning before password expires	: 7

The expiry status of a ‘tecmint‘ user is Dec 1 2014, let’s change it to Nov 1 2014 using ‘usermod -e‘ option and confirm the expiry date with ‘chage‘ command.

# usermod -e 2014-11-01 tecmint
# chage -l tecmint

Last password change					: Nov 02, 2014
Password expires					: never
Password inactive					: never
Account expires						: Nov 01, 2014
Minimum number of days between password change		: 0
Maximum number of days between password change		: 99999
Number of days of warning before password expires	: 7

Add User Expiry Date in Linux

Set User Account Expiry Date

4. Change User Primary Group

To set or change a user primary group, we use option ‘-g‘ with usermod command. Before, changing user primary group, first make sure to check the current group for the user tecmint_test.

# id tecmint_test

uid=501(tecmint_test) gid=502(tecmint_test) groups=502(tecmint_test)

Now, set the babin group as a primary group to user tecmint_test and confirm the changes.

# usermod -g babin tecmint_test
# id tecmint_test

uid=501(tecmint_test) gid=502(babin) groups=502(tecmint_test)

Change User Group in Linux

Change User Primary Group

5. Adding Group to an Existing User

If you want to add a new group called ‘tecmint_test0‘ to ‘tecmint‘ user, you can use option ‘-G‘ with usermod command as shown below.

# usermod -G tecmint_test0 tecmint
# id tecmint

Add Group to User in Linux

Add Group to User

Note: Be careful, while adding a new groups to an existing user with ‘-G’ option alone, will remove all existing groups that user belongs. So, always add the ‘-a‘ (append) with ‘-G‘ option to add or append new groups.

6. Adding Supplementary and Primary Group to User

If you need to add a user to any one of the supplementary group, you can use the options ‘-a‘ and ‘-G‘. For example, here we going to add a user account tecmint_test0 with the wheel user.

# usermod -a -G wheel tecmint_test0
# id tecmint_test0

So, user tecmint_test0 remains in its primary group and also in secondary group (wheel). This will make my normal user account to execute any root privileged commands in Linux box.

eg : sudo service httpd restart

Add Multiple Groups to User

Add Multiple Groups to User

7. Change User Login Name

To change any existing user login name, we can use ‘-l‘ (new login) option. In the example below, we changing login name tecmint to tecmint_admin. So the username tecmint has been renamed with the new name tecmint_admin.

# usermod -l tecmint_admin tecmint

Now check for the tecmint user, It will not be present because we have changed it to tecmint_admin.

# id tecmint

Check for the tecmint_admin account it will be there with same UID and with existing group what we have added before.

# id tecmint_admin

Change User Login Name in Linux

Change User Login Name

8. Lock User Account

To Lock any system user account, we can use ‘-L‘ (lock) option, After the account is locked we can’t login by using the password and you will see a ! added before the encrypted password in /etc/shadow file, means password disabled.

# usermod -L babin

Check for the locked account.

# grep -E --color 'babin' cat /etc/shadow

Lock User Account in Linux

Lock User Account

9. Unlock User Account

The ‘-U‘ option is used to unlock any locked user, this will remove the ! before the encrypted password.

# grep -E --color 'babin' /etc/shadow
# usermod -U babin

Verify the user after unlock.

# grep -E --color 'babin' /etc/shadow

Unlock User Account in Linux

Unlock User Account

10. Move User Home Directory to New location

Let’s say you’ve a user account as ‘pinky‘ with home directory ‘/home/pinky‘, you want to move to new location say ‘/var/pinky‘. You can use the options ‘-d‘ and ‘-m‘ to move the existing user files from current home directory to a new home directory.

Check for the account and it’s current home directory.

# grep -E --color 'pinky' /etc/passwd

Then list the files which is owned by user pinky.

# ls -l /home/pinky/

Now we have to move the home directory from /home/pinky to /var/pinky.

# usermod -d /var/pinky/ -m pinky

Next, verify the directory change.

# grep -E --color 'pinky' /etc/passwd

Check for the files under ‘/home/pinky‘. Here we have moved the files using -m option so there will be no files. The pinky user files will be now under /var/pinky.

# ls -l /home/pinky/
# ls -l /var/pinky/

Move User Home Directory in Linux

Move User Home Directory

11. Create Un-encrypted Password for User

To create an un-encrypted password, we use option ‘-p‘ (password). For demonstration purpose, I’m setting a new password say ‘redhat’ on a user pinky.

# usermod -p redhat pinky

After setting password, now check the shadow file to see whether its in encrypted format or un-encrypted.

# grep -E --color 'pinky' /etc/shadow

Create Unencrypted User Password in Linux

Create Unencrypted User Password

Note: Did you see in the above image, the password is clearly visible to everyone. So, this option is not recommended to use, because the password will be visible to all users.

12. Change User Shell

The user login shell can be changed or defined during user creation with useradd command or changed with ‘usermod‘ command using option ‘-s‘ (shell). For example, the user ‘babin‘ has the /bin/bash shell by default, now I want to change it to /bin/sh.

# grep -E --color 'babin' /etc/passwd
# usermod -s /bin/sh babin

After changing user shell, verify the user shell using the following command.

# grep -E --color 'babin' /etc/passwd

Change User Login Shell in Linux

Change User Login Shell

13. Change User ID (UID)

In the example below, you can see that my user account ‘babin‘ holds the UID of 502, now I want to change it to 888 as my UID. We can assign UID between 0 to 999.

# grep -E --color 'babin' /etc/passwd
OR
# id babin

Now, let’s change the UID for user babin using ‘-u‘ (uid) option and verify the changes.

# usermod -u 888 babin
# id babin

Change User UID in Linux

Change User UID

14. Modifying User Account with Multiple Options

Here we have a user jack and now I want to modify his home directory, shell, expiry date, label, UID and group at once using one single command with all options as we discussed above.

The user Jack has the default home directory /home/jack, Now I want to change it to /var/www/html and assign his shell as bash, set expiry date as December 10th 2014, add new label as This is jack, change UID to 555 and he will be member of apple group.

Let we see how to modify the jack account using multiple option now.

# usermod -d /var/www/html/ -s /bin/bash -e 2014-12-10 -c "This is Jack" -u 555 -aG apple jack

Then check for the UID & home directory changes.

# grep -E --color 'jack' /etc/passwd

Account expire check.

# chage -l jack

Check for the group which all jack have been member.

# grep -E --color 'jack' /etc/group

Using Multiple Options with usermod

Using Multiple Options with usermod

15. Change UID and GID of a User

We can change UID and GID of a current user. For changing to a New GID we need an existing group. Here already there is an account named as orange with GID of 777.

Now my jack user account want to be assigned with UID of 666 and GID of Orange (777).

Check for the current UID and GID before modifying.

# id jack

Modify the UID and GID.

# usermod -u 666 -g 777 jack

Check for the changes.

# id jack

Change User GID

Change User UID and GID

Conclusion

Here we have seen how to use usermod command with its options in very detailed fashion, Before knowing about usermod command, one should must know ‘useradd’ command and its options to use the usermod. If I’ve missed any point in the article do let me know via comments and don’t forget to add your valuable comments.

Source

3 Ways to Find Out Which Process Listening on a Particular Port

A port is a logical entity which represents an endpoint of communication and is associated with a given process or service in an operating system. In previous articles, we explained how to find out list of all open ports in Linux and how to check if remote ports are reachable using ‘nc’ command.

In this short guide, we will show different ways of finding the process/service listening on a particular port in Linux.

1. Using netstat Command

netstat (network statistics) command is used to display information concerning network connections, routing tables, interface stats and beyond. It is available on all Unix-like operating systems including Linux and also on Windows OS.

In case you do not have it installed by default, use the following command to install it.

$ sudo yum install net-tools	#RHEL/CentOS 
$ sudo apt install net-tools	#Debian/Ubuntu
$ sudo dnf install net-tools	#Fedora 22+

Once installed, you can use it with grep command to find the process or service listening on a particular port in Linux as follows (specify the port).

$ netstat -ltnp | grep -w ':80' 

Check Port Using netstat Command

Check Port Using netstat Command

In the above command, the flags.

  • l – tells netstat to only show listening sockets.
  • t – tells it to display tcp connections.
  • n – instructs it show numerical addresses.
  • p – enables showing of the process ID and the process name.
  • grep -w – shows matching of exact string (:80).

2. Using lsof Command

lsof command (LiSt Open Files) is used to list all open files on a Linux system. To install it on your system, type the command below.

$ sudo yum install lsof	        #RHEL/CentOS 
$ sudo apt install lsof		#Debian/Ubuntu
$ sudo dnf install lsof		#Fedora 22+

To find the process/service listening on a particular port, type (specify the port).

$ lsof -i :80

Find Port Using lsof Command

Find Port Using lsof Command

3. Using fuser Command

fuser command shows the PIDs of processes using the specified files or file systems in Linux.

You can install it as follows:

$ sudo yum install psmisc	#RHEL/CentOS 
$ sudo apt install psmisc	#Debian/Ubuntu
$ sudo dnf install psmisc	#Fedora 22+

You can find the process/service listening on a particular port by running the command below (specify the port).

$ fuser 80/tcp

Then find the process name using PID number with the ps command like so.

$ ps -p 2053 -o comm=
$ ps -p 2381 -o comm=

Find Port and Process ID in Linux

Find Port and Process ID in Linux

You can also check out these useful guides about processes in Linux.

  1. All You Need To Know About Processes in Linux [Comprehensive Guide]
  2. Limit CPU Usage of a Process in Linux with CPULimit Tool
  3. How to Find and Kill Running Processes in Linux
  4. Find Top Running Processes by Highest Memory and CPU Usage in Linux

That’s all! Do you know of any other ways of finding the process/service listening on a particular port in Linux, let us know via the comment form below.

Source

How to Find Out What Version of Linux You Are Running

There are several ways of knowing the version of Linux you are running on your machine as well as your distribution name and kernel version plus some extra information that you may probably want to have in mind or at your fingertips.

Therefore, in this simple yet important guide for new Linux users, I will show you how to do just that. Doing this may seem to be relatively easy task, however, having a good knowledge of your system is always a recommended practice for a good number of reasons including installing and running the appropriate packages for your Linux version, for easy reporting of bugs coupled with many more.

Suggested Read: 5 Ways to Find Out Linux System is 32-bit or 64-bit

With that said, let us proceed to how you can figure out information about your Linux distribution.

Find Out Linux Kernel Version

We will use uname command, which is used to print your Linux system information such as kernel version and release name, network hostname, machine hardware name, processor architecture, hardware platform and the operating system.

To find out which version of Linux kernel you are running, type:

$ uname -or

Shows Current Linux Kernel Version Running on System

Shows Current Linux Kernel Version Running on System

In the preceding command, the option -o prints operating system name and -r prints the kernel release version.

You can also use -a option with uname command to print all system information as shown:

$ uname -a

Shows Linux System Information

Shows Linux System Information

Next, we will use /proc file system, that stores information about processes and other system information, it’s mapped to /proc and mounted at boot time.

Simply type the command below to display some of your system information including the Linux kernel version:

$ cat /proc/version

Shows Linux System Information

Shows Linux System Information

From the image above, you have the following information:

  1. Version of the Linux (kernel) you are running: Linux version 4.5.5-300.fc24.x86_64
  2. Name of the user who compiled your kernel: mockbuild@bkernel01.phx2.fedoraproject.org
  3. Version of the GCC compiler used for building the kernel: gcc version 6.1.1 20160510
  4. Type of the kernel: #1 SMP (Symmetric MultiProcessing kernel) it supports systems with multiple CPUs or multiple CPU cores.
  5. Date and time when the kernel was built: Thu May 19 13:05:32 UTC 2016

Find Out Linux Distribution Name and Release Version

The best way to determine a Linux distribution name and release version information is using cat /etc/os-release command, which works on almost all Linux system.

---------- On Red Hat Linux ---------- 
$ cat /etc/redhat-release

---------- On CentOS Linux ---------- 
$ cat /etc/centos-release

---------- On Fedora Linux ---------- 
$ cat /etc/fedora-release

---------- On Debian Linux ---------- 
$ cat /etc/debian_version

---------- On Ubuntu and Linux Mint ---------- 
$ cat /etc/lsb-release

---------- On Gentoo Linux ---------- 
$ cat /etc/gentoo-release

---------- On SuSE Linux ---------- 
$ cat /etc/SuSE-release

Find Linux Distribution Name and Release Version

Find Linux Distribution Name and Release Version

In this article, we walked through a brief and simple guide intended to help new Linux user find out the Linux version they are running and also get to know their Linux distribution name and version from the shell prompt.

Perhaps it can also be useful to advanced users on one or two occasions. Lastly, to reach us for any assistance or suggestions you wish to offer, make use of the feedback form below.

Source

20 Linux YUM (Yellowdog Updater, Modified) Commands for Package Management

In this article, we will learn how to install, update, remove, find packages, manage packages and repositories on Linux systems using YUM (Yellowdog Updater Modified) tool developed by RedHat. The example commands shown in this article are practically tested on our CentOS 6.3 server, you can use these material for study purpose, certifications or just to explore ways to install new packages and keep your system up-to-date. The basic requirement of this article is, you must have a basic understanding of commands and a working Linux operating system, where you can explore and practice all the commands listed below.

20 Linux Yum Commands

20 Linux Yum Commands

What is YUM?

YUM (Yellowdog Updater Modified) is an open source command-line as well as graphical based package management tool for RPM (RedHat Package Manager) based Linux systems. It allows users and system administrator to easily install, update, remove or search software packages on a systems. It was developed and released by Seth Vidal under GPL (General Public License) as an open source, means anyone can allowed to download and access the code to fix bugs and develop customized packages. YUM uses numerous third party repositories to install packages automatically by resolving their dependencies issues.

1. Install a Package with YUM

To install a package called Firefox 14, just run the below command it will automatically find and install all required dependencies for Firefox.

# yum install firefox
Loaded plugins: fastestmirror
Dependencies Resolved

================================================================================================
 Package                    Arch        Version                    Repository            Size        
================================================================================================
Updating:
firefox                        i686        10.0.6-1.el6.centos     updates             20 M
Updating for dependencies:
 xulrunner                     i686        10.0.6-1.el6.centos     updates             12 M

Transaction Summary
================================================================================================
Install       0 Package(s)
Upgrade       2 Package(s)

Total download size: 32 M
Is this ok [y/N]: y
Downloading Packages:
(1/2): firefox-10.0.6-1.el6.centos.i686.rpm                                |  20 MB   01:10
(2/2): xulrunner-10.0.6-1.el6.centos.i686.rpm                              |  12 MB   00:52
------------------------------------------------------------------------------------------------
Total                                                           63 kB/s |  32 MB   02:04

Updated:
  firefox.i686 0:10.0.6-1.el6.centos

Dependency Updated:
  xulrunner.i686 0:10.0.6-1.el6.centos

Complete!

The above command will ask confirmation before installing any package on your system. If you want to install packages automatically without asking any confirmation, use option -y as shown in below example.

# yum -y install firefox

2. Removing a Package with YUM

To remove a package completely with their all dependencies, just run the following command as shown below.

# yum remove firefox
Loaded plugins: fastestmirror
Setting up Remove Process
Resolving Dependencies
--> Running transaction check
---> Package firefox.i686 0:10.0.6-1.el6.centos set to be erased
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================================
 Package                    Arch        Version                        Repository            Size        
====================================================================================================
Removing:
 firefox                    i686        10.0.6-1.el6.centos            @updates              23 M

Transaction Summary
====================================================================================================
Remove        1 Package(s)
Reinstall     0 Package(s)
Downgrade     0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Erasing        : firefox-10.0.6-1.el6.centos.i686                                                                                                                          1/1

Removed:
  firefox.i686 0:10.0.6-1.el6.centos

Complete!

Same way the above command will ask confirmation before removing a package. To disable confirmation prompt just add option -y as shown in below.

# yum -y remove firefox

3. Updating a Package using YUM

Let’s say you have outdated version of MySQL package and you want to update it to the latest stable version. Just run the following command it will automatically resolves all dependencies issues and install them.

# yum update mysql
Loaded plugins: fastestmirror
Dependencies Resolved

============================================================================================================
 Package            Arch                Version                    Repository                    Size
============================================================================================================
Updating:
 vsftpd             i386                2.0.5-24.el5_8.1           updates                       144 k

Transaction Summary
============================================================================================================
Install       0 Package(s)
Upgrade       1 Package(s)

Total size: 144 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Updating       : vsftpd                                                                     1/2
  Cleanup        : vsftpd                                                                     2/2

Updated:
  vsftpd.i386 0:2.0.5-24.el5_8.1

Complete!

4. List a Package using YUM

Use the list function to search for the specific package with name. For example to search for a package called openssh, use the command.

# yum list openssh
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: mirror.nus.edu.sg
Installed Packages
openssh.i386                                       4.3p2-72.el5_6.3                                                                      installed
Available Packages                                 4.3p2-82.el5                                                                          base

To make your search more accurate, define package name with their version, in case you know. For example to search for a specific version openssh-4.3p2 of the package, use the command.

# yum list openssh-4.3p2

5. Search for a Package using YUM

If you don’t remember the exact name of the package, then use search function to search all the available packages to match the name of the package you specified. For example, to search all the packages that matches the word .

# yum search vsftpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: ftp.iitm.ac.in
============================== Matched: vsftpd ========================
ccze.i386 : A robust log colorizer
pure-ftpd-selinux.i386 : SELinux support for Pure-FTPD
vsftpd.i386 : vsftpd - Very Secure Ftp Daemon

6. Get Information of a Package using YUM

Say you would like to know information of a package before installing it. To get information of a package just issue the below command.

# yum info firefox
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: ftp.iitm.ac.in
Available Packages
Name       : firefox
Arch       : i386
Version    : 10.0.6
Release    : 1.el5.centos
Size       : 20 M
Repo       : updates
Summary    : Mozilla Firefox Web browser
URL        : http://www.mozilla.org/projects/firefox/
License    : MPLv1.1 or GPLv2+ or LGPLv2+
Description: Mozilla Firefox is an open-source web browser, designed for standards
           : compliance, performance and portability.

7. List all Available Packages using YUM

To list all the available packages in the Yum database, use the below command.

# yum list | less

8. List all Installed Packages using YUM

To list all the installed packages on a system, just issue below command, it will display all the installed packages.

# yum list installed | less

9. Yum Provides Function

Yum provides function is used to find which package a specific file belongs to. For example, if you would like to know the name of the package that has the /etc/httpd/conf/httpd.conf.

# yum provides /etc/httpd/conf/httpd.conf
Loaded plugins: fastestmirror
httpd-2.2.3-63.el5.centos.i386 : Apache HTTP Server
Repo        : base
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-63.el5.centos.1.i386 : Apache HTTP Server
Repo        : updates
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-65.el5.centos.i386 : Apache HTTP Server
Repo        : updates
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-53.el5.centos.1.i386 : Apache HTTP Server
Repo        : installed
Matched from:
Other       : Provides-match: /etc/httpd/conf/httpd.conf

10. Check for Available Updates using Yum

To find how many of installed packages on your system have updates available, to check use the following command.

# yum check-update

11. Update System using Yum

To keep your system up-to-date with all security and binary package updates, run the following command. It will install all latest patches and security updates to your system.

# yum update

12. List all available Group Packages

In Linux, number of packages are bundled to particular group. Instead of installing individual packages with yum, you can install particular group that will install all the related packages that belongs to the group. For example to list all the available groups, just issue following command.

# yum grouplist
Installed Groups:
   Administration Tools
   DNS Name Server
   Dialup Networking Support
   Editors
   Engineering and Scientific
   FTP Server
   Graphics
   Java Development
   Legacy Network Server
Available Groups:
   Authoring and Publishing
   Base
   Beagle
   Cluster Storage
   Clustering
   Development Libraries
   Development Tools
   Eclipse
   Educational Software
   KDE (K Desktop Environment)
   KDE Software Development

13. Install a Group Packages

To install a particular package group, we use option as groupinstall. Fore example, to install “MySQL Database“, just execute the below command.

# yum groupinstall 'MySQL Database'
Dependencies Resolved

=================================================================================================
Package								Arch      Version			 Repository        Size
=================================================================================================
Updating:
 unixODBC                           i386      2.2.11-10.el5      base              290 k
Installing for dependencies:
 unixODBC-libs                      i386      2.2.11-10.el5      base              551 k

Transaction Summary
=================================================================================================
Install       1 Package(s)
Upgrade       1 Package(s)

Total size: 841 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : unixODBC-libs	1/3
  Updating       : unixODBC         2/3
  Cleanup        : unixODBC         3/3

Dependency Installed:
  unixODBC-libs.i386 0:2.2.11-10.el5

Updated:
  unixODBC.i386 0:2.2.11-10.el5

Complete!

14. Update a Group Packages

To update any existing installed group packages, just run the following command as shown below.

# yum groupupdate 'DNS Name Server'

Dependencies Resolved
================================================================================================================
 Package			Arch	        Version				Repository           Size
================================================================================================================
Updating:
 bind                           i386            30:9.3.6-20.P1.el5_8.2          updates              981 k
 bind-chroot                    i386            30:9.3.6-20.P1.el5_8.2          updates              47 k
Updating for dependencies:
 bind-libs                      i386            30:9.3.6-20.P1.el5_8.2          updates              864 k
 bind-utils                     i386            30:9.3.6-20.P1.el5_8.2          updates              174 k

Transaction Summary
================================================================================================================
Install       0 Package(s)
Upgrade       4 Package(s)

Total size: 2.0 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Updating       : bind-libs            1/8
  Updating       : bind                 2/8
  Updating       : bind-chroot          3/8
  Updating       : bind-utils           4/8
  Cleanup        : bind                 5/8
  Cleanup        : bind-chroot          6/8
  Cleanup        : bind-utils           7/8
  Cleanup        : bind-libs            8/8

Updated:
  bind.i386 30:9.3.6-20.P1.el5_8.2                  bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Dependency Updated:
  bind-libs.i386 30:9.3.6-20.P1.el5_8.2             bind-utils.i386 30:9.3.6-20.P1.el5_8.2

Complete!

15. Remove a Group Packages

To delete or remove any existing installed group from the system, just use below command.

# yum groupremove 'DNS Name Server'

Dependencies Resolved

===========================================================================================================
 Package                Arch              Version                         Repository          Size
===========================================================================================================
Removing:
 bind                   i386              30:9.3.6-20.P1.el5_8.2          installed           2.1 M
 bind-chroot            i386              30:9.3.6-20.P1.el5_8.2          installed           0.0

Transaction Summary
===========================================================================================================
Remove        2 Package(s)
Reinstall     0 Package(s)
Downgrade     0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Erasing        : bind                                                   1/2
warning: /etc/sysconfig/named saved as /etc/sysconfig/named.rpmsave
  Erasing        : bind-chroot                                            2/2

Removed:
  bind.i386 30:9.3.6-20.P1.el5_8.2                                        bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Complete!

16. List Enabled Yum Repositories

To list all enabled Yum repositories in your system, use following option.

# yum repolist

repo id                     repo name                                            status
base                        CentOS-5 - Base                                      enabled:  2,725
epel                        Extra Packages for Enterprise Linux 5 - i386         enabled:  5,783
extras                      CentOS-5 - Extras                                    enabled:    282
mod-pagespeed               mod-pagespeed                                        enabled:      1
rpmforge                    RHEL 5 - RPMforge.net - dag                          enabled: 11,290
updates                     CentOS-5 - Updates                                   enabled:    743
repolist: 20,824

16. List all Enabled and Disabled Yum Repositories

The following command will display all enabled and disabled yum repositories on the system.

# yum repolist all

repo id                     repo name                                            status
C5.0-base                   CentOS-5.0 - Base                                    disabled
C5.0-centosplus             CentOS-5.0 - Plus                                    disabled
C5.0-extras                 CentOS-5.0 - Extras                                  disabled
base                        CentOS-5 - Base                                      enabled:  2,725
epel                        Extra Packages for Enterprise Linux 5 - i386         enabled:  5,783
extras                      CentOS-5 - Extras                                    enabled:    282
repolist: 20,824

17. Install a Package from Specific Repository

To install a particular package from a specific enabled or disabled repository, you must use –enablerepo option in your yum command. For example to Install PhpMyAdmin 3.5.2 package, just execute the command.

# yum --enablerepo=epel install phpmyadmin

Dependencies Resolved
=============================================================================================
 Package                Arch           Version            Repository           Size
=============================================================================================
Installing:
 phpMyAdmin             noarch         3.5.1-1.el6        epel                 4.2 M

Transaction Summary
=============================================================================================
Install       1 Package(s)

Total download size: 4.2 M
Installed size: 17 M
Is this ok [y/N]: y
Downloading Packages:
phpMyAdmin-3.5.1-1.el6.noarch.rpm                       | 4.2 MB     00:25
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : phpMyAdmin-3.5.1-1.el6.noarch             1/1
  Verifying  : phpMyAdmin-3.5.1-1.el6.noarch             1/1

Installed:
  phpMyAdmin.noarch 0:3.5.1-1.el6

Complete!

18. Interactive Yum Shell

Yum utility provides a custom shell where you can execute multiple commands.

# yum shell
Loaded plugins: fastestmirror
Setting up Yum Shell
> update httpd
Loading mirror speeds from cached hostfile
 * base: mirrors.sin3.sg.voxel.net
 * epel: ftp.riken.jp
 * extras: mirrors.sin3.sg.voxel.net
 * updates: mirrors.sin3.sg.voxel.net
Setting up Update Process
>

19. Clean Yum Cache

By default yum keeps all the repository enabled package data in /var/cache/yum/ with each sub-directory, to clean all cached files from enabled repository, you need to run the following command regularly to clean up all the cache and make sure that there is nothing unnecessary space is using. We don’t want to give the output of the below command, because we like to keep cached data as it is.

# yum clean all

20. View History of Yum

To view all the past transactions of yum command, just use the following command.

# yum history

Loaded plugins: fastestmirror
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    10 | root               | 2012-08-11 15:19 | Install        |    3
     9 | root               | 2012-08-11 15:11 | Install        |    1
     8 | root               | 2012-08-11 15:10 | Erase          |    1 EE
     7 | root               | 2012-08-10 17:44 | Install        |    1
     6 | root               | 2012-08-10 12:19 | Install        |    2
     5 | root               | 2012-08-10 12:14 | Install        |    3
     4 | root               | 2012-08-10 12:12 | I, U           |   13 E<
     3 | root               | 2012-08-09 13:01 | Install        |    1 >
     2 | root               | 2012-08-08 20:13 | I, U           |  292 EE
     1 | System            | 2012-08-08 17:15 | Install        |  560
history list

We have tried to cover all the basic to advance yum commands with their examples. If anything related to yum commands may have missed out. Please update us through our comment box. So, we keep updating the same based on feedback’s received.

Source

How to Run MySQL/MariaDB Queries Directly from the Linux Command Line

If you are in charge of managing a database server, from time to time you may need to run a query and inspect it carefully. While you can do that from the MySQL / MariaDB shell, but this tip will allow you to execute the MySQL/MariaDB Queries directly using the Linux command line AND save the output to a file for later inspection (this is particularly useful if the query return lots of records).

Let us look at some simple examples of running queries directly from the command line before we can move to a more advanced query.

To view all the databases on your server, you can issue the following command:

# mysql -u root -p -e "show databases;"

Next, to create a database table named tutorials in the database tecmintdb, run the command below:

$ mysql -u root -p -e "USE tecmintdb; CREATE TABLE tutorials(tut_id INT NOT NULL AUTO_INCREMENT, tut_title VARCHAR(100) NOT NULL, tut_author VARCHAR(40) NOT NULL, submissoin_date DATE, PRIMARY KEY (tut_id));"

We will use the following command and pipe the output to the tee command followed by the filename where we want to store the output.

Suggested Read: 20 MySQL/MariaDB Commands for Database Administration in Linux

For illustration, we will use a database named employees and a simple join between the employees and salaries tables. In your own case, just type the SQL query between the quotes and hit Enter.

Note that you will be prompted to enter the password for the database user:

# mysql -u root -p -e "USE employees; SELECT DISTINCT A.first_name, A.last_name FROM employees A JOIN salaries B ON A.emp_no = B.emp_no WHERE hire_date < '1985-01-31';" | tee queryresults.txt

View the query results with the help of cat command.

# cat queryresults.txt

Run MySQL/MariaDB Queries from Commandline

Run MySQL/MariaDB Queries from Commandline

With the query results in a plain text files, you can process the records more easily using other command-line utilities.

Summary

We have shared several Linux tips that you, as a system administrator, may find useful when it comes to automating your daily Linux tasks or performing them more easily.

Suggested Read: How to Backup and Restore MySQL/MariaDB Databases

Do you have any other tips that you would like to share with the rest of the community? If so, please do so using the comment form below.

Otherwise, feel free to let us your thoughts about the assortment of tips that we have looked at, or what we can add or possibly do to improve each of them. We look forward to hearing from you!

Source

15 Basic ‘ls’ Command Examples in Linux

ls command is one of the most frequently used command in Linux. I believe ls command is the first command you may use when you get into the command prompt of Linux Box.

We use ls command daily basis and frequently even though we may not aware and never use all the ls option available. In this article, we’ll be discussing basic ls command where we have tried to cover as much parameters as possible.

Linux ls Command

Linux ls Command

1. List Files using ls with no option

ls with no option list files and directories in bare format where we won’t be able to view details like file types, size, modified date and time, permission and links etc.

# ls

0001.pcap        Desktop    Downloads         index.html   install.log.syslog  Pictures  Templates
anaconda-ks.cfg  Documents  fbcmd_update.php  install.log  Music               Public    Videos

2 List Files With option –l

Here, ls -l (-l is character not one) shows file or directory, size, modified date and time, file or folder name and owner of file and its permission.

# ls -l

total 176
-rw-r--r--. 1 root root   683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root  1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Documents
drwxr-xr-x. 4 root root  4096 Aug 16 02:55 Downloads
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Videos

3. View Hidden Files

List all files including hidden file starting with ‘.‘.

# ls -a

.                .bashrc  Documents         .gconfd          install.log         .nautilus     .pulse-cookie
..               .cache   Downloads         .gnome2          install.log.syslog  .netstat.swp  .recently-used.xbel
0001.pcap        .config  .elinks           .gnome2_private  .kde                .opera        .spice-vdagent
anaconda-ks.cfg  .cshrc   .esd_auth         .gtk-bookmarks   .libreoffice        Pictures      .tcshrc
.bash_history    .dbus    .fbcmd            .gvfs            .local              .pki          Templates
.bash_logout     Desktop  fbcmd_update.php  .ICEauthority    .mozilla            Public        Videos
.bash_profile    .digrc   .gconf            index.html       Music               .pulse        .wireshark

4. List Files with Human Readable Format with option -lh

With combination of -lh option, shows sizes in human readable format.

# ls -lh

total 176K
-rw-r--r--. 1 root root  683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1.6K Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Documents
drwxr-xr-x. 4 root root 4.0K Aug 16 02:55 Downloads
-rw-r--r--. 1 root root  21K Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root  46K Jul 31 09:58 index.html
-rw-r--r--. 1 root root  48K Jul 31 02:17 install.log
-rw-r--r--. 1 root root  12K Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Music
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Public
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Templates
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Videos

5. List Files and Directories with ‘/’ Character at the end

Using -F option with ls command, will add the ‘/’ Character at the end each directory.

# ls -F

0001.pcap        Desktop/    Downloads/        index.html   install.log.syslog  Pictures/  Templates/
anaconda-ks.cfg  Documents/  fbcmd_update.php  install.log  Music/              Public/    Videos/

6. List Files in Reverse Order

The following command with ls -r option display files and directories in reverse order.

# ls -r

Videos     Public    Music               install.log  fbcmd_update.php  Documents  anaconda-ks.cfg
Templates  Pictures  install.log.syslog  index.html   Downloads         Desktop    0001.pcap

7. Recursively list Sub-Directories

ls -R option will list very long listing directory trees. See an example of output of the command.

# ls -R

total 1384
-rw-------. 1 root     root      33408 Aug  8 17:25 anaconda.log
-rw-------. 1 root     root      30508 Aug  8 17:25 anaconda.program.log

./httpd:
total 132
-rw-r--r--  1 root root     0 Aug 19 03:14 access_log
-rw-r--r--. 1 root root 61916 Aug 10 17:55 access_log-20120812

./lighttpd:
total 68
-rw-r--r--  1 lighttpd lighttpd  7858 Aug 21 15:26 access.log
-rw-r--r--. 1 lighttpd lighttpd 37531 Aug 17 18:21 access.log-20120819

./nginx:
total 12
-rw-r--r--. 1 root root    0 Aug 12 03:17 access.log
-rw-r--r--. 1 root root  390 Aug 12 03:17 access.log-20120812.gz

8. Reverse Output Order

With combination of -ltr will shows latest modification file or directory date as last.

# ls -ltr

total 176
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-------. 1 root root  1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Videos
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Documents
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
drwxr-xr-x. 4 root root  4096 Aug 16 02:55 Downloads
-rw-r--r--. 1 root root   683 Aug 19 09:59 0001.pcap

9. Sort Files by File Size

With combination of -lS displays file size in order, will display big in size first.

# ls -lS

total 176
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Documents
drwxr-xr-x. 4 root root  4096 Aug 16 02:55 Downloads
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root  4096 Jul 31 02:48 Videos
-rw-------. 1 root root  1586 Jul 31 02:17 anaconda-ks.cfg
-rw-r--r--. 1 root root   683 Aug 19 09:59 0001.pcap

10. Display Inode number of File or Directory

We can see some number printed before file / directory name. With -i options list file / directory with inode number.

# ls -i

20112 0001.pcap        23610 Documents         23793 index.html          23611 Music     23597 Templates
23564 anaconda-ks.cfg  23595 Downloads            22 install.log         23612 Pictures  23613 Videos
23594 Desktop          23585 fbcmd_update.php     35 install.log.syslog  23601 Public

11. Shows version of ls command

Check version of ls command.

# ls --version

ls (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Richard M. Stallman and David MacKenzie.

12. Show Help Page

List help page of ls command with their option.

# ls --help

Usage: ls [OPTION]... [FILE]...

13. List Directory Information

With ls -l command list files under directory /tmp. Wherein with -ld parameters displays information of /tmpdirectory.

# ls -l /tmp
total 408
drwx------. 2 narad narad   4096 Aug  2 02:00 CRX_75DAF8CB7768
-r--------. 1 root  root  384683 Aug  4 12:28 htop-1.0.1.tar.gz
drwx------. 2 root  root    4096 Aug  4 11:20 keyring-6Mfjnk
drwx------. 2 root  root    4096 Aug 16 01:33 keyring-pioZJr
drwx------. 2 gdm   gdm     4096 Aug 21 11:26 orbit-gdm
drwx------. 2 root  root    4096 Aug 19 08:41 pulse-gl6o4ZdxQVrX
drwx------. 2 narad narad   4096 Aug  4 08:16 pulse-UDH76ExwUVoU
drwx------. 2 gdm   gdm     4096 Aug 21 11:26 pulse-wJtcweUCtvhn
-rw-------. 1 root  root     300 Aug 16 03:34 yum_save_tx-2012-08-16-03-34LJTAa1.yumtx
# ls -ld /tmp/

drwxrwxrwt. 13 root root 4096 Aug 21 12:48 /tmp/

14. Display UID and GID of Files

To display UID and GID of files and directories. use option -n with ls command.

# ls -n

total 36
drwxr-xr-x. 2 500 500 4096 Aug  2 01:52 Downloads
drwxr-xr-x. 2 500 500 4096 Aug  2 01:52 Music
drwxr-xr-x. 2 500 500 4096 Aug  2 01:52 Pictures
-rw-rw-r--. 1 500 500   12 Aug 21 13:06 tmp.txt
drwxr-xr-x. 2 500 500 4096 Aug  2 01:52 Videos

15. ls command and its Aliases

We have made alias for ls command, when we execute ls command it’ll take -l option by default and display long listing as mentioned earlier.

# alias ls="ls -l"

Note: We can see number of alias available in your system with below alias command and same can be unalias as shown below example.

# alias

alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

To remove an alias previously defined, just use the unalias command.

# unalias ls

Source

How to Access a Remote Server Using a Jump Host

jump host (also known as a jump server) is an intermediary host or an SSH gateway to a remote network, through which a connection can be made to another host in a dissimilar security zone, for example a demilitarized zone (DMZ). It bridges two dissimilar security zones and offers controlled access between them.

jump host should be highly secured and monitored especially when it spans a private network and a DMZ with servers providing services to users on the internet.

A classic scenario is connecting from your desktop or laptop from inside your company’s internal network, which is highly secured with firewalls to a DMZ. In order to easily manage a server in a DMZ, you may access it via a jump host.

In this article, we will demonstrate how to access a remote Linux server via a jump host and also we will configure necessary settings in your per-user SSH client configurations.

Consider the following scenario.

SSH Jump Host

SSH Jump Host

In above scenario, you want to connect to HOST 2, but you have to go through HOST 1, because of firewalling, routing and access privileges. There is a number of valid reasons why jumphosts are needed..

Dynamic Jumphost List

The simplest way to connect to a target server via a jump host is using the -J flag from the command line. This tells ssh to make a connection to the jump host and then establish a TCP forwarding to the target server, from there (make sure you’ve Passwordless SSH Login between machines).

$ ssh -J host1 host2

If usernames or ports on machines differ, specify them on the terminal as shown.

$ ssh -J username@host1:port username@host2:port	  

Multiple Jumphosts List

The same syntax can be used to make jumps over multiple servers.

$ ssh -J username@host1:port,username@host2:port username@host3:port

Static Jumphost List

Static jumphost list means, that you know the jumphost or jumphosts that you need to connect a machine. Therefore you need to add the following static jumphost ‘routing’ in ~/.ssh/config file and specify the host aliases as shown.

### First jumphost. Directly reachable
Host vps1
  HostName vps1.example.org

### Host to jump to via jumphost1.example.org
Host contabo
  HostName contabo.example.org
  ProxyJump contabo

Now try to connect to a target server via a jump host as shown.

$ ssh -J vps1 contabo

Login to Target Host via Jumphost

Login to Target Host via Jumphost

The second method is to use the ProxyCommand option to add the jumphost configuration in your ~.ssh/config or $HOME/.ssh/config file as shown.

In this example, the target host is contabo and the jumphost is vps1.

Host vps1
	HostName vps1.example.org
	IdentityFile ~/.ssh/vps1.pem
	User ec2-user

Host contabo
	HostName contabo.example.org	
	IdentityFile ~/.ssh/contabovps
	Port 22
	User admin	
	Proxy Command ssh -q -W %h:%p vps1

Where the command Proxy Command ssh -q -W %h:%p vps1, means run ssh in quiet mode (using -q) and in stdio forwarding (using -W) mode, redirect the connection through an intermediate host (vps1).

Then try to access your target host as shown.

$ ssh contabo

The above command will first open an ssh connection to vps1 in the background effected by the ProxyCommand, and there after, start the ssh session to the target server contabo.

For more information, see the ssh man page or refer to: OpenSSH/Cookbxook/Proxies and Jump Hosts.

That’s all for now! In this article, we have demonstrated how to access a remote server via a jump host. Use the feedback form below to ask any questions or share your thoughts with us.

Source

A Definitive Series to Learn Java Programming for Beginners

We are pleased to announce our dedicated series of posts on Java Programming Language on the demand of our readers. In this series we are going to cover everything you need to know about Java.

Learn Java Programming

Learn Java Programming

Why Java?

Java is a General purpose, Object Oriented Programming Language written by James Gosling. It is known for many features which makes it different from other Programming languages. It is one of those Programming Language that has always remained in demand since the time of its initial release. It is one of the most powerful Programming Language which can do amazing things when combined with the power of Linux. Linux+Java is Future. Most talked about Features of Java are:

  1. General Purpose Programming Language
  2. Object Oriented approach
  3. Friendly Syntax
  4. Portability
  5. Memory Management Feature
  6. Architecture Neutral
  7. Interpreted

This tutorial is for those, who have knowledge of any other programming and/or Scripting Language and want to learn Java from core level.

What you need to get started with Java

First thing is you need is to install Java Compiler and set path. The detailed instructions to install latest version of Java and set path is here [Install Java JDK/JRE in Linux]. Once the Java Compiler is Installed and Path is set, run

$ java -version
Sample Output
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Second thing is you need a text editor. You may use any text editor of your choice which may be command line based or a GUI Text editor. My favorite editors are nano (command_line) and gedit (GUI).

You may use any but make sure you don’t use an Integrated Development Environment (IDE). If you start using IDE at this level, you will never understand a few things, so say no to IDE.

The last things you need is a good step-by step guide (which I will be providing) and a never ending quest to learn Java.

Topics we are going to cover

This is an Ever expanding list of topics and there is nothing hard and fast associated with it. I will keep adding up topics to this section as we dive deep into Java. From here you may go anywhere but I suggest you to go through all the topics stepwise.

Part 6Understanding Class and Objects in Java to Create Object in Java
Part 7Understanding Java Variables and its Types and Introduction to Keywords
Part 8Behavior of objects in JVM and variable Initialization in Java
Part 9Local Variables and Instances in Java
Part 10How to Code and Develop Your First Class in Java

We always got the support of our readers and once again we seek the support of our beloved Readers to make popular Java Series Post on Tecmint. Fasten your seat belts and lets start. Keep following.

What is Java? A Brief History about Java

Java is a General Purpose, class based, object oriented, Platform independent, portable, Architecturally neutral, multithreaded, dynamic, distributed, Portable and robust interpreted Programming Language.

What is Java and Brief History about Java

What is Java and Brief History about Java

Why Java is a called:

General Purpose

Java capabilities are not limited to any specific application domain rather it can be used in various application domain and hence it is called General Purpose Programming Language.

Class based

Java is a class based/oriented programming language which means Java supports inheritance feature of object-oriented Programming Language.

Object oriented

Java is object-oriented means software developed in Java are combination of different types of object.

Platform Independent

A Java code will run on any JVM (Java Virtual Machine). Literally you can run same Java code on Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same result every time.

Java Platform Independent

Java Platform Independent

Architecturally Neutral

A Java code is not dependent upon Processor Architecture. A Java Application compiled on 64 bit architecture of any platform will run on 32 bit (or any other architecture) system without any issue.

Multithreaded
A thread in Java refers to an independent program. Java supports multithread which means Java is capable of running many tasks simultaneously, sharing the same memory.

Dynamic

Java is a Dynamic programming language which means it executes many programming behavior at Runtime and don’t need to be passed at compile time as in the case of static programming.

Distributed

Java Supports distributed System which means we can access files over Internet just by calling the methods.

Portable

A Java program when compiled produce bytecodes. Bytecodes are magic. These bytecodes can be transferred via network and can be executed by any JVM, hence came the concept of ‘Write once, Run Anywhere(WORA)’.

Java Concept

Java Concept

Robust

Java is a robust programming Language which means it can cope with error while the program is executing as well as keep operating with abnormalities to certain extent. Automatic Garbage collection, strong memory management, exception handling and type checking further adds to the list.

Interpreted

Java is a compiled programming Language which compiles the Java program into Java byte codes. This JVM is then interpreted to run the program.

Other than the above discussed feature, there are a few other remarkable features, like:

Security

Unlike other programming Language where Program interacts with OS using User runtime environment of OS, Java provides an extra layer of security by putting JVM between Program and OS.

Java Security

Java Security

Simple Syntax

Java is an improved c++ which ensures friendly syntax but with removed unwanted features and inclusion of Automatic Garbage collection.

High Level Programming Language

Java is a High Level Programming Language the syntax of which is human readable. Java lets programmer to concentrate on what to achieve and not how to achieve. The JVM converts a Java Program to Machine understandable language.

High Performance

Java make use of Just-In-Time compiler for high performance. Just-In-Time compiler is a computer program that turns Java byte codes into instructions that can directly be sent to compilers.

History of Java

Java Programming Language was written by James Gosling along with two other person ‘Mike Sheridan‘ and ‘Patrick Naughton‘, while they were working at Sun Microsystems. Initially it was named oak Programming Language.

Java Releases
  1. Initial Java Versions 1.0 and 1.1 was released in the year 1996 for Linux, Solaris, Mac and Windows.
  2. Java version 1.2 (Commonly called as java 2) was released in the year 1998.
  3. Java Version 1.3 codename Kestrel was released in the year 2000.
  4. Java Version 1.4 codename Merlin was released in the year 2002.
  5. Java Version 1.5/Java SE 5 codename ‘Tiger’ was released in the year 2004.
  6. Java Version 1.6/Java SE 6 Codename ‘Mustang’ was released in the year 2006.
  7. Java Version 1.7/Java SE 7 Codename ‘Dolphin’ was released in the year 2011.
  8. Java Version 1.8 is the current stable release which was released this year (2015).

Five Goals which were taken into consideration while developing Java:

  1. Keep it simple, familiar and object oriented.
  2. Keep it Robust and Secure.
  3. Keep it architecture-neural and portable.
  4. Executable with High Performance.
  5. Interpreted, threaded and dynamic.

Why we call it Java 2, Java 5, Java 6, Java 7 and Java 8, not their actual version number which 1.2, 1.5, 1.6, 1.7 and 1.8?

Java 1.0 and 1.1 were Java. When Java 1.2 was released it had a lots of changes and marketers/developers wanted a new name so they called it Java 2 (J2SE), remove the numeric before decimal.

This was not the condition when Java 1.3 and Java 1.4 were released hence they were never called Java 3 and Java 4, but they were still Java 2.

When Java 5 was released, once again it was having a lots of changes for the developer/marketers and need a new name. The next number in sequence was 3, but calling Java 1.5 as Java 3 was confusing hence a decision was made to keep the naming as per version number and till now the legacy continues.

Places where Java is used

Java is implemented over a number of places in modern world. It is implemented as Standalone Application, Web Application, Enterprise Application and Mobile Application. Games, Smart Card, Embedded System, Robotics, Desktop, etc.

Keep connected we are coming up with “Working and code Structure of Java”.

How Java Works and Understanding Code Structure of Java – Part 2

In our last post ‘What is Java and History of Java‘ we had covered What is Java, features of Java in details, release history and its naming as well as places where Java is utilized.

Working of Java Understanding Java Code

Working of Java Understanding Java Code – Part 2

Here in this post we will be going through working and code structure of Java Programming Language. Before we proceed let me remind you that Java was developed keeping in mind “Write Once Run Anywhere/Anytime (WORA)” means to ensure that the application developed should be architecturally neutral, Platform Independent and portable.

Working of Java

Having these goals in mind Java was developed with the below working model which can be classified into four stages.

Stage 1

Write the source file. This file contains all the procedure, method, class and objects within established protocol for Java Programming Language. The name of source file should be the name of the class or vice-versa. The source file name must have extension .java. Also the filename and class name are case sensitive.

Stage 2

Run the Java Source Code file through Java Compiler. Java Source code Compiler checks for error and syntax in the source file. It won’t let you compile your source code without satisfying Java compiler by fixing all errors and warning.

Stage 3

Compiler creates classfile. These classfile inherit the same name as the Source code file name, but the extension varies. The Source file name has extension 'filename.java', where as the extension of classfile created by compiler is 'filename.class'. This classfile is coded into bytecode – bytecodes are like magic.

Stage 4

This classfile created by Java Compiler is portable and architecturally neutral. You can port this classfile to run on any processor architecture and Platform/device. All you need is a Java Virtual Machine (JVM) to run this code no matter where.

Now understand the above four stages using an example. Here is a small sample Java Program code. Don’t worry if you don’t understand the code below. As of now just understand how it works.

public class MyFirstProgram
{
    public static void main(String[] args)
    {
        System.out.println("Hello Tecmint, This is my first Java Program");
    }
}

1. I wrote this program and defined class name MyFirstProgram. It is important to notice that this program must be saved as 'MyFirstProgram.java'.

Remember stage 1 above – The class name and file name must be same and filename must have extension .java. Also java is case sensitive hence if your classname is ‘MyFirstProgram‘, your source file name must be ‘MyFirstProgram.java‘.

You can not name it as ‘Myfirstprogram.java‘ or ‘myfirstprogram.java‘ or anything else. By convention it is a good idea to name your class based upon what the program is doing actually.

2. To compile this Java Source file, you need to pass it through Java compiler. Java compiler will essentially check the source code for any error and warning. It wont compile the source code until all the issues are solved. To compile java source code, you need to run:

$ javac MyFirstProgram.java

Where MyFirstProgram.java is the name of the source file.

3. On successful compilation you will notice that the Java compiler created a new file in the same directory the name of which is MyFirstProgram.class.

This class file is coded in bytecodes and can be run on any platform, any processor architecture any number of time. You may run the class file inside of JVM (Java Virtual Machine) on Linux or any other platform simply as:

$ java MyFirstProgram

So all you learnt above can be summarized as:

Java Source Code >> Compiler >> classfile/bytecode >> Various devices running JVM 

Understanding Code Structure in Java

1. Java source code file must contains a class definition. One Java Source file can contain only one public class/top-level class however it can contain lots of private class/inner-class.

The outer class/top class/public class can access all private class/inner class. The class must be within curly braces. Everything in Java is an object and class is a blueprint for object.

A demo of public/private class in Java:

public class class0
{
...
	private class1
	{
	…
	}

	private class 2
	{
	…
	}
...
}

2. Class contain one or more methods. Method must go within the curly braces of the class. A dummy example is:

public class class0
{
	public static void main(String[] args)
	{
	…..
	…..
	}
}

3. A method contain one or more statement/instruction. The instruction(s) must go within the curly braces of method. A dummy example is:

public class class0
{
	public static void main(String[] args)
	{
	System.out.println("Hello Tecmint, This is my first Java Program");
	System.out.println("I am Loving Java");
	…
	...
	}
}

Also important to mention at this point – Every Statement must end with semicolon. A dummy example is:

System.out.println("Hello Tecmint, This is my first Java Program");
...
...
System.out.println("I am Loving Java");

Writing your first Java Program with detailed description. The description is being put as comments here (//means commented out) in this example. You should write comments within a program.

Not only because this is a good habit but also because it makes the code readable ab you or anyone else at anytime later.

// Declare a Public class and name it anything but remember the class name and file name must be same, say class name is MyProg and hence file name must be MyProg.java
public class MyProg

// Remember everything goes into curly braces of class?
{
 

// This is a method which is inside the curly braces of class.
   public static void main(String[] args)

    // Everything inside a method goes into curly braces	
    {
        
    // Statement or Instruction inside method. Note it ends with a semicolon
    System.out.println("I didn't knew JAVA was so much fun filled");
    
    // closing braces of method
    }

// closing braces of class
}

A detailed technical description of the above simple Java Program.

public class MyProg

Here in the above name of class is MyProg and MyProg is a Public class which means everyone can access it.

public static void main(String[] args)

Here the method name is main which is a public method, means it can be accessed by anyone. The return type is void which means no return value. 'Strings[] args' means the arguments for the method main should be array which is to be called args. Don’t worry about the meaning of ‘static‘ as of now. We will be describing in details about it when required.

System.out.println("I didn't knew JAVA was so much fun filled");

System.out.ln ask JVM to print the output to standard output which is Linux command Line in our case. Anything that is in between braces of println statement gets print as it is, unless it is a variable. We will be going into details of variable later. The statement is ending with semicolon.

Even if something is not clear now you need not worry about this. Also you don’t need to memories anything. Just go through the post and understand terminologies and working even when the picture is not very clear.

That’s all for now. Provide us with your valuable feedback in the comments below. We are working on the next part “class and Main method in Java”and will be publishing soon.

Understanding Java Class, Main Method and Loops Control in Java – Part 3

In our last post ‘Working and code structure of Java‘ we emphasized in details of working of Java, Java Source File, Java Class File, Class (Public/Private), Method, Statement, Your first Java Program, Compilation and running of Java Program.

Here in this java learning series guide, we will understand how java class, main method and loops control works and also we will see basic codes using Java class with main method and loops control.

Understanding Java Class Method and Loops Control

Understanding Java Class Method and Loops Control – Part 3

Everything in Java goes in a class

Everything in Java is an object and class is a blueprint of object. Every piece of code in Java is placed under the curly braces of class. When you compile a Java Program it produces a class file. When you run Java Program you are not running the Program file in actual but the class.

When you run a Program in Java Virtual Machine (JVM), it loads the required class and then goes directly to the main () method. The program continues to run till the closing braces of main () method. The program start executing just after the main() method. A class must have a main () method. Not all the class (Private class) requires a main () method.

What goes inside main () Method?

main () method is the place where magic starts. You can ask JVM to do anything within main() method via statement/instructions and loops.

What is loop?

Loop is an instruction or a number of instructions in sequence that keeps on repeating till the condition is reached. Loops are the logical structure of a programming language. Loop logical structure are typically used to do a process, check the condition, do a process, check the condition,….. till condition requirements are met.

Loops in Java

There are three different loop mechanism in Java.

1. while Loop

while Loop in Java is a control structure which is used to perform a task repeatedly for a certain number of times, as defined in boolean expression, till the expression test result is true. If the boolean expression text result is false the while loop will be ignored completely without being executed even a single time.

Syntax of while loop:

while (boolean expression)
{
	statement/instructions
}

An example of while Loop in Java:

public class While_loop
{
    public static void main(String[] args)
    {
        int A = 100;
        while(A>0)
        {
            System.out.println("The Value of A = " +A);
            A=A-10;
        }
    }
}
Sample Output
$ java While_loop 

The Value of A = 100
The Value of A = 90
The Value of A = 80
The Value of A = 70
The Value of A = 60
The Value of A = 50
The Value of A = 40
The Value of A = 30
The Value of A = 20
The Value of A = 10

Anatomy of While_loop Program

// Public Class While_loop
public class While_loop
{
    // main () Method
    public static void main(String[] args)
    {
        // declare an integer variable named 'A' and give it the value of 100
        int A = 100;
        // Keep looping as long as the value of A is greater than 0. 'A>0' here is the boolean                 
           expression
        while(A>0)
        {
	 // Statement
            System.out.println("The Value of A = " +A);
            // Post Decrement (by 10)
	 A=A-10;
        }
    }
}
2. do..while Loop

do…while loop is very much similar to the while loop except the fact that it contains a do… before while to ensure that loop execute at least once.

Syntax of while loop:

do 
{
statement/instructions
}
while (boolean expression);

You may see the above syntax which clearly shows that the 'do..' part of the loop executed before checking the boolean expression, if it is true or false. Hence no matter what the result (true/false) of boolean expression, the loop executes. If true it will execute till the condition is satisfied. If false it will be executed once.

An Example of do…while Loop in Java:

public class do_while
{
    public static void main(String[] args)
    {
        int A=100;
        do
        {
            System.out.println("Value of A = " +A);
            A=A-10;
        }
        while (A>=50);
    }
}
Sample Output
$ java do_while 

Value of A = 100
Value of A = 90
Value of A = 80
Value of A = 70
Value of A = 60
Value of A = 50

Anatomy of do_while Program:

// public class do_while
public class do_while
{
    // main () Method
    public static void main(String[] args)
    {
        // Declare a Integer Variable 'A' and assign it a value = 100
        int A=100;
        // do...while loop starts
        do
        {
            // execute the below statement without checking boolean expression condition if true 
               or false
            System.out.println("Value of A = " +A);
            // Post Decrement (by 10)
            A=A-10;
        }
        // Check condition. Loop the execute only till the value of Variable A is greater than or 
           equal to 50.
        while (A>=50);
    }
}
3. for Loop

for_loop in Java is widely used for repetition control. It is used to iterate a task for specific number of times. For loop is used to control how many times the loop needs to execute to perform a task. for loop is only useful if you know how many times you need to execute the loop.

Syntax of for loop:

for (initialization; boolean-expression; update)
{
statement
}

An example of the for loop in Java

public class for_loop
{
    public static void main(String[] arge)
    {
        int A;
        for (A=100; A>=0; A=A-7)
        {
            System.out.println("Value of A = " +A);
        }
    }
}
Sample Output
$ java for_loop 

Value of A = 100
Value of A = 93
Value of A = 86
Value of A = 79
Value of A = 72
Value of A = 65
Value of A = 58
Value of A = 51
Value of A = 44
Value of A = 37
Value of A = 30
Value of A = 23
Value of A = 16
Value of A = 9
Value of A = 2

Anatomy of for_loop Program:

// public class for_loop
public class for_loop
{
    // main () Method
    public static void main(String[] arge)
    {
        // Declare a Integer Variable A
        int A;
        // for loop starts. Here Initialization is A=100, boolean_expression is A>=0 and update is 
           A=A-7
        for (A=100; A>=0; A=A-7)
        {
            // Statement        
            System.out.println("Value of A = " +A);
        }
    }
}

The Break and Continue keywords for loops in Java

1. The Break Keyword

As the name suggest the break keyword is used to stop the entire loop immediately. The break keyword must always be used inside the loop or switch statement. Once the loop breaks by using break; JVM starts executing the very next line of code outside of the loop. An example of break loop in Java is:

public class break
{
    public static void main(String[] args)
    {
        int A = 100;
        while(A>0)
        {
            System.out.println("The Value of A = " +A);
            A=A-10;
            if (A == 40)
            {
                break;
            }
        }
    }
}
Sample Output
$ java break 

The Value of A = 100
The Value of A = 90
The Value of A = 80
The Value of A = 70
The Value of A = 60
The Value of A = 50
The Continue Keyword

The continue keyword can be used with any loop in Java. Continue keyword ask the loop to jump to the next iteration immediately. However it is interpreted differently by for loop and while/do…while loop.

Continue Keyword in for loop jumps to the next update statement.

An example of continue in for loop:

public class continue_for_loop
{
    public static void main(String[] arge)
    {
        int A;
        for (A=10; A>=0; A=A-1)
        {
	    if (A == 2)
		{
	        continue;
		}
            System.out.println("Value of A = " +A);
        }
    }
}
Sample Output
$ java continue_for_loop

Value of A = 10
Value of A = 9
Value of A = 8
Value of A = 7
Value of A = 6
Value of A = 5
Value of A = 4
Value of A = 3
Value of A = 1
Value of A = 0

Did you noticed, it skipped Value of A = 2. It does so by dumping to the next update statement.

2. Continue Keyword in while loop or do…while loop jumps to the boolean expression.

Well you can do it yourself. Its too easy. Just follow the above steps.

That’s all for now from my side.

Understanding Java Compiler and Java Virtual Machine – Part 4

Till now we have gone through working and code structure of Java and Class, Main method & Loop Control in Java. Here in this post we will see What is Java Compiler and Java Virtual Machine. What are they meant for and their roles.

Understanding Java Compiler and Java Virtual Machine

Understanding Java Compiler and Java Virtual Machine – Part 4

What is Java Compiler

Java is a strongly typed language which means variable must hold right kind of data. In a strongly typed language a variable can not hold wrong data type. This is a safety feature very well implemented in Java Programming Language.

Java compiler is responsible for through checking the variables for any violation in data-type holding. A few exception may arise at run-time which is compulsory for dynamic binding feature of Java. As Java program runs it may include new objects that were not existing before hence to have some degree of flexibility a few exceptions are allowed in data-type that a variable can hold.

Java Compiler set filter for those piece of code that won’t compile ever except for the comments. Compiler do not parse the comments and leave it as it is. Java code supports three kinds of comments within Program.

1. /* COMMENT HERE */
2. /** DOCUMENTATION COMMENT HERE */
3. // COMMENT HERE

Anything that is placed between /* and */ or /** and */ or after // is ignored by Java Compiler.

Java Compiler is responsible for strict checking any syntax violation. Java Compiler is designed to be a bytecode compiler ie., it create a class file out of actual program file written purely in bytecode.

Java Compiler is the first stage of security. It is the first line of defense where checking for incorrect data-type in variable is checked. A wrong data-type can cause damage to the program and outside it. Also compiler check if any piece of code trying to invoke restricted piece of code like private class. It restrict unauthorized access of code/class/critical data.

Java Compiler produce bytecodes/class file that are platform and architecturally neutral that requires JVM to run and it will literally run on any device/platform/architecture.

What is Java Virtual Machine (JVM)

Java Virtual Machine is the next line of security which put an extra layer between Java Application and OS. Also it check the class file that has been security checked and compiled by Java Compiler, if someone tampered the class file/bytecode to restrict access to unauthorized critical data.

Java Virtual Machine interprets the bytecode by loading the class file to machine Language.

JVM is responsible for functions like Load and Store, Arithmetic calculation, Type conversion, Object Creation, Object Manupulation, Control Transfer, Throwing exception, etc.

The working model of Java in which Java Compiler compiles the code into calssfile/bytecodes and then Java Virtual Machine run the classfile/bytecode. This model ensures that code run at fast speed and the additional layer ensures security.

So what do you think – Java Compiler or Java Virtual Machine perform more important task? A Java program has to run through both the surface (Compiler and JVM) essentially.

This post sums the role of Java Compiler and JVM. All your suggestions are welcome in the comments below. We are working on the next post “object oriented approach of Java”. Till then stay tuned and connected to TecMint. Like and share us and help us get spread.

Object Oriented Approach of Java Programming and Encapsulation – Part 5

Since the beginning of this series (and even before that) you knew Java is an Object Oriented Programming Language. The object oriented Programming Language is based upon the concept of “objects”, which contains data as attributes in methods.

Object Oriented Approach of Java

Object Oriented Approach of Java – Part 5

Every object in Java has state and behavior which are represented by instance variables and methods. Each instance of a class can have unique value for it’s instance variable.

For example,

Machine A may be powered up with Debian and have 8GB of RAM while Machine B can have installed Gentoo with 4GB of RAM. Also it is obvious that managing Machine that have installed Gentoo requires more knowledge – A behavior acting on its state. Here method is using instance variable values.

The JVM when parse a class, it make object of that kind. When you are writing a class, in actual you acting like a compiler telling your class what the object should know and how it should act. Every object of a particular type can have different value for same instance variable.

Every Instance of a class has the same method but it possible that all of them behave differently.

The OS class has 3 Instance variables namely OS NameOS TypeOS Category.

OS
OS_Name
OS_Type
OS_Category
Boot()
Reboot()
scan()

The Boot() method boots one OS which is represented by OS Name for that instance. So if you boot() on one instance you will boot into Debian while on another instance you will boot into Gentoo. The method code, remains the same in either case.

Void Boot() 
	{
	bootloader.bootos(OS_Name);
	}

You are already aware that the program starts to execute just after the main() method. You can pass values into you method.

For example you would like to tell you OS what services to start at boot as:

You are already aware that the program starts to execute just after the main() method. You can pass values into you method. For example you would like to tell you OS what services to start at boot as:
OS.services(apache2);

What you pass into methods are called arguments. You can use a variable with a type and a name inside a method. It is important to pass values with parameter if a method takes a parameter.

OS deb = debian();
deb.reboot(600);

Here the reboot method on the OS passes the value of 600 (reboot machine after 600 sec) as an argument to the method. Till now we have seen method always returning void, which means it don’t return you anything, simply as:

void main()
	{
	…
	…
	}

However you can ask your compiler to get exactly what you are desiring and your compiler won’t return you wrong types. You may simply do like:

int Integer()
	{
	…
	…
	return 70;
	}

You can send more than one value value to a method. You can do this by calling two parameter methods and sending it to arguments. Note variable type and parameter type must always match.

void numbers(int a, int b)
	{
	int c = a + b;
	System.out.print(“sum is” +c);
	}
Declare and Initialize Instance Variables

1. When you don’t know the value to initialize.

int a;
float b;
string c;

2. When the know the value to Initialize.

int a = 12;
float b = 11.23;
string c = tecmint;

Note: A instance variables are often confused with local variables, however there is a very thin line between them to differentiate.

3. Instance Variables are declared inside a class unlike local variables that are declared within a method.

4. Unlike Instance Variables, local variables must initialize before it can be used. The compiler will report error if you use local variable before it is initialized.

Encapsulation

You might have heard about encapsulation. It is a feature of most of the object oriented programming language which makes it possible to bind data and functions into a single component. Encapsulation is supported by class and protects codes from accidental damage by creating a wall around objects and hides their properties and methods, selectively.

We will expand encapsulation in details in the right tutorial when it is required. As of now it is sufficient for you to know What encapsulation is? What it does? And how it does?

That’s all for now.

Day to Day: Learning Java Programming Language – Part I

In 1995 when c++ programming language were widely used. An employee of Sun Microsystem working on a platform called ‘Green‘ Developed a programming language and named it as ‘oak‘.

The name was inspired by an oak tree which he use to see outside of his office windows. Later the name oakwas replaced by Java.

Java Programming language was developed by James Gosling and hence James Gosling has been honoured as the Father of Java Programming Language.

James Gosling - Father of Java Programming

James Gosling – Father of Java Programming

Now the question is, if there already was such a functional programming language (c++) available, why Mr. Gosling and his team needed a different programming language.

Java was intended with the Features:
  1. Write once, run anywhere
  2. Cross Platform Program Development i.e., Architecturally Neutral
  3. Security
  4. Class based
  5. Object oriented
  6. Support for web technologies
  7. Robust
  8. Interpreted
  9. Inheritance
  10. Threaded
  11. Dynamic
  12. High Performance

Before Java was developed, The program written on a computer or for an architecture won’t run on another computer and architecture, hence while developing Java the team focus mainly on cross platform functionality and from there the concept of write oncerun anywhere came, which remains the quote of sun microsystem for a long time.

Java program runs inside JVM (Java Virtual Machine) which adds an extra layer between System and program, which further means extra security. Other programming language prior to Java was not having such feature which means a code being run could be malicious can infect a system or other systems attached to it, however Java maintained to overcome this issue using JVM.

Java is a OOP (Object Oriented Programming) Language. By object oriented feature, it means all the entity is a object which further suggest Real World Object.

When Java was being developed at Sun, coincidentally web technologies has started to take take shape and the Java development was highly influenced with this, and even today web world uses Java more than any other language. Java is strictly an interpreted language, which means Java executes the source code directly by translating the source code in an intermediate form.

Java is robust in nature i.e., it can cope up with errors be in input or calculation. When we say Java is dynamic programming language, we mean to say that it is capable of breaking complex problems into simple problems and then execute them independently.

Java supports threadingThreads are small processes that can be managed independently by operating system scheduler.

Java Support Inheritance, which means relation can be established between classes.

No doubt! Java was developed as a successor to ‘c‘ and ‘c++‘ programming Language hence it inherit a number of features from its predecessor viz., c and c++ with a number of new features.

Learning Java from the point of view of carrier is highly appreciated and one of the most sought after technology. The best way to learn any programming language is to start programming.

Before we go to programming, one more thing we need to know is: the class name and program name should be same, however it can be different in certain condition but by convention it is always a good idea to rename the program as it’s class name.

Javac is the compiler of Java Programming Language. Obviously you should have Java installed and environment variable set. Installing Java on RPM based system is just a click away as on Windows and more or less on Debian based system.

However Debian Wheezy don’t have Java in its repo. And it is a little messy to install Java in Wheezy. Hence a quick step to install on debian is as below:

Installing Java in Debian Wheezy

Download correct Java version for your System and architecture from here:

  1. http://www.oracle.com/technetwork/java/javase/downloads/index.html

Once you’ve downloaded , use the following commands to install in Debian Wheezy.

# mv /home/user_name/Downloads /opt/
# cd /opt/
# tar -zxvf jdk-7u3-linux-x64.tar.gz
# rm -rf jdk-7u3-linux-x64.tar.gz
# cd jdk1.7.0_03
# update-alternatives --install /usr/bin/java java /opt/jdk1.7.0_03/bin/java 1
# update-alternatives --install /usr/bin/javac javac /opt/jdk1.7.0_03/bin/javac 1
# update-alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so mozilla-javaplugin.so /opt/jdk1.7.0_03/jre/lib/amd64/libnpjp2.so 1
# update-alternatives --set java /opt/jdk1.7.0_03/bin/java
# update-alternatives --set javac /opt/jdk1.7.0_03/bin/javac
# update-alternatives --set mozilla-javaplugin.so /opt/jdk1.7.0_03/jre/lib/amd64/libnpjp2.so

For RHELCentOS and Fedora users can also install latest version of Java by going to below url.

  1. Install Java in RHEL, CentOS and Fedora

Let’s move to programming section to learn few basic Java programs.

Program 1: hello.java

class hello{
public static void main (String args[]){
System.out.println("Sucess!");
}
}

Save it as: hello.java. And Compile it and run as shown.

# javac hello.java
# java hello

Sample Output

Sucess!

Program 2: calculation.java

class calculation { 
public static void main(String args[]) { 
int num; 
num = 123;
System.out.println("This is num: " + num); 
num = num * 2; 
System.out.print("The value of num * 2 is "); 
System.out.println(num); 
} 
}

Save it as: calculation.java. And Compile it and run as shown.

# javac calculation.java
# java calculation

Sample Output

This is num: 123
The value of num * 2 is 246

Do it Yourself:

  1. Write a program that ask for your first name and last name and then address you with your last name.
  2. Write a program with three Integer values and perform additionSubstractionMultiplication and Divisionand gets the custom output.

Note: This way of learning will make you know and learn something. However if you face problem in writing programs of ‘Do it Yourself‘ you can come up with your codes and problems in comments.

Day to Day: Learning Java Programming Language – Part 2

Moving a step ahead of the previous article on Day-to-DayJava Programming Part – I. Here in this very post we will be learning control statements and loops in Java, which is very useful in developing an application.

Learning java Programming

Learning java Programming Part – 2

if statement

The if statement in Java works similar to if statement in any other programming language of the world including shell scripting.

Program 3: compare.java

class compare{ 
public static void main(String args[]){ 
int a,b; 
a=10; 
b=20; 
if(a < b)  
System.out.println("a(" +a+ ")is less than b(" +b+")");  
a=a*2;  
if(a==b)  
System.out.println("a(" +a+ ")is equal to b(" +b+")");  
a=a*2;  
if(a>b) 
System.out.println("a(" +a+ ")is greater than b(" +b+")"); 
} 
}

Save it as: compare.java. And Compile it and run as shown.

# javac compare.java
# java compare

Sample Output

a(10)is less than b(20) 
a(20)is equal to b(20) 
a(40)is greater than b(20)

Note: In the above program

  1. A class namely compare is defined.
  2. Two Integers are declared with the initial value of 10 and 20 respectively.
  3. The if statement checks the condition and act according to the statement. Syntax of if statement is if (condition) statement;
  4. System.out.println prints anything and everything that is placed between double quotes. Anything within the quotes are printed as it is, and outside of quotes are treated as variable.
  5. + is a concatenation, which is used to concatenate two parts of a statement.
for loop

If you have any programming experience, sure you would be aware of the importance of loop statements. Here again the for loop statement works similar to the for statement in any language.

Program4: forloop.java

class forloop{ 
public static void main(String args[]){ 
int q1; 
for (q1=0; q1<=10; q1++) 
System.out.println("The value of interger: "+q1); 
} 
}

Save it as: forloop.java. And Compile it and run as shown.

# javac forloop.java
# java forloop

Sample Output

Output:
The value of interger: 0 
The value of interger: 1 
The value of interger: 2 
The value of interger: 3 
The value of interger: 4 
The value of interger: 5 
The value of interger: 6 
The value of interger: 7 
The value of interger: 8 
The value of interger: 9 
The value of interger: 10

Note: In the above program all the statements and codes are more or less identical to the above program, except the for statement.

  1. The above for statement is a loop, which continues to execute again and again till the conditions are satisfied.
  2. The for loop, generally is divided in three chunks of codes separated by semicolon, each of which is very meaningful.
  3. The first part (q1=0, in the above program) is called initialiser. i.e., the above integer, q1 is forced to start with ‘0‘.
  4. The second part (q1<=10, in the above program) is called condition. i.e., the above integer is permitted to go up-to the value of 10 or less than 10, which ever is correct for the given situation.
  5. The Third and the last part (q1++, in the above code, which may be written as q+1) is called iteration.i.e., the above integer value is asked to increase with a value of ‘+1‘ every time the loop is executed, till the condition is satisfied.

Well the above program has only one linked statement to the ‘for loop‘. But in larger and more sophisticated program the loop statement could be linked to more than one statement or say a block of codes.

Program 5: loopblock.java

class loopblock{ 
	public static void main(String args[]){ 
		int x, y=20;		 
		for(x=0;x<20;x=x+2) 
		{ 
		System.out.println("x is: "+x); 
		System.out.println("y is: "+y); 
		y=y-2; 
} 
} 
}

Save it as: loopblock.java. And Compile it and run as shown.

# javac loopblock.java
# java loopblock

Sample Output

x is: 0 
y is: 20 
x is: 2 
y is: 18 
x is: 4 
y is: 16 
x is: 6 
y is: 14 
x is: 8 
y is: 12 
x is: 10 
y is: 10 
x is: 12 
y is: 8 
x is: 14 
y is: 6 
x is: 16 
y is: 4 
x is: 18 
y is: 2

Note: The above program is almost the same as the previous program, except it uses a block of codes linked with for loop. To execute more than one statement/block, we need to put all the statement as “{….codes/block..}” else the code won’t compile correctly.

Yeah we can use ‘x- –‘ or ‘x-1‘ for decrease statement in for loop where required.

After getting a glimpse of whole lot of codes, we need to know a little theory which will be helpful in the later stage of coding’s.

What we have seen till now is: Java programs are a collection of Whitespacesidentifierscommentsliteralsoperatorsseparators and keywords.

Whitespace

Java is a free form language, you need not follow any indentation rule. You could write all the codes on a single line with one whitespace between each token and it will execute correctly. However it will be difficult to understand.

Identifiers

In Java identifiers are class namemethod name or variable name. It could be uppercase, lowercase, their sequence or a combination of all of these with special characters like ‘$‘. However identifiers should never start with a numerical values.

Examples of valid identifiers in Java:

s4, New#class, TECmint_class, etc.
Literals

A constant value in Java is created using literals. e.g., ‘115′ is an integer literal. ‘3.14‘ is a float literal, ‘X‘ is a character constant and “tecmint is the best online site dedicated to foss technology” is a string literal.

Comment

comment has nothing to do with the execution of codes in Java or any other language, however comment in between the codes make them readable and human understandable. It is a good practice to write comments in between the lines of code, where required.

In Java anything between /** and **/ is meant for documentation and is a comment.

Certain separators are defined in Java.

  1. Parenthesis ()
  2. Braces {}
  3. Brackets []
  4. Semicolon ;
  5. comma ,
  6. Period .

Note: Each separator has a meaning and needs to be used where required, You can’t use one in place of other. We will discuss them in details, in the later phase of codes itself.

Keywords

There are 50 reserved keywords defined in Java. These keywords can not be used as names for a variable, class or method as these keywords has predefined meaning.

abstract	continue	for	          new	        switch
assert	        default	        goto	          package	synchronized
boolean	        do	        if	          private	this
break   	double	        implements	  protected	throw
byte	        else	        import	          public	throws
case	        enum	        instanceof	  return	transient
catch	        extends	        int	          short	        try
char	        final	        interface	  static	void
class	        finally	        long	          strictfp	volatile
const	        float	        native	          super	        while

The keyword cons and keywords are reserved but not used. Feeling nervous with all these stuffs. You actually don’t need to be nervous, neither you need to memorise all these stuffs. You will be used to all these when you start living Java.

That’s all for now from me.

Source

HTML5 Mobile Web Development

Installing Netbeans and Java JDK in Ubuntu and Setting Up a Basic HTML5 Project

In this 4-article mobile web development series, we will walk you through setting up Netbeans as an IDE (also known as Integrated Development Environment) in Ubuntu 14.04.2 LTS Trusty Tahr to start developing mobile-friendly and responsive HTML5 web applications.

HTML5 Mobile Web Development

HTML5 Mobile Web Development – Part 1

Following are the 4-article series about HTML5 Mobile Web Development:

Part 1Installing Netbeans and Java JDK in Ubuntu 14.04 and Setting Up a Basic HTML5 Project

A well-polished work environment (as we will later see), autocompletion for supported languages, and its seamless integration with web browsers are, in our opinion, some of Netbeans, most distinguishing features.

Let us also remember that the HTML 5 specification brought many advantages for developers – to name a few examples: cleaner code thanks to many new elements), built-in video and audio playback capabilities (which replaces the need for Flash), cross-compatibility with major browsers, and optimization for mobile devices.

Although we will initially test our applications on our local development machine, we will eventually move our web site to a LAMP server and turn it into a dynamic tool.

Along the way we will make use of jQuery (a well-known cross-platform Javascript library that greatly simplifies client-side scripting), and of Bootstrap (the popular HTML, CSS, and JavaScript framework for developing responsive websites). You will see in coming articles how easy it is to set up a mobile-friendly application using these HTML 5 tools.

After you go through this brief series, you will be able to:

  1. use the tools described herein to create basic HTML5 dynamic applications, and
  2. go on to learn more advanced web development skills.

However, please note that even though we will be using Ubuntu for this series, the instructions and procedures are perfectly valid for other desktop distributions as well (Linux MintDebianCentOSFedora, you name it).

To that end, we have chosen to install the necessary software (Netbeans and the Java JDK, as you will see in a minute) using a generic tarball (.tar.gz) as installation method.

That being said – let’s get started with Part 1.

Installing Java JDK and NetBeans

This tutorial assumes that you already have an Ubuntu 14.04.2 LTS Trusty Tahr desktop installation in place. If you don’t, please refer to Ubuntu 14.04 Desktop Installation article, written by our colleague Matei Cezar before proceeding further.

Since the Netbeans version that is available for download from the Ubuntu official repositories (7.0.1) is a little outdated, we will download the package from the Oracle website to get a newer version (8.0.2).

To do this, you have two choices:

  1. Choice 1: download the bundle that includes Netbeans + JDK, or
  2. Choice 2: install both utilities separately.

In this article we will choose #2 because that not only means a download that is a bit smaller (as we will only install Netbeans with support for HTML5 and PHP), but also will allow us to have a standalone JDK installer should we need it for another setting that does not require Netbeans nor involve web development (mostly related to other Oracle products).

To download JDK 8u45, go to the Oracle Technology Network site and navigate to the Java → Java SE → Downloads section.

When you click on the image highlighted below, you will be asked to accept the license agreement and then you will be able to download the necessary JDK version (which in our case is the tarball for 64-bit machines). When prompted by your web browser, choose to save the file instead of opening it.

Download Java JDK

Download Java JDK

When the download is complete, go to ~/Downloads and extract the tarball to /usr/local/bin:

$ sudo tar xf jdk-8u45-linux-x64.tar.gz -C /usr/local/bin

Extract Java

Extract Java

To install Netbeans with support for HTML5 and PHP, go to https://netbeans.org/downloads/ and click Download as indicated in the following image:

Download NetBeans

Download NetBeans

This will cause your browser to either open the installation shell script or save it to your computer. Choose Save File, then OK:

Save NetBeans Shell Script

Save NetBeans Shell Script

Once done, turn the .sh into an executable file and then run the shell script with administrative privileges:

$ cd ~/Downloads
$ chmod 755 netbeans-8.0.2-php-linux.sh
$ sudo ./netbeans-8.0.2-php-linux.sh --javahome /usr/local/bin/jdk1.8.0_45

From then on, follow the on-screen instructions to complete the installation leaving the default values:

NetBeans IDE Installation

NetBeans IDE Installation

and wait for the installation to complete.

Adding References

That sure looks good, but we still haven’t told our index.html file to use any of those files. For the sake of simplicity, we will replace the contents of that file with a barebones html file first:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>jQuery and Bootstrap</title>
</head>
<body>
 
   <!-- // Your code will appear here. -->

</body>
</html>

Then, just drag and drop each file from the project navigator section to the code, inside the </head> tags, as you can see in the following screencast. Make sure that the reference to jQuery appears before the reference to Bootstrap because the latter depends on the former:

That’s it – you have added the references to both jQuery and Bootstrap, and can now start writing code.

Writing Your First Responsive Code

Let’s now add a navigation bar and place it at the top of our page. Feel free to include 4-5 links with dummy text and don’t link it to any document for the time being – just insert the following code snippet inside the body of the document.

Don’t forget to spend some time become acquainted with the auto-completion feature in Netbeans, which will show you the classes made available by Bootstrap as you start typing.

At the heart of the code snippet below is the Bootstrap container class, which is used to place content inside of a horizontal container which will automatically resize depending on the size of the screen where it is being viewed. Not less important is the container-fluid class, which will ensure that the content within will occupy the entire width of the screen.

<div class="container">
  	<nav class="navbar navbar-default">
    	<div class="container-fluid">
      	<div class="navbar-header">
        	<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          	<span class="sr-only">Toggle navigation</span>
          	<span class="icon-bar"></span>
          	<span class="icon-bar"></span>
          	<span class="icon-bar"></span>
        	</button>
        	<a class="navbar-brand" href="#">Project name</a>
      	</div>
      	<div id="navbar" class="navbar-collapse collapse">
        	<ul class="nav navbar-nav">
          	<li class="active"><a href="#">Home</a></li>
          	<li><a href="#">About</a></li>
          	<li><a href="#">Contact</a></li>
          	<li class="dropdown">
            	<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
            	<ul class="dropdown-menu">
              	<li><a href="#">Action</a></li>
              	<li><a href="#">Another action</a></li>
              	<li><a href="#">Something else here</a></li>
              	<li role="separator" class="divider"></li>
              	<li class="dropdown-header">Nav header</li>
              	<li><a href="#">Separated link</a></li>
              	<li><a href="#">One more separated link</a></li>
            	</ul>
          	</li>
        	</ul>
      	</div><!--/.nav-collapse -->
    	</div><!--/.container-fluid -->
  	</nav>
</div>

Another distinguishing feature of Bootstrap is that it eliminates the need for tables in HTML code. Instead, it uses a grid system to layout content and make it look properly both on large and small devices (from phones all the way to big desktop or laptop screens).

In Bootstrap’s grid system, the screen layout is divided in 12 columns:

Bootstrap Grid Layout

Bootstrap Grid Layout

A typical setup consists of using the 12-column layout divided into 3 groups of 4 columns each, as follows:

Bootstrap Column Layout

Bootstrap Column Layout

To indicate this fact in code, and in order to have it displayed that way starting in medium-size devices (such as laptops) and above, add the following code below the closing </nav> tag:

...
    </nav>
   	 <div class="row">
   	 	<div class="col-md-4">This is the text in GROUP 1</div>
   	 	<div class="col-md-4">This is the text in GROUP 2</div>
   	 	<div class="col-md-4">This is the text in GROUP 3</div>
   	 </div>
</div> <!--Closing tag of the container class -->

You must have probably noticed that the column classes in the Bootstrap grid indicate the starting layout for a specific device size and above, as md in this example stands for medium (which also covers lg, or large devices).

For smaller devices (sm and xs), the content divs gets stacked and appears one above the next.

In the following screencast you can see how your page should look by now. Note that you can resize your browser’s window to simulate different screen sizes after launching the project using the Run project button as we learned in Part 1.

Summary

Congratulations! You must have written a simple, yet functional, responsive page by now. Don’t forget to check the Bootstrap website in order to become more familiar with the almost-limitless functionality of this framework.

As always, in case you have a question or comment, feel free to contact us using the form below.

Creating a Dynamic HTML5 Web Application and Deploying on Remote Web Server Using Filezilla

In the previous two articles of this series, we explained how to set up Netbeans in a Linux desktop distribution as an IDE to develop web applications. We then proceeded to add two core components, jQuery and Bootstrap, in order to make your pages mobile-friendly and responsive.

Create HTML5 Applications and Deploy to Web Server

Create HTML5 Applications and Deploy to Web Server – Part 3

  1. Install Netbeans and Java to Create a Basic HTML5 Application – Part 1
  2. Creating Mobile-Friendly and Responsive Web Application Using jQuery and Bootstrap – Part 2

As you will seldom deal with static content as a developer, we will now add dynamic functionality to the basic page that we set up in Part 2. To begin, let us list the prerequisites and address them before moving forward.

Prerequisites

In order to test a dynamic application in our development machine before deploying it to a LAMP server, we will need to install some packages. Since we are using a Ubuntu 14.04 desktop to write this series, we assume that your user account has already been added to the sudoers file and granted the necessary permissions.

Installing Packages and Configuring Access to the DB Server

Please note that during the installation you may be prompted to enter a password for the MySQL root user. Make sure you choose a strong password and then continue.

Ubuntu and derivatives (also for other Debian-based distributions):

$ sudo aptitude update && sudo aptitude install apache2 php5 php5-common php5-myqsql mysql mysql-server filezilla

Fedora / CentOS / RHEL:

$ sudo yum update && sudo yum install httpd php php-common php-mysql mysql mysql-server filezilla

When the installation is complete, it is strongly recommended that you run mysql_secure_installation to, not surprisingly, secure your database server. You will be prompted for the following information:

  1. Change the root password? [Y/n]. If you already set a password for the MySQL root user, you can skip this step.
  2. Remove anonymous users? [Y/n] y.
  3. Disallow root login remotely? [Y/n] y (Since this is your local development environment, you will not need to connect to your DB server remotely).
  4. Remove test database and access to it? [Y/n] y
  5. Reload privilege tables now? [Y/n] y.

Creating a sample Database and Loading test Data

To create a sample database and load some test data, log on to your DB server:

$ sudo mysql -u root -p

You will be be prompted to enter the password for the MySQL root user.

At the MySQL prompt, type

CREATE DATABASE tecmint_db;

and press Enter:

Create MySQL Database

Create MySQL Database

Now let’s create a table:

USE tecmint_db;
CREATE TABLE articles_tbl(
   Id INT NOT NULL AUTO_INCREMENT,
   Title VARCHAR(100) NOT NULL,
   Author VARCHAR(40) NOT NULL,
   SubmissionDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   PRIMARY KEY ( Id )
);

Create Database Table

Create Database Table

and populate it with sample data:

INSERT INTO articles_tbl (Title, Author) VALUES ('Installing Filezilla in CentOS 7', 'Gabriel Canepa'), ('How to set up a LAMP server in Debian', 'Dave Null'), ('Enabling EPEL repository in CentOS 6', 'John Doe');

Populate Database Table

Populate Database Table

Adding symbolic links in the Web Server directory

Since Netbeans, by default, stores projects in the current user’s home directory, you will need to add symbolic links that point to that location. For example,

$ sudo ln -s /home/gabriel/NetBeansProjects/TecmintTest/public_html /var/www/html/TecmintTest

will add a soft link called TecmintTest that points to /home/gabriel/NetBeansProjects/TecmintTest/public_html.

For that reason, when you point your browser to http://localhost/TecmintTest/, you will actually see the application that we set up in Part 2:

HTML5 Application

HTML5 Application

Setting up a remote FTP and Web server

Since you can easily set up a FTP and Web server with the instructions provided in Part 9 – Install and Configure Secure FTP and Web Server of the RHCSA series in Tecmint, we will not repeat them here. Please refer to that guide before proceeding further.

Turning our application into a Dynamic One

You will probably think that we can’t do much with the sample data that we added to our database earlier, and you are right, but it will be enough to learn the basics of embedding PHP code and the results of queries to a MySQL DB in your HTML5 pages.

First off, we will need to change the extension of the main document of our application to .php instead of html:

# mv /var/www/html/TecmintTest/index.html /var/www/html/TecmintTest/index.php

Then let’s open the project in Netbeans and start doing some modifications.

1. Add a folder to the project named includes where we will store backend php applications.

2. Create a file named dbconnection.php inside includes and insert with the following code:

<?php
    $host = "localhost";
    $username = "root";
    $password = "MyFancyP4ssw0rd";
    $database = "tecmint_db";

    //Establish a connection with MySQL server
    $mysqli = new mysqli($host, $username, $password,$database);

    /* Check connection status. Exit in case of errors. */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $mysqli -> query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

    $records = array();
    $query = "SELECT Title, Author, SubmissionDate FROM articles_tbl;";
    $result = $mysqli->query($query) or die($mysqli->error);
    $data = array();

    while ( $row = $result->fetch_assoc() ){
        $data[] = json_encode($row);
    }
    echo json_encode( $data );
?>

as indicated in the following image:

Create Database Configuration FileCreate Database Configuration File

Create Database Configuration File

This file will be used to connect to the database server, to query it, and to return the results of that query in a JSON-like string to be consumed by the frontend application with a slight modification.

Note that typically you would use separate files to perform each of these operations, but we chose to include all of that functionality in one file for sake of simplicity.

3. In index.php, add the following snippet just beneath the opening body tag. That is the jQuery way of calling an external PHP app when the web document is ready, or in other words, each time it loads:

<script>
    $(document).ready(function(){
        $.ajax({
            url: 'includes/dbconnection.php',
            datatype: 'json',
            type: 'POST',
            success: function(data){
                var output = $.parseJSON(data);
                for(var i =0;i < output.length;i++)
                {
                  var item = output[i];
                  $("#title").append("<br>"+item.Title);
                  $("#author").append("<br>"+item.Author);
                  $("#submissiondate").append("<br>"+item.SubmissionDate);
                }
            }}
        );
    });
</script>

Add jQuery Script

Add jQuery Script

4. Now, add an unique id (same as inside the for loop above) to each line in the div with class row at the bottom of index.php:

<div class="row">
    <div class="col-md-4" id="title" style="text-align: center"><strong>Titles</strong></div>
    <div class="col-md-4" id="author" style="text-align: center"><strong>Authors</strong></div>
    <div class="col-md-4" id="submissiondate" style="text-align: center"><strong>Published on:</strong></div>
</div>

If you now click Run Project, you should see this:

Working Web Application Preview

Working Web Application Preview

Which is essentially the same as the information returned when we ran the query from our MySQL client prompt earlier.

Deploying to a LAMP server using Filezilla

Launch Filezilla from the Dash menu and enter the IP of the remote FTP server and your credentials. Then click Quickconnect to connect to the FTP server:

Upload Files To FTP Server

Deploying Application on Web Server

Navigate to /home/gabriel/NetBeansProjects/TecmintTest/public_html/, select its contents, right click on them and select Upload.

This, of course, assumes that the remote user indicated in Username has write permissions on the remote directory. When the upload is complete, point your browser to the desired location and you should see the same page as before (please note that we have not set up the local MySQL database to the remote host, but you can easily do so following the steps from the beginning of this tutorial).

Web Application Preview

Web Application Preview

Summary

In this article we have added dynamic functionality to our web application using jQuery and a little JavaScript. You can refer to the official jQuery docs for more information, which will be very helpful if you decide to write more complex applications. Wrapping up, we have also deployed our application to a remote LAMP server using a FTP client.

We are excited to hear your opinion about this article – feel free to contact us using the form below.

Tuning Dynamic HTML5 Web Apps Using Open Source Online Tools

As I begin the last article in this series, it is my hope that you have been able to grasp the importance of HTML 5 and mobile-friendly / responsive web development. Regardless of your desktop distribution of choice, Netbeansis a powerful IDE and when used together with basic Linux command-line skills and the tools discussed in Part 3, can help you to create outstanding applications without much hassle.

Tuning Dynamic HTML5 Web Apps

Tuning Dynamic HTML5 Web Apps – Part 4

However, please note that we have only covered the basics of HTML 5 and web development in this series and assumed that you are somewhat familiar with HTML, but the WWW is full of great resources – some of them are FOSS – to expand on what we’ve shared here.

In this last guide we will talk about some of those tools and show you how to use them to add to the existing page we have been working on Beautifying our UI (user interface).

You will recall from Part 2 of this series (“Adding jQuery and Bootstrap to Write a HTML5 Web Application“) that the Bootstrap zip file comes with a directory named fonts. We saved its contents into a folder with the same name inside our project’s SiteRoot:

Bootstrap Fonts

Bootstrap Fonts

As you probably can tell from the above image, Bootstrap includes a set of elements called glyphicons, which are no more and no less the built-in components that provide nice-looking icons for buttons and menus in your applications. The complete list of glyphicons included in Bootstrap is available at http://getbootstrap.com/components/.

To illustrate the use of glyphicons, let’s add some to the navigation bar in our main page. Modify the navigation bar menus as follows. Please note the space between each closing span tag and the menu text:

<li class="active"><a href="#"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> Home</a></li>
<li><a href="#"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span> About</a></li>
<li><a href="#"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> Contact</a></li>

(by the way, the span tags are used here to prevent the icons from getting mixed with other components).

And here’s the result:

Add Navigation Menu

Add Navigation Menu

Glyphicons, though useful, are also limited. And here’s where Font Awesome enters the scene. Font Awesome is an icon / font / css complete toolkit that has the potential to seamlessly integrate with Bootstrap.

Not only you can add a whole lot of other icons to your pages, but can also resize them, cast shadows, change color, and a many other options using CSS. However, since dealing with CSS is out of the scope of this series, we will only deal with the default-sized icons but encourage you at the same time to “dig a little deeper” to discover how far this tool can take you.

To download Font Awesome and incorporate it into your project, execute the following commands (or feel free to go directly to the project’s web site and download the zip file through your browser and decompress it using GUI tools):

# wget http://fortawesome.github.io/Font-Awesome/assets/font-awesome-4.3.0.zip

(yes, the domain name is actually FortAwesome, with an R, so that is not a typo).

# unzip font-awesome-4.3.0.zip
# cp font-awesome-4.3.0/css/font-awesome.min.css /home/gabriel/NetBeansProjects/TecmintTest/public_html/styles
# cp font-awesome-4.3.0/fonts/* /home/gabriel/NetBeansProjects/TecmintTest/public_html/fonts

And add the .css file to the references list at the top of our page, just like we did with jQuery and Bootstrapearlier (remember that you don’t have to type everything – just drag the file from the Projects tab into the code window):

Add Font Awesome

Add Font Awesome

Let’s take the dropdown list in our navigation bar, for example:

Dropdown List

Dropdown List

Nice, right? All it takes is replacing the contents of the existing ul class named dropdown-menu at the bottom of index.php with:

<li><a href="#"><i class="fa fa-pencil fa-fw"></i> Edit</a></li>
<li><a href="#"><i class="fa fa-trash-o fa-fw"></i> Delete</a></li>
<li><a href="#"><i class="fa fa-ban fa-fw"></i> Ban</a></li>
<li class="divider"></li>
<li><a href="#"><i class="i"></i> Make admin</a></li>

Believe me – investing your time in learning how to use these tools will be a very rewarding experience.

Where to Ask for Help

As an IT person, you must be well acquainted with the many resources for help the Internet has made available. Since doing web development is not an exception, here are a few resources that we’re sure you will find useful while tuning your applications.

When dealing with Javascript code (for example, when working with jQuery as we did in Part 2), you will want to use JSHint, an online Javascript quality code checker that aims at helping developers to detect errors and potential problems. When those pitfalls are found, JSHint indicates the line number where they are located and gives you hints to fix them:

JSHint Tool to Detect Errors

JSHint Tool to Detect Errors

That surely looks great, but even with this great automated tool, there will be times when you will need someone else to take a look at your code and tell you how to fix it or otherwise improve it, which implies sharing it somehow.

JSFiddle (an online Javascript / CSS / HTML code tester) and Bootply (same as JSFiddle but specialized in Bootstrap code) let you save code snippets (also known as fiddles) and provide you a link to share them very easily over the Internet (either via email with your friends, using your social network profiles, or in forums).

Summary

In this article we have provided you with a few tips to tune your web applications and shared some resources that will come in handy if you get stuck or want another pair of eyes (and not just one, but many) to take a look at your code to see how it can be improved. Chances are that you may know of other resources as well. We hope that this series have given you a glimpse of the vast possibilities of mobile-friendly and responsive web development.

Source

SUSE OpenStack Cloud 9 – coming soon!

Share with friends and colleagues on social media

Here at SUSE, we’re very excited to let you know that the latest version of SUSE OpenStack Cloud is due to be released later this month. In fact, you might say that we’re on cloud 9.

The main event

Now that I have that dreadful pun out of the way, let me tell you a little bit about this release. Designed and engineered to take the pain out of implementing a software-defined infrastructure, SUSE OpenStack Cloud enables customers to transform their IT infrastructure so they can meet the business challenges of today and tomorrow. Based on the OpenStack Rocky release, SUSE OpenStack Cloud 9 delivers enhanced agility and improved time to value, while simplifying the transition of traditional workloads. New features and improved functionality include:

  • Improved agility with a new user interface that simplifies post-deployment cloud operations. The new day two UI, CLM Admin Console simplifies post-deployment cloud operations for customers choosing the CLM installation of SUSE OpenStack Cloud, through its familiar interface.
  • Simplifying the transition of traditional workloads to OpenStack private cloud and maximizing the value of your existing IT investments. Businesses can now choose to customize their bare metal servers for specific workload performance and use case needs, further simplifying the transition of traditional or business-critical workloads to their OpenStack private cloud.
  • Improved time to value by reducing the complexity of delivering an enterprise-grade software-defined infrastructure. Powered by the OpenStack Rocky release and built on SUSE Linux Enterprise 12 SP4, SUSE OpenStack Cloud takes the complexity out of deploying a mature, stable and robust private cloud that has been designed for mission-critical workloads.

Moving to a software-defined infrastructure is a key part of many organizations’ digital transformation, and increasing numbers of businesses are choosing SUSE OpenStack Cloud to power their software-defined infrastructure. It gives them the business agility they need to compete in today’s market, as well as enabling them to make better use of their existing IT infrastructure for cost benefit, while taking advantage of new business opportunities and rapidly evolving technology trends such as DevOps, containers and AI.

The winning combination

Combining SUSE OpenStack Cloud with SUSE Enterprise Storage makes it easier for businesses to build a software-defined infrastructure with cost-effective, near-infinite storage scalability. Those companies concerned about an IT skills gap delaying their digital transformation may be interested in SUSE Select Services. Offering a 12-month, fixed-price solution combining implementation, consulting, knowledge transfer and premium support to jumpstart their private cloud investment and help them to realize the benefits sooner.

Gonna fly now

One thing’s for sure, SUSE OpenStack Cloud 9 powered by OpenStack Rocky can keep your business going the distance through their IT transformation, and with SUSE Select Services to support them, your internal IT teams won’t be holding out for a hero with a burning heart. Before the final countdown commences though, I’m gonna fly now as there’s no easy way out of these terrible attempts at puns. What’s your favourite tune from the Rocky series of films? In my view, they’re all great and the perfect addition to my workout playlist, but Gonna Fly Now always helps me push a little bit harder on the treadmill!

If you’re visiting Nashville for SUSECON, then please come and say hello to hear more about this upcoming release. We’ll also be at the inaugural Open Infrastructure Summit in Denver at the end of April, so come along there to hear more about SUSE OpenStack Cloud 9 and to hear about how it could help you to take the stress out of your software-defined infrastructure.

Note: OpenStack Rocky is not affiliated with, supported or endorsed by Rocky Balbao. No copyright infringement intended. Other Rockys are available – see Rocky Mountains, Rocky Road, Rocky the Flying Rooster, Rocky and Bullwinkle and Rocky Horror for more details.

Share with friends and colleagues on social media

Source

WP2Social Auto Publish Powered By : XYZScripts.com