Wednesday, 7 December 2016

20 Unix Command Line Tricks


Let us start new year with these Unix command line tricks to increase productivity at the Terminal. I have found them over the years, and I am now going to share with you.
unix-command-line-tricks.001
Deleting a HUGE file
I had a huge log file 200GB I need to delete on a production web server. My rm and ls command was crashed and I was afraid that the system to a crawl with huge disk I/O load. To remove a HUGE file, enter:
> /path/to/file.log
# or use the following syntax
: > /path/to/file.log
 
# finally delete it 
rm /path/to/file.log

Want to cache console output?

Try the script command line utility to create a typescript of everything printed on your terminal.
script my.terminal.session
Type commands:
ls
date
sudo service foo stop
To exit (to end script session) type exit or logout or press control-D
exit
To view type:
more my.terminal.session
less my.terminal.session
cat my.terminal.session

Restoring deleted /tmp folder

As my journey continues with Linux and Unix shell, I made a few mistakes. I accidentally deleted /tmp folder. To restore it all you have to do is:
mkdir /tmp
chmod 1777 /tmp
chown root:root /tmp
ls -ld /tmp

Locking a directory

For privacy of my data I wanted to lock down /downloads on my file server. So I ran:
chmod 0000 /downloads
The root user can still has access and ls and cd commands will not work. To go back:
chmod 0755 /downloads

Password protecting file in vim text editor

Afraid that root user or someone may snoop into your personal text files? Try password protection to a file in vim, type:
vim +X filename
Or, before quitting in vim use :X vim command to encrypt your file and vim will prompt for a password.

Clear gibberish all over the screen

Just type:
reset

Becoming human

Pass the -h or -H (and other options) command line option to GNU or BSD utilities to get output of command commands like ls, df, du, in human-understandable formats:
ls -lh
# print sizes in human readable format (e.g., 1K 234M 2G)
df -h
df -k
# show output in bytes, KB, MB, or GB
free -b
free -k
free -m
free -g
# print sizes in human readable format (e.g., 1K 234M 2G)
du -h
# get file system perms in human readable format
stat -c %A /boot
# compare human readable numbers
sort -h -a file
# display the CPU information in human readable format on a Linux
lscpu
lscpu -e
lscpu -e=cpu,node
# Show the  size of each file but in a more human readable way
tree -h
tree -h /boot

Show information about known users in the Linux based system

Just type:
## linux version ##
lslogins
 
## BSD version ##
logins
Sample outputs:
UID USER      PWD-LOCK PWD-DENY LAST-LOGIN GECOS
  0 root             0        0   22:37:59 root
  1 bin              0        1            bin
  2 daemon           0        1            daemon
  3 adm              0        1            adm
  4 lp               0        1            lp
  5 sync             0        1            sync
  6 shutdown         0        1 2014-Dec17 shutdown
  7 halt             0        1            halt
  8 mail             0        1            mail
 10 uucp             0        1            uucp
 11 operator         0        1            operator
 12 games            0        1            games
 13 gopher           0        1            gopher
 14 ftp              0        1            FTP User
 27 mysql            0        1            MySQL Server
 38 ntp              0        1            
 48 apache           0        1            Apache
 68 haldaemon        0        1            HAL daemon
 69 vcsa             0        1            virtual console memory owner
 72 tcpdump          0        1            
 74 sshd             0        1            Privilege-separated SSH
 81 dbus             0        1            System message bus
 89 postfix          0        1            
 99 nobody           0        1            Nobody
173 abrt             0        1            
497 vnstat           0        1            vnStat user
498 nginx            0        1            nginx user
499 saslauth         0        1            "Saslauthd user"

How do I fix mess created by accidentally untarred files in the current dir?

So I accidentally untar a tarball in /var/www/html/ directory instead of /home/projects/www/current. It created mess in /var/www/html/. The easiest way to fix this mess:
cd /var/www/html/
/bin/rm -f "$(tar ztf /path/to/file.tar.gz)"

Confused on a top command output?

Seriously, you need to try out htop instead of top:
sudo htop

Want to run the same command again?

Just type !!. For example:
/myhome/dir/script/name arg1 arg2
 
# To run the same command again 
!!
 
## To run the last command again as root user
sudo !!
The !! repeats the most recent command. To run the most recent command beginning with “foo”:
!foo
# Run the most recent command beginning with "service" as root
sudo !service
The !$ use to run command with the last argument of the most recent command:
# Edit nginx.conf
sudo vi /etc/nginx/nginx.conf
 
# Test nginx.conf for errors
/sbin/nginx -t -c /etc/nginx/nginx.conf
 
# After testing a file with "/sbin/nginx -t -c /etc/nginx/nginx.conf", you
# can edit file again with vi
sudo vi !$

Get a reminder you when you have to leave

