Select Page

How to Migrate a WordPress Website to a New Web Server and Web Host Easily Using All-in-One WP Migration Plugin

At some point in time you’re going to need to migrate a WordPress website from one web server to another web server. Whether that is because you’re moving your own website to another web server, or if you are moving your WordPress website from WordPress.com over to your own self-hosted WordPress setup on your web server.

Thankfully there is a really handy plugin available which allows you to easily migrate your WordPress website with relative ease, and that plugin is called All-in-One WP Migration. But, the WordPress migration is just one part of the process and you need to make sure you’ve got your activities in line to avoid any disruption to your website. We’ve already covered topics such as How to Migrate a Web Server Seamlessly with Zero Downtime and How to Migrate an Ecommerce Website between Servers with Zero Downtime previously, so to avoid repeating a lot of the other considerations you need to take into account we’ll be omitting them from this blog post. So we’ll be purely focusing on how to use the All-in-One WP Migration plugin.

 

Step 1 – Download your Website

Firstly, download and install the All-in-One WP Migration plugin via the usual route on the website you are looking to migrate elsewhere. Once installed go to, WordPress Admin > All-in-One WP Migration > Export and select where you would like to export the website to. I’d recommend exporting to File as this will download the website to the computer you are doing this work on. Exporting to File will make your life a little easier in the next step which is to import the website into a new installation.

This option will download your entire website including files and database content.

 

Step 2 – Install WordPress on the New Web Server

Now you need to prepare the new web server. Ideally you’d do this before so you have time to iron out any kinks. You need to install WordPress via the usual mechanism you do this. This can vary between servers and web hosts or using the famous WordPress one-click-install option.

Once you’ve installed WordPress on the new web server you’ll need to  install the All-in-One WP Migration plugin again.

 

Step 3 – Upload your Backup File

Now it’s time to upload the backup file from Step 1 to your WordPress installation on the new web server as outlined in Step 2. Important to note that many web servers out of the box limit the file upload size to around 2mb, so it’s likely you’ll need to temporarily increase the max_file_size and max_post_size settings within your php.ini file to make sure it is large enough to handle the upload.

To import your backup file simple navigate to, WordPress Admin > All-in-One WP Migration > Import, and you can import your backup file easily;

Once this has complete you’ll need to login to the website again as the default username and password you created in Step 2 will have been overwritten by the username and password that you used on the website when it was hosted on the old web server.

 

Summary

And it really is that simple to migrate a WordPress website between web servers or from WordPress.com over to a self-hosted version of WordPress. Naturally there are a lot of nuances along the way when working with web servers, DNS and file transfers so if you haven’t done this before make sure you give this a go on a test website initially. For low traffic websites the risk is extremely low. But for high traffic websites, ecommerce websites or heavily integrated websites then you need to plan these activities in a lot more detail to ensure its clear what the steps are to complete this successfully in the first run. There are often a lot more things to think about along the way, for example you may have a Mail Server or FTP server or non-WordPress databases also running on the old web server – you need to consider how you’re going to migrate these things as part of the process too if you’re using those. Some setups are simpler than others, but always consider as much as you can to minimise any issues during a migration.

How to Use the Vi Text Editor on Linux Guide for Humans

If you can remember all the cryptic commands within the Vi text editor on Linux then you are some kind of genius. For us mere mortals, the quickest way to edit files on Linux is to bin off Vi and move over to Nano. There, I said it, get over it. Nano is better than Vi hands down. 

But in the unfortunate event you need to do a bit of Vi work before you can move over to Nano, for example to configure a network configuration file or to configure a Yum repositories configuration file for example, then you need to know how to work with Vi so you can get through that painful process as quick as possible. 

