Manage Multiple JDKs in Linux: Default & Switch Guide



In the dynamic world of Java development, you often need to manage multiple JDKs in Linux simultaneously. Indeed, this is crucial for:

  • Ensuring Compatibility: Testing your applications across different JDK versions.
  • Supporting Legacy Projects: Maintaining projects that rely on specific, older JDKs.
  • Facilitating Multi-Project Development: Handling projects with diverse JDK requirements.

Therefore, this guide will walk you through the process of installing multiple JDKs and seamlessly managing the default JDK in your Linux environment.

Manage Multiple JDKs in Linux: Default & Switch Guide

1. Installing Multiple JDKs: Preparing Your Environment

To begin, you need to install the desired JDK distributions.

  • Download and Extract: Download the JDK distributions (e.g., OpenJDK, Oracle JDK) from their official websites. Subsequently, extract the downloaded archives to a designated directory, such as /usr/lib/jvm. You can find the latest OpenJDK releases on the Official Oracle JDK website or OpenJDK website.
  • Example: Bashsudo mkdir -p /usr/lib/jvm sudo tar -xzf jdk-11.0.15_linux-x64_bin.tar.gz -C /usr/lib/jvm/ sudo tar -xzf jdk-17.0.7_linux-x64_bin.tar.gz -C /usr/lib/jvm/

2. Setting the Default JDK: Using update-alternatives

Following the installation, you’ll use the update-alternatives command to manage symbolic links and set the default JDK.

  • Create Symbolic Links: Bashsudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk-11.0.15/bin/java" 1 sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk-17.0.7/bin/java" 2 In this case, the priority numbers (1 and 2) determine the order of preference. A lower number signifies higher priority.
  • Configure the Default JDK: Bashsudo update-alternatives --config java This command will display a list of available alternatives. Select the desired JDK version using the arrow keys and press Enter.
  • Verify the Default JDK: Bashjava -version This command should display the version of the currently selected default JDK.

3. Managing JDK Alternatives: Advanced Techniques

Moreover, you can use these commands to manage your JDK alternatives.

  • List Available Alternatives: Bashupdate-alternatives --list java
  • Display Current Default: Bashupdate-alternatives --display java
  • Change Default JDK: Bashsudo update-alternatives --config java
  • Remove an Alternative: Bashsudo update-alternatives --remove java /usr/lib/jvm/jdk-11.0.15/bin/java

4. Setting Default JDK for Specific Users: Customization

Furthermore, if you need to set different default JDKs for individual users, create symbolic links within the user’s bin directory.

  • Example: Bashln -s /usr/lib/jvm/jdk-11.0.15/bin/java ~/bin/java

5. Managing javac and Other Java Tools: Consistency

Similarly, repeat the update-alternatives process for other Java tools like javac, jar, javadoc, etc. This ensures consistency across your Java development environment. In addition, if you want to automate this process, you may find this article on shell scripting in linux helpful.

Important Notes: Best Practices

  • Compatibility: Ensure that the JDK installations are compatible with your system architecture (e.g., x86_64).
  • Updates: Regularly update your JDKs to benefit from the latest security patches and performance improvements.
  • Java Version Managers: Consider using a Java Version Manager (like SDKMAN!) for more advanced and flexible JDK management.

Conclusion: Streamlining Your Java Development Workflow

In summary, by following these steps, you can effectively manage multiple JDKs in Linux and seamlessly switch between them. Thus, this flexibility is crucial for developers working on projects with diverse JDK requirements. Therefore, streamline your Java development workflow today!

Streamlining Java Apps: Effortless Service Management with systemd in Ubuntu



Tired of wrestling with manual start/stop commands for your Java apps as systemd services in Ubuntu? In today’s streamlined Ubuntu environments, systemd stands as the quintessential service manager. Therefore, let’s delve into the process of running your Java apps as systemd services in Ubuntu, simplifying management and ensuring robust automatic restarts.

Imagine the all-too-familiar scenario: you’re immersed in a debugging session, repeatedly tweaking configuration files and restarting your Java application. To terminate the application, you resort to the cumbersome kill [PID] command. Furthermore, your JAR and configuration files reside in disparate directories, forcing you to navigate between them. Starting the application involves the tedious:

Bash

$ java -jar myjar.jar &