If you need a reminder to leave your terminal, type the following command:
leave +hhmm
Where,
  • hhmm – The time of day is in the form hhmm where hh is a time in hours (on a 12 or 24 hour clock), and mm are minutes. All times are converted to a 12 hour clock, and assumed to be in the next 12 hours.

Home sweet home

Want to go the directory you were just in? Run:
cd -
Need to quickly return to your home directory? Enter:
cd
The variable CDPATH defines the search path for the directory containing directories:
export CDPATH=/var/www:/nas10
Now, instead of typing cd /var/www/html/ I can simply type the following to cd into /var/www/html path:
cd html

Editing a file being viewed with less pager

To edit a file being viewed with less pager, press v. You will have the file for edit under $EDITOR:
less *.c
less foo.html
## Press v to edit file ##
## Quit from editor and you would return to the less pager again ##

List all files or directories on your system

To see all of the directories on your system, run:
find / -type d | less
 
# List all directories in your $HOME
find $HOME -type d -ls | less
To see all of the files, run:
find / -type f | less
 
# List all files in your $HOME
find $HOME -type f -ls | less

Build directory trees in a single command

You can create directory trees one at a time using mkdir command by passing the -poption:
mkdir -p /jail/{dev,bin,sbin,etc,usr,lib,lib64}
ls -l /jail/

Copy file into multiple directories

Instead of running:
cp /path/to/file /usr/dir1
cp /path/to/file /var/dir2
cp /path/to/file /nas/dir3
Run the following command to copy file into multiple dirs:
echo /usr/dir1 /var/dir2 /nas/dir3 |  xargs -n 1 cp -v /path/to/file
Creating a shell function is left as an exercise for the reader

Quickly find differences between two directories

The diff command compare files line by line. It can also compare two directories:
ls -l /tmp/r
ls -l /tmp/s
# Compare two folders using diff ##
diff /tmp/r/ /tmp/s/
Fig. : Finding differences between folders
Fig. : Finding differences between folders

Text formatting

You can reformat each paragraph with fmt command. In this example, I’m going to reformat file by wrapping overlong lines and filling short lines:
fmt file.txt
You can also split long lines, but do not refill i.e. wrap overlong lines, but do not fill short lines:
fmt -s file.txt

See the output and write it to a file

Use the tee command as follows to see the output on screen and also write to a log file named my.log:
mycoolapp arg1 arg2 input.file | tee my.log
The tee command ensures that you will see mycoolapp output on on the screen and to a file same time.

Tuesday, 6 December 2016

New SUSE Linux Enterprise 12 Service Pack 2 Speeds Innovation with Reliability

  SUSE releases SUSE Linux Enterprise 12 Service Pack 2




As enterprises worldwide seek greater competitive advantage and growth via open source technologies, SUSE® today unveiled SUSE Linux Enterprise 12 Service Pack 2 to power physical, virtual and cloud-based mission-critical workloads. The newest version of the world-class SUSE Linux Enterprise Server open source operating system, SUSE Linux Enterprise 12 SP2 will help customers accelerate innovation, improve system reliability, meet tough security requirements and adapt to new technologies. More than two-thirds of the Fortune Global 100 use SUSE Linux Enterprise.
“SUSE Linux Enterprise 12 SP2 has already earned rave reviews from partners and beta testers worldwide,” said Olaf Kirch, SUSE vice president of SUSE Linux Enterprise Engineering. “SUSE is committed to enabling customers to bring their state-of-the-art solutions to market faster by leveraging the latest technologies. They also need to run mission-critical workloads with maximum uptime and proven security. This latest version of SUSE Linux Enterprise helps them do both using all the advantages of open source software.”
Enhancements to SUSE Linux Enterprise 12 SP2 include:
  • Ten-fold increase in packet processing via software-defined networking that combines Open vSwitch with the Data Plane Development Kit. This is a key enabler for telecom providers to efficiently implement virtual network functions. Added to SUSE Linux Enterprise’s broad hypervisor support, the integration of DPDK gives customers a complete virtualization solution for cloud and on-premise deployments.

  • More agile support for SAP applications to ease migration to S/4HANA, accelerate deployment of SAP applications, tune SAP HANA for performance, and create a more resilient and secure SAP environment with enhanced support for SAP HANA clusters, even on geographical levels.

  • Reduced downtime and improved I/O performance through persistent system memory applications using integrated NVDIMMs that save data in seconds and make data immediately available on reboot.

  • Increased ability to implement cost-effective, high performance data analytics on IBM Power Systems LC and OpenPOWER servers, including bare metal support.

  • Time- and resource-saving “skip service packs” functionality, which lets customers skip upgrades of prior service packs and jump straight to SP2 from SUSE Linux Enterprise Server 12.

  • Ongoing FIPS 140-2 certification to meet strict security requirements of federal government, FISMA and financial industry customers.

  • Reduced downtime for large-memory IBM POWER-based systems via minimized memory initialization times for server restarts along with high availability and geo clustering support for IBM POWER.

  • Support for ARMv8-A, including enablement for the Raspberry Pi3, making SUSE Linux Enterprise Server 12 SP2 one of the first commercially available enterprise Linux platforms for this architecture.

  • Support for Intel’s scalable Omni-Path Architecture to deploy high performance computing workloads.

  • Simplified access to the latest packages and technologies via SUSE Package Hub integration with SUSE Customer Center, helping customers seamlessly obtain modules and package updates.