Here are some handy Vi commands;

  • Open a file: vi filename.txt
  • Edit the file – aka. go into ‘insert mode’: Press the letter ‘i’ once you have opened the file
  • Change what ever you need to do as usual
  • Exit from Insert Mode: Press ESC
  • Prepare to exit the file: Press colon :
  • Now save and exit the file: Press, wq, then enter
  • Whoops I messed up: Within Vi there are so many commands that seem to just utterly break the editor unless you know what they do that is can be difficult to exit out of the thing. If in doubt press ESC or CTRL + Q or CTRL + C and you should get back to where you need. Then exit the file without saving by pressing, :, q!, enter

I mean, simple, right?!?! Anyhow, that’s how you quickly edit the files you need and recover from when Vi has gone a bit crazy. 

 

How to Install Nano Editor on CentOS 7

Out of the box on CentOS 7 the default file editor is Vi, not Nano. And for any humans around, using Vi is beyond the reach of the mere mortals. Hey, if you can use Vi, then great, you can be on your merry way. But for the average user (like me!) then Nano is by far the easier option when it comes to working with editing files on Linux and CentOS 7. 

Thankfully CentOS 7 also comes with Yum installed out of the box which is quite handy. Although if you’re playing with a complete fresh install, make sure your CentOS 7 box can connect to the internet as Ethernet is disabled out of the box too. I mean, who needs to access the internet, right…? So, assuming your all good to go based on the above, simply run the following command to get Nano installed on your system;

yum install nano

And that’s it, your download will start and you’ll be good to use Nano in no time at all. 

Handy Database Design for Records to Track Created Date Time and Updated Date Time

A common requirement for any project is to track the created and updated date/time stamp information. Thankfully with MySQL this is a relatively straight forward task… well, at least at the pure database level.  

It is always recommended to track when your records were created and updated within all tables in your database as you can guarantee that at the point when you need it most, if you don’t have it you’ll regret not having it. Particularly when debugging problems and investigating issues.

Databases rarely live in isolation these days and there are many ways of logging the created and updated times. For example, you could within your web application actually generate the timestamp for all of your Insert and Update statements throughout your codebase and that is one perfectly good way of doing it. But let’s be honest, who has time for that. This approach comes with a  lot of overhead for basic requirements although it is often essential to go down this approach for more complex requirements. But for now, let’s keep things simple.

MySQL is extremely powerful when it comes to managing your data. The two commands we’re going to take a look at for this are;

  • DEFAULT
  • ON UPDATE

 

DETAULT Command

As you can probably imagine, this defines the default value for a column in your table. This allows you to assign a default value of your choosing based on the data type. In this case, a TIMESTAMP field which tracks the date and time. For this you can set the default to be the CURRENT_TIMESTAMP which will automatically populate your column created_date_time with the current timestamp whenever a new row is inserted.

 

ON UPDATE Command

And you can probably guess what this command does too…. It does something whenever a row of data is updated. You can only have one column per table that uses the ON UPDATE command so use it wisely. Again, you simply say what you want to do ON UPDATE, in this case you again want to store the CURRENT_TIMESTAMP against the field updated_date_time.

 

Example Alteration to a Table

Below you can see an example of how you can alter one of your database tables to have the created_date_time and updated_date_time columns with the handy MySQL features turned on so that you never have to worry about when the record was created or updated.

ALTER TABLE your_table_name ADD COLUMN created_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE your_table_name ADD COLUMN updated_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

How to Deploy a Java WAR File without Tomcat Manager using cPanel

For those core Java developers you will be very comfortable utilising the power of the Tomcat Manager to deploy your applications to your servers. But what happens when you’re working on a server that doesn’t have the usual Tomcat Manager available for you to use, just how do you go about deploying your application easily?

Thankfully, it is fairly straight forward to do, it just requires a couple more steps to get this working.