Clearly, this workflow becomes frustratingly inefficient. You yearn for a more streamlined approach, one that mirrors the simplicity of managing standard Ubuntu services:

Bash

$ sudo systemctl start my-java-app
$ sudo systemctl stop my-java-app

Thankfully, systemd provides the elegant solution you seek.

Unveiling systemd: The Cornerstone of Modern System Administration

First, let’s solidify our understanding of systemd. systemd is the modern system and service manager that forms the bedrock of contemporary Linux distributions, including Ubuntu. Indeed, it offers a comprehensive suite of features for managing services, ensuring they seamlessly start on boot, gracefully recover from failures, and operate under designated user accounts. Moreover, it provides a standardized and efficient framework for managing system services, enhancing overall system stability. You can learn more about systemd from the official systemd documentation.

Streamlining Java Apps: Effortless Service Management with systemd in Ubuntu

Preparing Your Java Application for Seamless systemd Integration

Before embarking on the configuration process, it’s paramount to ensure your Java application is primed for systemd integration. Specifically, verify that your application can be launched directly from the command line without requiring manual intervention.

Step-by-Step: A Detailed Guide to Configuring Your Java Apps as systemd Services in Ubuntu

Now, let’s embark on a step-by-step journey through the configuration process, transforming your Java application into a resilient systemd service.

1. Crafting the systemd Service File

Firstly, navigate to the /etc/systemd/system/ directory. Then, create a file named my-java-app.service (or a similar descriptive name). Afterward, open the file using a text editor such as sudo nano my-java-app.service.

2. Populating the Service File with Essential Configuration Directives

Next, populate the service file with the following configuration directives, meticulously adjusting paths and variables to match your specific environment:

Ini, TOML

[Unit]
Description=My Java Application
After=network.target

[Service]
User=your_user
WorkingDirectory=/path/to/your/app/directory
ExecStart=/usr/bin/java -jar /path/to/your/app/directory/myjar.jar
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

Specifically, let’s dissect each section:

  • [Unit]: This section encapsulates general information about the service.
    • Description: Provides a human-readable label for the service, aiding in identification.
    • After=network.target: Ensures that the service initiates only after the network stack is fully operational, preventing potential startup issues.
  • [Service]: This section defines the operational parameters of the service.
    • User: Specifies the user account under which the service will execute, enhancing security and process isolation.
    • WorkingDirectory: Sets the working directory for the service, ensuring that file access occurs within the correct context.
    • ExecStart: Specifies the precise command to launch the Java application, including the full path to the Java executable and JAR file.
    • Restart=on-failure: Configures systemd to automatically restart the service if it encounters an unexpected termination.
    • RestartSec=10: Sets a 10-second delay before systemd attempts to restart the service, preventing rapid restart loops.
  • [Install]: This section defines the service’s activation behavior.
    • WantedBy=multi-user.target: Enables the service for multi-user systems, ensuring it starts during normal system operation.

3. Substituting Placeholders with Your Environment-Specific Values

Subsequently, replace the placeholders /path/to/your/app/directory, myjar.jar, and your_user with the actual paths and user specific to your setup. Ensure that these values are accurate and reflect the correct locations.

4. Reloading systemd to Register the New Service Configuration

Then, reload systemd to register the newly created service configuration:

Bash

$ sudo systemctl daemon-reload

5. Initiating Your Java Application Service

Next, initiate the service using the following command:

Bash

$ sudo systemctl start my-java-app

6. Enabling Your Service to Automatically Start on System Boot

Also, enable the service to automatically start upon system boot:

Bash

$ sudo systemctl enable my-java-app

7. Terminating Your Java Application Service

Similarly, terminate the service when necessary:

Bash

$ sudo systemctl stop my-java-app

8. Verifying the Operational Status of Your Java Application Service

Finally, verify the operational status of your service to ensure it’s running as expected:

Bash

$ sudo systemctl status my-java-app

The Compelling Advantages of Leveraging systemd for Java Application Management

Indeed, there are numerous compelling advantages to using systemd for managing your Java applications.

  • Simplified Management Paradigm: Start, stop, and restart your Java application with intuitive, standardized commands.
  • Automatic Restart Functionality: systemd automatically restarts your application in the event of a crash, ensuring high availability.
  • Seamless System Boot Integration: Your application seamlessly starts when the system boots, eliminating manual intervention.
  • Enhanced Security Through User Context Management: Run your application under a designated user account, bolstering security and process isolation.
  • Comprehensive Logging via journalctl: Access detailed logs using journalctl, simplifying debugging and troubleshooting.