Input from partners including HPE, Intel and others have enabled building NVDIMM capability as an integral component of the SUSE Linux Enterprise Server 12 platform, allowing customers to benefit from early adoption. Scott Farrand, vice president of Platform Software, Hewlett Packard Enterprise, said, “Next-generation applications, especially database and analytics applications, require new levels of performance. Through close collaborative engineering, HPE and SUSE have enabled support for NVDIMM technology on SUSE Linux Enterprise Server 12 SP2, allowing customers to begin achieving and exceeding performance requirements for next-generation applications.”
Barbara Couturier, Lenovo director of Strategic Alliances, said, “SUSE Linux Enterprise continues to be a powerful foundation for the deployment of mission-critical services, benefiting our joint customers with maximized uptime and security on value-added Lenovo hardware.”
Enhanced solutions based on SUSE Linux Enterprise 12 SP2 include:
  • SUSE Linux Enterprise Server

  • SUSE Linux Enterprise Server for SAP Applications

  • SUSE Linux Enterprise Server for z Systems and LinuxONE

  • SUSE Linux Enterprise Server for POWER

  • SUSE Linux Enterprise Server for ARM

  • SUSE Linux Enterprise Server for Raspberry Pi

  • SUSE Linux Enterprise High Availability Extension and Geo Clustering for SUSE Linux Enterprise High Availability Extension

  • SUSE Linux Enterprise Desktop

  • SUSE Linux Enterprise Workstation Extension

SUSE Linux Enterprise 12 SP2 images are also available for public cloud infrastructures, making it easier to offer public cloud services and migrate to public cloud from on-premise environments. For more information about the SUSE Linux Enterprise 12 Service Pack 2 family of solutions, visit www.suse.com/server.

How to Issue WMI Queries from Linux

Querying Windows Management Instrumentation (WMI) to gather information about a computer is second nature on a PC for some. But working with it on Linux not-so-much. Here's what you need to know.
Credit: ShutterstockCredit: ShutterstockAt one time, a "Windows guy," a "Linux guy" and a "security guy" existed in separate silos. IT workers were split into various roles and rarely ventured outside of their role's responsibilities. Now the industry is starting to merge together. DevOps, anyone? So, it's becoming rarer for an administrator just to work with one operating system or one niche.
With this merge comes challenges and features of an administrator's operating system of choice may not exist or may not be as intuitive as one might expect. Windows Management Instrumentation (WMI) is one of those technologies.
To a Windows "guy," WMI is a fact of life. Querying WMI to gather information about a computer becomes second nature on a Windows computer. But attempting to work with WMI on Linux will soon put the brakes on any enthusiast Windows fan. But that needn't be the case.

Monday, 5 December 2016

Hibernate Interview Questions Part 2

1.What is the difference between load() and get()?
load() vs. get() :-
load() get() 
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods. 
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database. 
load() just returns a proxy by default and database won�t be hit until the proxy is first invoked.  get() will hit the database immediately. 

2.What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

3.How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
<id column="USER_ID" name="id" type="java.lang.Long"> 
   <generator class="sequence"> 
     <param name="table">SEQUENCE_NAME</param>
   <generator>
</id>

4.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

5.What do you mean by Named � SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name} 
      FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :
List people = session.getNamedQuery("empdetails")
       .setString("TomBrady", name)
       .setMaxResults(50)
       .list();

6.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">
 <return alias="emp" class="employee">
   <return-property name="empid" column="EMP_ID"/>       

   <return-property name="name" column="EMP_NAME"/>       
   <return-property name="address" column="EMP_ADDRESS"/>
    { ? = call selectAllEmployees() }
 </return>
</sql-query>



7.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
           .add(Restrictions.like("name", "a%") )
           .add(Restrictions.like("address", "Boston"))
    .addOrder(Order.asc("name") )
    .list();

8.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

9.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
  • HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  • Common functions are simplified to single method calls.
  • Sessions are automatically closed.
  • Exceptions are automatically caught and converted to runtime exceptions.

10.How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

11.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>

12.What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

13.What is component mapping in Hibernate?
  • A component is an object saved as a value, not as a reference
  • A component can be saved directly without needing to declare interfaces or identifier properties
  • Required to define an empty constructor
  • Shared references not supported
Example:
Component Mapping

14.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-

sorted collection order collection 
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. 
If your collection is not large, it will be more efficient way to sort it.

source:http://www.developersbook.com/
If your collection is very large, it will be more efficient way to sort it .