Ultimately your .war file for your Java web application is just a fancy .zip file and as such we can treat it as so. So follow the simple steps outlined below and you’ll have your Java WAR file deployed on cPanel in no time, all without using the Tomcat Manager.

  • Within your IDE, Clean and Build your project to compile and package the war file so you’ll end up with a file here: /{IDE_FOLDER}/ExampleProject/dist/ExampleProject.war
  • Rename this file to .zip
  • Login to your cPanel account and go to the File Manager
  • Navigate to /public_html
  • Create a folder called: Backup_yyyy_mm_dd (you know…. Just in case)
  • Move all of your current files into the backup folder you just created (excluding any files that aren’t part of your project i.e. .htaccess file, cgi-bin, .well-known (SSL certificates with Let’s Encrypt) and any application live data files such as images or document uploads that only sit within your live system due to user usage etc.
  • Upload your ExampleProject.zip file
  • Unzip the file
  • Done

Note, you shouldn’t need to restart Tomcat as all your new files should get automatically loaded into memory by Tomcat, but if you do notice that some files aren’t showing the latest version then you may need to restart Tomcat to ensure the files are all uploaded. To do this the handy command on the latest version of cPanel (at the time of writing!) is as follows. Simple SSH into your server or use the Terminal functionality that exists within cPanel and run the command;

                ubic restart ea-tomcat85

This will restart the running Tomcat instance for your user only. Simple!

And if all has failed and you need to restore the backup files you backed up at the start, jump into your FTP Client software such as FileZilla where you can easily move all files within your backup folder back to the parent level. Unfortunately this part isn’t out of the box functionality with cPanel, so I’d make sure you can access your server using FileZilla before you attempt this process as you may need to quickly jump back on there and fix it.

How to Install Multiple Versions of Java on Linux

You’re probably looking for information on how to install multiple versions of Java on Linux as part of a migration piece of work and/or a new deployment activity after spinning up a new Linux server which has a different version of Java running than what your Java web application was compiled in. Whatever Java version your application is compiled in needs to be the same Java version that is running on your web application server to ensure it works without issues (or even just works!).

So, let’s assume you’ve got the handy yum tool installed on your Linux box which allows you to easily run handy commands to install software. Within yum you can find lots of handy versions of java just sitting around waiting to install them. Take a look at all the Java packages within yum.

What you’ll notice is that the majority of them are utilising the OpenJDK setup. This is a handy open source version of the Java platform. So all you need to do is get it installed then get it configured. Simple.

 

Check Current Java Version Installed

Firstly you need to check the current version of Java that you have installed on your Linux box. To do this simply run the following command;

 

java -version

 

 

Install Java 1.8 Version on Linux Using Yum

Simply run the following command to install the latest version of Java (whatever the latest version is on your system);

 

sudo yum instal java-1.8.0-openjdk

 

Configure Linux to Use the New Version of Java via Alternatives

On Linux machines you can configure multiple versions of Java to run via the ‘alternatives’ feature. This essentially allows you to install multiple Java versions alongside each other without having to worry about the specifics. This allows you to have multiple versions of Java installed, and still configure a default.

Which basically means that when you run any default java command that it will run against whatever alternative has been configured to point at the different versions of Java installed on your Linux box.

To check this, simply run the command;

 

sudo alternatives --config java

 

Which will allow you to configure which is the default Java version.

And it’s as simple as that. Install as many versions of Java as you need, but you can only use one of them at once.

If you have multiple applications running which all require different versions of Java then you have a couple of options. Either upgrade everything so they are all running the latest version of Java so you can keep everything on a single server. Or move applications to their own servers to give yourself the maximum control.

How to Configure Apache as a Reverse Proxy for Apache Tomcat

So you’re running an Apache Tomcat environment on Linux but since this is a public facing web application, you want to get rid of the port 80 business so that your users don’t have to go remembering what port the application is running on. After all, port 8080 or 8084 isn’t exactly easy to remember for the average non-technical user. And god forbid you’ve decided to change this to something non-default, trying to remember that is going to be even more fun!

Thankfully it’s fairly straight forward to use Apache as a Reverse Proxy that sits in front of Apache Tomcat so that you can serve requests over port 80. You could configure Apache Tomcat to run on port 80, but if you’re running the Apache Tomcat Manager GUI then this restricts you to running your web applications only in sub-directories – and let’s be honest – no-one wants that. Everyone wants to be running their web application at the root of their domain, i.e. www.example.com rather than www.example.com/my-web-application/.

 

Configure an Apache Virtual Host File

Simply SSH into your server and run the command below;

 

sudo nano /etc/httpd/conf.d/httpd.conf

 

It’s worth nothing to double check the other files that currently exist in that directory before configuring this. Sometimes you will have slightly differently named files and/or this file may already exist with current configurations. Don’t just go adding configurations to this fil unless you’re sure what you are doing. At least take a backup of the current file(s) so you can revert your changes if you mess things up.

Thankfully on many vanilla installations of Apache this file will not exist, so the nano command above will create the file so you can edit it straight away.

To keep things simple all you need to do is add the following lines of code to that file;

 

<VirtualHost www.example.com:80>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>

 

Now run the command to restart Apache to ensure the changes take effect.

 

sudo service httpd restart

 

Now you’ll notice that the above doesn’t actually change anything. It just means the Apache Tomcat Manager GUI now loads over port 80 rather than port 8080. That isn’t quite what we want, so we need to configure the Virtual Hosts file to suit your application needs.

Let’s say your application is called MyWebApplication, which sits at www.example.com:8080/MyWebApplicaion on Apache Tomcat. You need to ensure your Virtual Hosts file looks as follows so that the application routes successfully;

 

<VirtualHost www.example.com:80>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/MyWebApplication
    ProxyPassReverse / http://127.0.0.1:8080/ MyWebApplication
</VirtualHost>

 

Simple. Now you’re done.

This is how you configure Apache as a Reverse Proxy for Apache Tomcat. This approach also allows you to run multiple Java web applications from a single Apache Tomcat instance if that suits your needs from a practical, management and security perspective. Alternatively, run everything from separate setups if you need something more segmented.  

How to Convert an SVG to a PNG in Java

Ok, this one is a little tricky as there isn’t a lot of authoritative and clear information online about how to do this, so I thought it would help to clarify how to do this as it’s a problem I just came across myself and spent a fair amount of time to get this working. Thankfully, this blog post should allow you to just read through it and be able to start converting SVG image to a PNG image in no time.

 

SVG to PNG Libraries

Firstly let’s look at the core libraries you need to do this. Thankfully there is just the one which is the Apache Batik library which is part of the Apache XML Graphics Project. In summary, Apache Batik is a Java-based toolkit for applications or applets that want to use images in the Scalable Vector Graphics (SVG) format for various purposes, such as display, generation or manipulation.

Now, this is where things start to get a little more challenging. I would recommend downloading the Bin ZIP file from the download link just mentioned. If you take a look around the Maven Repository you’ll notice that there are a lot of different versions which look all very similar, and all of them are generally last updated around 10 years ago. Sure, these things of tools rarely change once built, but this always worries me.

Once you’ve extracted the ZIP, you’re looking for the file titled batik-all-1.12.jar (Note, the version number may differ when you are reading this…) which will be in the folder, /batik-bin-1.12/batik-1.12/lib/batik-all-1.12.jar.

Add that JAR file to your project.

Now you would think that the project developers would have included all of the dependencies already bundled up. But no. And the documentation isn’t clear about all the dependencies which makes life even more difficult.

 

Dependencies

So, you need a few dependencies to get this up and running.

 

XML Commons from the Apache Xerces project

Download XML Commons and add the two JAR files to your project called, xml-apis.jar and xml-apis-ext.jar.

 

XML Graphics Commons from the Apache XML Graphics Project

Yes, this is the same project as where Batik lives, but hey. Download XML Graphics Commons and add the xmlgraphics-commons-2.4.jar file to your project.   

 

Java Code to Convert an SVG into a PNG

Ok, so now we’ve got all the libraries and dependencies added to your project, it’s now time to actually write the code to convert an SVG to a PNG. Use this code as a starting point to get you going;

 

try {

            // Use this to Read a Local Path
            // String svgUriImputLocation = Paths.get("https://www.contradodigital.com/logo.svg").toUri().toURL().toString();
            // Read Remote Location for SVG
            String svgUriImputLocation = "https:// www.contradodigital.com/logo.svg";
            TranscoderInput transcoderInput = new TranscoderInput(svgUriImputLocation);

            // Define OutputStream Location
            OutputStream outputStream = new FileOutputStream("C:\\Users\\{{Your User Name on Windows}}\\Documents\\logoAsPngFile.png");
            TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);

            // Convert SVG to PNG and Save to File System
            PNGTranscoder pngTranscoder = new PNGTranscoder();
            pngTranscoder.transcode(transcoderInput, transcoderOutput);

            // Clean Up
            outputStream.flush();
            outputStream.close();

        } catch (IOException | TranscoderException ex) {
            System.out.println("Exception Thrown: " + ex);
        }

 