Essential Considerations for systemd Service Configuration Best Practices

Remember, systemd is the default service manager for modern Ubuntu systems. For advanced configurations, refer to the official systemd documentation. Additionally, always conduct thorough testing of your service configuration in a development environment before deploying it to production. If you’re also interested in managing other system processes, you might find our article on Basic Linux Commands helpful.

Conclusion: Empowering Your Java Application Management with systemd’s Efficiency

In summary, running your Java apps as systemd services in Ubuntu significantly streamlines its management. No longer will you grapple with manual PID hunting or tedious command-line operations. With a few straightforward steps, you can transform your Java application into a robust and easily managed service. Therefore, embrace systemd’s efficiency and elevate your workflow today!

Streamline Your Java App: Running it as a Service with Upstart in Ubuntu



Streamline Your Java App: Running it as a Service with Upstart in Ubuntu

Want to simplify managing your Java application as a service with Upstart in Ubuntu?

Hi, one day, while I was deep into my Java project, I found myself in a repetitive cycle of debugging. Specifically, I’d tweak configuration files, restart the application, and then repeat the process. To stop my Java application, Iā€™d hunt down the PID and use the trusty kill [PID] command.

Moreover, my application’s JAR file and configuration files lived in separate directories. Therefore, every time I needed to change a setting, Iā€™d navigate to CONF_DIR, make my edits, and then jump back to APP_HOME_DIR to fire up the application with:

Bash

$ java -jar myjar.jar &

Clearly, this process, as you can imagine, quickly became tedious. I longed for a simpler way, something that a typical user could easily manage. In essence, I wanted to start and stop my Java application just like any other Ubuntu service, using:

Bash

$ service MY_JAVA_APP start|stop

Fortunately, I found a solution!

Understanding Upstart: Your Service Management Ally

First, let’s talk about Upstart. Ubuntu, in its older versions, relied on Upstart for service management. Although Systemd is now more prevalent, Upstart is still relevant and a fantastic tool to learn. Indeed, it allows you to define how your application should start, stop, and restart, giving you that seamless ā€œserviceā€ feel. For more information on Upstart, you can refer to the official Ubuntu documentation: Upstart Documentation

Step-by-Step: Setting Up Your Java Application as a Service with Upstart in Ubuntu

Now, let’s dive into the practical steps to configure your Java application as a service with Upstart in Ubuntu.

1. Creating the Upstart Configuration File

Firstly, navigate to /etc/init/. Then, create a file named my-java-app.conf (or something similar). Afterward, open the file with a text editor (like sudo nano my-java-app.conf).

2. Populating the Configuration File

Next, add the following content, adjusting paths and variables as needed:

Code snippet

description "My Java Application"
author "Your Name"

start on runlevel [2345]
stop on shutdown

respawn
respawn limit 5 30

setuid your_user
setgid your_user

env APP_HOME_DIR=/path/to/your/app/directory
env CONF_DIR=/path/to/your/config/directory
env JAR_FILE=myjar.jar

exec java -jar $APP_HOME_DIR/$JAR_FILE
chdir $APP_HOME_DIR

# Optional: Log output
# console log
# console output

Specifically, here’s an explanation:

  • description and author: Provide metadata.
  • start on runlevel [2345]: Starts the service on boot in runlevels 2, 3, 4, and 5.
  • stop on shutdown: Stops the service during system shutdown.
  • respawn: Restarts the service if it crashes.
  • respawn limit 5 30: Limits respawns to 5 times within 30 seconds.
  • setuid and setgid: Runs the service as the specified user, enhancing security.
  • env: Sets environment variables for your application.
  • exec: Specifies the command to run your Java application.
  • chdir: Changes the working directory.
  • console log and console output are optional, but useful for debugging.

3. Replacing Placeholders

Subsequently, replace /path/to/your/app/directory, /path/to/your/config/directory, myjar.jar, and your_user with your actual paths and user.

4. Starting Your Service

Then, use the command: sudo service my-java-app start.

5. Stopping Your Service

Similarly, use the command: sudo service my-java-app stop.

6. Checking Service Status

Also, use the command: sudo service my-java-app status.

7. Restarting Your Service