Hope that helps to get you going in the right direction if you’re working on a similar problem to this.

How to Setup an Apache Tomcat Environment for Java on AWS Using EC2 in 15 Minutes

How to Setup an Apache Tomcat Environment for Java on AWS Using EC2 in 15 Minutes

So, you’re ready to enter the world of AWS then. Or, maybe you’re already used to working with AWS and just want to spin up a quick environment to prove a point. Either way, let’s take a look at how to spin up an Apache Tomcat environment on AWS in around 15 minutes so you can get the ball rolling. This clearly isn’t going to be a full production-ready setup, but it will get you going on the right lines.

 

Step 1 – Spin Up an EC2 Instance

I’m not going to talk through how to do that here. Google it. Click around. It’s a fairly simple setup. For the purposes of this blog post I’m going to assume you’re re-using an SSH Key so we don’t need to talk through how to get one of those setup and configured so you can SSH into your server.

NOTE: Important note on the different versions of the Operating Systems when installing;

  • Amazon Linux 2 only supports older versions of Apache Tomcat when using yum, i.e. version 7 and lower (oddly)
  • Amazon Linux (aka. version 1) support the later versions of Apache Tomcat when using yum, i.e. versions 8 and higher

 

Step 2 – Configure the Firewall aka. the AWS Security Group