Finally, use the command: sudo service my-java-app restart.

The Benefits of Using Upstart: Why It Matters

Indeed, there are many benefits to running your Java application as a service with Upstart in Ubuntu.

  • Simplified Management: Start, stop, and restart your Java application with simple commands.
  • Automatic Restart: Upstart automatically restarts your application if it crashes.
  • Run on Boot: Your application starts automatically when the system boots.
  • Security: Run your application under a specific user account.
  • Logging: Easily capture application logs.

Important Notes: What to Keep in Mind

Remember, for modern Ubuntu systems, Systemd is the default. If you are interested in learning about systemd, check out this similar article using systemd. However, understanding Upstart can be beneficial, especially when working with older systems. Additionally, always ensure your Java application is configured correctly and tested before deploying it as a service. For advanced configurations, refer to the Upstart Documentation.

Conclusion: Streamlining Your Workflow

In summary, running your Java application as a service with Upstart in Ubuntu significantly simplifies its management. No longer will you need manual PID hunting or tedious command-line operations. With a few simple steps, you can transform your Java application into a robust and easily managed service. Therefore, give it a try, and streamline your workflow today!

Beyond Tables: Diving into the NoSQL World with MongoDB



Beyond Tables: Your Gateway to NoSQL with MongoDB

The digital realm is in perpetual motion, and consequently, traditional relational databases often struggle to keep pace with the demands of modern applications. Therefore, if you’re building dynamic, scalable applications that grapple with diverse and rapidly evolving data, then it’s time to explore the world of NoSQL, where MongoDB provides a compelling and approachable entry point.

Demystifying NoSQL: Beyond the Acronym

Initially understood as “non-SQL” or “non-relational,” NoSQL has now matured to signify “Not Only SQL.” In essence, as Wikipedia succinctly puts it, a NoSQL database (i.e. MongoDB) provides a mechanism for storing and retrieving data modeled in ways that extend beyond the rigid tabular relationships found in relational databases. Specifically, these systems optimize performance for data-intensive operations on vast datasets, encompassing tasks like searching, sorting, full-text search, and map-reduce. While you won’t write traditional SQL queries, instead, each NoSQL database offers its own unique interface, tailored to its specific features and data model.

Why the Paradigm Shift? Unpacking the Core Advantages

The advantages of NoSQL become readily apparent when juxtaposed with relational databases:

  • Adaptive Data Models: NoSQL databases offer a significantly more flexible data model, which is crucial for accommodating the structured, unstructured, and semi-structured data that pervades today’s agile development environments. Moreover, this adaptability empowers developers to iterate rapidly, free from the constraints of rigid schema definitions.
  • Seamless Horizontal Scalability: NoSQL systems inherently support horizontal scalability, thus enabling you to effortlessly handle escalating data volumes and traffic. Consequently, businesses can scale their applications to meet burgeoning demands without incurring substantial infrastructure overhauls.
  • Optimized Performance: Tailored for specific data operations, NoSQL databases frequently deliver superior performance, particularly for high-volume read and write operations. As a result, applications respond with greater agility, providing a more seamless and responsive user experience.

Developers engaged in agile sprints encounter rapidly changing data types and massive data volumes. Therefore, NoSQL databases directly address these challenges by providing the necessary flexibility and scalability for contemporary applications.

A Concise Tour: Navigating the Diverse NoSQL Landscape

The NoSQL ecosystem encompasses a diverse array of database types, each meticulously optimized for distinct use cases:

  • Key-Value Stores (Redis, Riak): These databases excel at storing and retrieving data as key-value pairs, rendering them ideal for caching and session management. They provide exceptional speed for rapid data retrieval and storage.
  • Wide-Column Stores (Cassandra, HBase): Designed for querying extensive datasets, these databases store data in columns rather than rows, making them exceptionally well-suited for analytics. They efficiently manage massive data volumes with remarkable proficiency.
  • Graph Databases (Neo4J, Giraph): These databases organize data as graphs, thereby providing an intuitive representation of relationships and networks, such as social connections. They empower users to execute complex relationship queries with ease.
  • Document Databases (MongoDB, CouchDB): These databases store data in flexible documents (like JSON or BSON), which enables the creation of complex data structures and facilitates seamless data evolution. They empower developers to build dynamic and adaptable applications.

Introducing MongoDB: Your Streamlined Path to Document Databases