As part of the setup in Step 1 you will have setup a Security Group, likely a brand new one. So you need to configure this to ensure that you can access your application. Thankfully there are a few simple ports you need to open on the Inbound Interface;

  • Port 80 for HTTP traffic
  • Port 443 for HTTPS traffic
  • Port 8080 or 8084 for Apache Tomcat, depending on the version or configuration you’re using

Once you’ve configured the ports on the firewall you can continue to get everything setup as required.

 

Step 3 – SSH Into the Server to Configure Things

As part of your setup in Step 1 once your EC2 instance is up and running, it will have a publicly accessible hostname and IP address. One thing to note with EC2 instance is that every time you reboot them the hostname and IP address changes. This doesn’t particularly matter for the purpose of this blog post, but it is something you should be aware of if you’re looking for something more permanent. You can setup Static IP address (which are confusingly known as Elastic IPs in AWS terminology) so that you can configure everything you need from there.

As mentioned earlier, I’m going to assume you can SSH into the server successfully. If not, there is a Console option within the AWS Console interface which allows you to SSH into your new box which is quite handy.

The public hostname will look something along the lines of, http://ec2-{public-ip-address}.{aws-zone}.compute.amazonaws.com/

 

Step 4 – Install Apache Tomcat and Goodies

Once you’re SSH’d into your server, basically just run the following command which will install Apache Tomcat and all handy tools including the Tomcat Manager which allows you to upload your .war file via a handy interface so you don’t have to worry about copying the files over.

 

sudo yum install tomcat8 tomcat8-webapps tomcat8-admin-webapps tomcat8-docs-webapp

 

Step 5 – Configure Apache Tomcat Users

Now you’ve got Apache Tomcat installed, you need to make sure you can actually access the Tomcat Manager interface, so let’s get you an account created. Simply run the command below which will open the configuration file;

 

sudo nano /etc/tomcat8/tomcat-users.xml

 

Then un-comment the line in the file which gives you a default admin/adminadmin username/password. Clearly you should make this more secure, but as mentioned, this isn’t a production ready system, we’re trying to do this in 15 minutes. Save the file and exit.

 

Step 6 – Configure Apache Tomcat to Whitelist a Valid Administration IP Addresses

Next you need to configure Apache Tomcat to ensure you can access the Tomcat Manager easily to upload your .war files to the system. To do this, first you need to find out the IP address of your system. If you’re not on a static IP address from your device (i.e. home dynamic IP address, tethered from a mobile phone or in a coffee shop), then this step is only going to work for a very short period of time for you. Best bet – get yourself a Static IP address if you don’t have one already so you don’t have to keep messing with the configuration files every time you need to deploy your code.

First, edit the Hosts Manager Context.xml file by running the following command;

 

sudo nano /usr/share/tomcat8/webapps/host-manager/META-INF/context.xml

 

Then include your IP address within that file.

Second, edit the Manager Context.xml file by running the following command;

 

sudo nano /usr/share/tomcat8/webapps/ manager/META-INF/context.xml

 

Then include your IP address within that file.

Note that your current static IP address will need to be in the format of 1\.2\.3\.4. And if you want to whitelist multiple IP addresses, then you can separate them with the Pipe character |.

Save and exit each file in turn.

 

Step 7 – Access the Apache Tomcat Manager

Accessing the URL that you have in your AWS EC2 instance on the correct port should allow you to connect to the application manager;

 

http://3.10.224.121:8080/

 

Note, you’ll need to login with the username/password which you configured previously. Which as a default will be admin/adminadmin. Then from here you can simple manage the deployment of your application with ease.

 

Step 8 – Productionise the Above Setup

So we’ve flown through how to get an Apache Tomcat environment up and running for Java on AWS using EC2 and if you’ve followed the above steps, you should have had this done within 15 minutes. Some points you’re going to need to consider to get this into a production ready state include;

  • Server size
  • Server schedule for being turned on/off
  • Joining up Apache with Apache Tomcat to ensure you can run the application on port 80/443 instead of 8080/8084
  • Setting up SSL certificates using Let’s Encrypt
  • Locking down your firewall (aka. AWS Security Group) to ensure only whitelisted IP addresses can access the ports that you have opened
  • Setting up server monitoring software either as standalone applications or within AWS CloudWatch
  • Configuring any local or remote databases for your application to run on
  • Securing the Tomcat Manager and Host Manager applications using SSL Certificates

Hope the above guide has helped to get you up and running.

How to Create and Run a Basic HelloWorld Java Class

Ok. Back to basics. It’s rare these days that any developer working in the real world has to write a basic HelloWorld.java, compile the file with the core Java Compiler (javac, the Java Programming Language Compiler) and run the file using the command line ‘java’ command. But hey, sometimes things are just fiddly to debug and you need to get back to the real basics and say HelloWorld.

Honestly, I’m mainly writing this blog post for myself as I can never remember how to do this as it is something that I haven’t had to do in many years, because you know, we have things called IDEs, Web Applications, Automated Deployments and just modern technology in general which is the space I tend to work in.

Just a general note, the common reason why you’ll need to do things like this is because your Local à Dev à Test à Live Environments are slightly different. Different enough to cause issues that you’ll only notice while you migrate your applications through the development lifecycle.  

 

How to Create a HelloWorld.java File with a Main Method

For the purpose of this blog post, let’s forget we’re in the 20th Century using a modern IDE, let’s get Notepad open.