MongoDB, a prominent document database, distinguishes itself through its comprehensive feature set, rapid time-to-market, global scalability, and unwavering high availability. Indeed, it serves as a popular choice for mobile, web, gaming, ad tech, IoT, and other applications that demand low-latency data access at any scale.

Dissecting MongoDB: Unveiling its Core Strengths

  • Document-Centric Design: MongoDB stores data in flexible, JSON-like BSON documents, which allows for dynamic schemas. This, in turn, allows developers to quickly adapt to evolving data requirements.
  • Scalability and Performance Optimization: Designed for horizontal scaling, MongoDB excels in managing large datasets and high-traffic loads. It provides efficient data distribution and replication, ensuring optimal performance.
  • Intuitive Developer Integration: Its intuitive document model and extensive driver support simplify integration with various programming languages. Developers can seamlessly integrate it into their existing workflows with minimal friction.
  • Robust Querying Capabilities: MongoDB offers a comprehensive query language for complex data retrieval and analysis. Users can execute sophisticated data manipulations with remarkable precision.

Practical Implementation: Getting Started with MongoDB

  1. Seamless Installation: Download and install MongoDB directly from the official website.
  2. Interactive Exploration: Interact with your database through the mongosh shell.
  3. Database and Collection Establishment: Create databases and collections using the use and db.createCollection() commands.
  4. Data Insertion Techniques: Employ db.collection.insertOne() and db.collection.insertMany() to add documents to your collections.
  5. Data Retrieval Methods: Retrieve data using db.collection.find() and a variety of query operators.
  6. Data Modification and Deletion: Modify and delete data with db.collection.updateOne(), db.collection.updateMany(), and db.collection.deleteOne() commands.

Where MongoDB Thrives: Ideal Use Cases Explored

  • Applications with evolving schemas benefit from MongoDB’s inherent flexibility.
  • Real-time analytics and data visualization applications leverage its performance capabilities.
  • Content management and e-commerce platforms capitalize on its scalability.
  • Mobile and IoT applications rely on its efficient data handling.
  • Applications demanding high scalability and performance find MongoDB to be an ideal solution.

The NoSQL paradigm, with MongoDB as a prime example, offers a powerful and adaptable alternative to traditional databases. Therefore, embrace the evolving data landscape, explore its diverse capabilities, and craft the data-driven applications that will define the future.

References:

NoSQL – Wikipedia

MongoDB

Persist/Share tomcat session state between multiple instances



In this article, I am going to explain how can you persist/share tomcat session state between multiple instances, and improve your site performance.

Persisting your session state outside of the tomcat servers is a very common and recommended configuration for large scale websites. This is usually done in pursuit of an architecture style called Shared Nothing.

In my post configuring multiple tomcat application servers with Apache HTTP server I’ve explained how to load balance multiple tomcat with apache web server. There is a common problem user found while load balancing with multiple tomcat servers, of sticky and non-sticky sessions on tomcat. So what is these sticky and non-sticky session actually?

lets have an example, suppose we have three tomcat servers to serve the request for our website behind a single apache server. And all the web request will come to apache server and the load balancer will decide which actual tomcat server will serve the request.
Now suppose we have three request request_A, request_B, and request_C, now what the load balancer should do to serve these requests? Should these requests served by different tomcat server because we also have three tomcat servers, or should these all go to same server? Here comes the role of sticky and non-sticky sessions.

think about if the request_A is for login and request_B is for user_dashboard page, and request_C is some other user’s page request, and what happened if request_A(login) served from server-1 and request_B(dashboard) served from server-2? is the dashboard will be served to the user or server-2 will send user a login page because of no active logged-in session on the server.

Sticky Session

Sticky session refers to a common feature of many load balancing solutions for handling session based web requests.
In case of sticky session, load balancer manage and route all the requests for a particular session to the same tomcat server that executed the first request for that session.

Sticky session: same session request will be served from same tomcat

Non-sticky Session

In case of non-sticky session all requests can be served from different tomcat servers, and each server will create a new session object for the request to serve. These three sessions are purely independent and doesn’t know about each other, and there is no direct way of knowing what is there in the session object of the other tomcat server.

This post is about, how to synchronize between these server sessions, and how to write/read the session data into a layer which is common to all.