For the purpose of this blog post, I’m going to use a real world example that I was debugging, specifically when trying to figure out why the ‘reasonably recent’ Java 8 functionality on one application wasn’t working on one application server, which had recently had Java 8 installed with Tomcat 7 which was installed via WHM > cPanel’s Easy Apache 3. The LocalDate.now() function is only available from Java 8, and a specific release of Java 8, just to add to the confusion. None of which is really relevant for this blog post, but it puts into context why you sometimes need to go back to real basics and to try and figure out where the problem ultimately lies.

Sometimes you just need to strip back the many layers of applications, get back to the core and build up from there to identify where the problem is. Anyhow, back to where we were.

Basically create this file and save the filename as HelloWorldMain.java;

 


package PlayGround;

import java.time.LocalDate;

&amp;amp;amp;nbsp;

public class HelloWorldMain {

public static void main(String[] args) {

System.out.println("LocalDate.now(): " + LocalDate.now());

}

}

 

Yes that’s right, pure, core, Java. No frameworks. No libraries. No helpers. Nothing. Welcome to the 80s.

The reason why we’re creating a Main method is to ensure that when we run the compiled code, as detailed later on, it will automatically run the Main method and print the information you require to the command line console.  

 

How to Compile Your HelloWorld.java File to Create a HelloWorld.class File

Ok, now you’ve created your HelloWorldMain.java file as outlined in the previous step, it’s time to compile this into executable code. As you’ll know, you can’t run .java files as they are (unlikely say .html files), instead you need to compile your .java files into .class files using the Java Development Kit (aka. JDK) that is installed on your machine (local machine or server).

To compile your .java file, firstly you need to open the Command Prompt (on Windows) or SSH into your Linux server. Using your command line skills (simple right…?), navigate to the location of your file and compile your .java file by running the following command;

 

javac HelloWorldMain.java

 

Awesome, you should now have a HelloWorldMain.class file created in the same directory you are currently in.

But… things aren’t always quite as they seem. We’ve not gone into any of the details yet about where you’ve just run the Java compiler command. Windows? Linux? Now this is where things get interesting. Let’s say you’re developing on a Windows machine, and you’re deploying on a Linux server. Immediately you’ve got a discrepancy.

What version of Java are you running on your Windows machine?

What version of Java are you running on your Linux machine?

What other crazy-ass things have you got configured that may be getting in the way in either environment? Hopefully nothing, but keep that in mind. Often things are configured in the background that you may not be aware of, particularly whenever you’ve used handy installers and other software to manage the installation of your environments.

So, let’s get back to the basics and find out the environments we’re working in.

 

Check the Java Version

On the machines you’re working on, check what version of Java is currently the priority by running the command;

java -version

 

You can also view on Linux the Environment Variables which can help to identify what is setup by running the command;

printenv

(aka. the Print Environment Variables command)

 

And on Windows you can view your Environment Variables by opening the Command Prompt ( aka. Windows Start Menu > Run > Then type ‘cmd’ without the quotes and press go ) or ( Just press Windows Key + R ), then type;

set

Which will output your Environment Variables.

 

Check the Java Alternatives

On Linux machines you can configure multiple versions of Java to run via the ‘alternatives’ feature. This essentially allows you to install multiple Java versions alongside each other without having to worry about the specifics. This allows you to have multiple versions of Java installed, and still configure a default.

Which basically means that when you run any default java command that it will run against whatever alternative has been configured to point at the different versions of Java installed on your Linux box.

To check this, simply run the command;

sudo alternatives --config java

Which will allow you to configure which is the default Java version – according to the Linux environment.

This is an important point to note, since an application (for example Tomcat…) can actually still override this locally within the application configuration files and hence completely ignore what you set at the base server level. The joys and flexibility (aka. frustrations…) of dealing with Linux.

 

How to Run Your HelloWorld.class File From the Command Line

Ok, so now we’ve covered a fair amount of the ‘basics’, let’s take a look at actually running the file we’ve just created.

Basically just run this command (with tweaks) against the file that is hosted against your own Linux server;

java -cp /home/{Root Directory for User }/public_html/WEB-INF/classes/ PlayGround.HelloWorldMain