non-sticky session are concurrent by nature, and when you are using parallel requests they will be executed by different tomcat servers and session will be used concurrently due to non-stickyness. But if you are having concurrent parallel requests that might change the session, you need to implement/use some kind of synchronization or session locking mechanism.

Non-sticky session: all requests served from different tomcats

Persist/share tomcat session state

There are many solutions exists to persist/share tomcat session state between multiple instances. Some most common and widely used solutions are: database, memcache, cassandra, redis, mongo, etc.

Personally I didn’t support for database to store session state, as persisting sessions in the database limits your scalability. If you still want to store session in a database and scalability is not that important for you, I prefer to use a combination of database + any caching platform.

Persist/share tomcat session state between multiple instances

I’ve written separate posts for some commonly usedĀ solutions, because writing in a single post will make this post very large, so follow the corresponding post link for more details.

  • Manage tomcat session replication using memcached (coming soon)
  • Manage tomcat session replication using cassandraĀ (coming soon)
  • Manage tomcat session replication using redisĀ (coming soon)
  • Manage tomcat session replication using mongoĀ (coming soon)

They all works good, and this is up to you which one suits you the best.

References:

Shared Nothing Architecture

Load Balancing

Replication aware JDBC connection in java and MySQL



Hi,

recently I was reviewing the code a project which was having some database issues, while the review I found that the project environment was setup with the MySQL with one master node and two slave node, and I was surprised that in the code they have used the default JDBC driver forĀ database connectivity which actually uses on single node for all read/write operations.

When asked to developer about the reason of using the default driver for database connectivity, he actually don’t knows that the default JDBC connector does not support replication aware connection. So I’ve realised that many of the developers actually don’t know about the replication aware JDBC connection driver, and I’ve decided to write this post.

There areĀ very little difference between default JDBC connector which support single node mysql connection and ReplicationAware JDBC Connector which is used to create Replication aware JDBC connection using multi node mysql setup.

1) The DriverClass

As you all know that for different type of connection we need to load different driver class. The default JDBC Connector class usesĀ com.mysql.jdbc.DriverĀ driver class and ReplicationAware driver usesĀ com.mysql.jdbc.ReplicationDriver driverĀ class for connection.

2) The connection string

As in default JDBC connection we have only single node and in replication environment we can have n number of nodes, so our connection string will also be different for both connections.

while using default jdbc connector we use connection string as

jdbc:mysql://[database host][:port]/[database_name][?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

and forĀ replication aware jdbc connector we have to provide all server’s ip including master and slaves

jdbc:mysql:replication://[master host][:port],[slave host 1][:port][,[slave host 2][:port]]...[/[database_name]][?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

thats it šŸ™‚

you have done it. its the only difference between default JDBC connector and ReplicationAware JDBC connector.

See MySQL documentation here for list of configuration properties that can be appended to the JDBCĀ URL.

One more thing that how to ensure that your operations redirecting to master and slave correctly:

1) Standalone Application:

if you are using standalone application then just call connection.setReadOnly(false) before any transaction and your all read/write operationsĀ will execute on master node and set readOnly flag to true if you want to execute queries from slave. ReplicationDriver will take care of your transactions and pick a slave from the list to execute query on a slave node. (Read configuring load balancing with connector/J)

2) Spring transactions:

If you are working with Spring, just add @TransactionalĀ annotation to the method with readOnly flag.

For read/write operations on master node, use @Transactional(readOnly = false) and all the database operations will go to the master only.
For read only operations with slave node, use @Transactional(readOnly = true) and all the database operations willĀ go to the slave.

 

References:

MySQL Replication with Connector/J

MySQL Configuration Properties for Connector/J

 

Helpful bash aliases for any Unix/Linux user



Aliases can be very helpful for any linux user, and after writing my last post “How to create custom command in Unix/Linux” I want to share these helpful bash aliases for any unix/linux user.

List in long format

alias ll=’ls -l’

Clear the screen

alias c=’clear’

Clear the history and screen

alias hcl=’history -c; clear’

use Bye to exit

alias bye=’exit’

Some change directoryĀ options

alias ..=’cd ..’

alias …=’cd ../..’

alias ….=’cd ../../..’

alias …..=’cd ../../../..’

Display path info

alias path=’echo -e ${PATH//:/\n}’

Display current Date/Time or Both

alias now=’date’

alias nowtime=’date +”%T”‘

alias nowdate=’date +”%d-%m-%Y”‘

Open last modified file in VIM

alias Vim=”vim ‘ls -t | head -1′”

Show all running java processes

alias psjava=’ps -ef | grep java’

If you are a regular windows user, create windows version of linux commands

alias cls=’clear’

alias dir=’ls -l’

alias chdir=’cd’

alias md=’mkdir’

alias copy=’cp’

alias rename=’mv’

alias move=’mv’

alias del=’rm -i’

alias rd=’rmdir’

alias deltree=’rm -r’

I think these alias can be helpful for you. There are many more but I’ve shared those I think are very useful for any Unix/Linux user.

References:

Alias Command

 

How to create custom commands in Unix/Linux



Few days ago one of my friend told me that the work on linux is so difficult, because he didn’t remember the complex commands of linux and every time when he want to do some debugging on their linux server he always need to google some commands first, so I’ve decided to write this postĀ “How to create custom commands in Unix/Linux”.

There are many ways to do this, I’ve explained some of the easiest way to create custom commands.

  • using a bash/shell script
  • using alias command

Using a bash/shell script

A bash/shell script is a linux program that can be run by a UNIXĀ shell. You can learn more about shell script on wikipedia. we are not here to learn about shell script. I assume you already have a basic knowledge of writing shell scripts.

So, we can learn creating custom command using a simple example.

Suppose you want to create a custom command for printing system’s date and time.

create a file calledĀ dt.sh anywhere on your machine using any text editor, i.e. /home/girishgaurav/dt.sh or just name the script what you want to type in to the terminal.


give it the execute permission using

chmod 777 /home/girishgaurav/dt.sh

you done half way, and its really that easy šŸ™‚

now you have two choices to configure this script to be used as a command:

  1. move this script to /usr/bin directory and you just done everything and your custom command named dt is ready to use. just type dt on the shell and see the output.

$ dt

Fri Dec 5 22:49:05 IST 2014

  1. for advance user who don’t want to mix system’s command with your own, you can create a separate directory for your custom commands:
    create a directory called commands in your home directory, i.e. /home/girishgaurav/commands/ or whatever you like and update your path variable to include this commandsĀ directory.

now just move the dt.sh to the above created directory and your custom command is ready šŸ™‚

 

Using alias command

The alias command is very useful to create your custom commands. The format is alias name=’command’

Now if you want to do our previous datetime example using alisas, it is more simple than writing a bash script.


and you are done, your custom command is created, is that so easy šŸ™‚

No! it’s not that easy. You’ve created your custom command for the current shell lifetime, and whenever you exit from the shell your command will no longer available for the next time.

So, for permanent, you need to do some more…

create a file called .bash_aliasesĀ in your home directoryĀ using any text editor or using touch command, i.e. touchĀ ~/.bash_aliases

Now you all done with your custom commands and you can create any command that you want.

Here are some useful aliases that can be helpful for any linux user.

References:

Bash/Shell Script

Alias Command

How to enable garbage collection logging (GC logs) in Apache tomcat



In this article I’ll provide information about how to enable garbage collection logging (GC logs) in Apache tomcat.

GC logs are very important when you are debugging an application. GC logs helps to analyse how your program uses the memory.

GC logs also helps to findĀ how often garbage collector cleans the memory for unused objects.

So, you can enable garbage collection logging in few simple steps, that are as follows:

for this you need a file named setenv.sh in the $TOMCAT_HOME/bin directory. Create one if it doesn’t exists.

setenv.sh is executedĀ when Apache Tomcat is started and sets the JVM options needed to enable garbage collection logging.

 

Restart Apache Tomcat to enable the changes.

look into tomcat’s logs directory you will find gc.log file, and you can analyse your GC logs šŸ™‚

Ā References:

http://tomcat.apache.org

Java VM Options

 

Send error logs through email using log4j SMTP appender



recently I was reading about Apache log4j appenders. and found log4j SMTPAppender which sends an e-mail when a specific logging event occurs, typically on errors or fatal errors. That timeĀ I got idea to write this post to send error logs through email using log4j SMTP appender.

for a developer error logs are very important. and it is very helpful for any developer to deliver error logs directly in their inbox.

So, you can add a simple SMTP appender entry in log4j configuration file and get error logs directly in your inbox.

 

References:

Log4j SMTPAppender

Official log4j Homepage

 

Load more