Announcing Eazy Ad Unblocker!

Hello everyone,

I wish to announce that I have released a wordpress plugin named “Eazy Ad Unblocker”. You can find this plugin at the following URL: https://wordpress.org/plugins/eazy-ad-unblocker/

Now, to tell you what this plugin does. Suppose you own a wordpress site and have painstakingly put advertisements on it. Now many of your visitors don’t even look at your ads, let alone clicking on it. Why? Because they install browser extensions that block those ads from being shown on your site!

What “Eazy Ad Unblocker” basically does is to detect if an adblocker is active on the page seen by the visitors. If an adblocker is active, a modal popup shows up on the screen and prevents your visitors from browsing your website in any way, asking the to either deactivate the adblocker or whitelist your site.
The plugin only detects ad blockers. It does not check if ads are actually there on the page.

Advanced and tech-savvy visitors may try to delete the popup and background overlay through web developer tools, inspect element and the like. This is countered effectively by the plugin. Right-clicking in the web page will fail
to invoke the context menu. Trying to invoke web dev tools by using keyboard shortcuts in the web page will also fail.

You will see this feature on many news sites, which implore users to deactivate adblockers or whitelist the site, telling them that the site they are viewing uses adverts for much needed revenue.

As a user of this plugin, you can configure the title, descriptive text and opacity of the modal popup shown to your visitors. You can completely black out your website content partially visible in the popup background by setting opacity to 100 %. You can add photos, videos and audio clips to the body content of the popup. Only formats supported by HTML5 will work in audio and video with this popup.

The plugin supports internationalization, both in the popup content and the wp-admin screen. You can preview the functioning of this plugin at https://myplugins.net/demo/
You can also see more details at https://wordpress.org/plugins/eazy-ad-unblocker/

Why Digital Marketing Is Important For Your Business

In the digital age, it does not make good business sense for your business not to have a digital presence. This is because you will not be able to reach out to the audiences of digital platforms who are your potential customers. Using social media and search engines is now commonplace. You need to market your business to the online audience, or in other words, do digital marketing.

What is Digital Marketing?

Digital marketing is the marketing of products or services using digital technologies, mainly on the Internet, but also on mobile phones, display advertising, and any other digital medium. Digital marketing channels are systems based on the internet that can create, accelerate, and transmit product value from producer to the terminal consumer by digital networks.

A Brief History of Digital Marketing

The term Digital Marketing came into being in the 1990s. The first clickable banner ad went live in 1994, which was a campaign by AT&T and over the first four months of it going live, 44% of its viewers clicked on it.

In the 2000s, with more people using the internet and the advent of the iPhone, more and more people searched for products and made decisions online instead of consulting a sales person. These developments made marketers find digital ways for market development. In 2007, marketing automation came into being. Marketing automation helped companies to partition customers into segments, launch multichannel marketing campaigns and provide personalized information for customers.

Digital marketing became more sophisticated in the 2000s and the 2010s, when the proliferation of devices capable of accessing digital media witnessed a sudden growth. In the 2000s, with the advent of social media, such as LinkedIn, Facebook, YouTube and Twitter, consumers became highly dependent on digital electronics in their daily lives. They began to expect a seamless user experience across different channels for searching product information. This change in customer behavior led to the diversification of marketing technology. Digital media volume was estimated at 4.5 trillion online ads served annually with digital media spending growing at 48 percent in 2010.

Photo credit:  Avantika Monnappa at https://www.simplilearn.com/

Types of Digital Marketing

Types of online digital marketing include:

1.   Search Engine Optimization (SEO): SEO is the art of increasing the visibility of your business site in the organic or non-paid search results of any of the search engines according to keywords entered by the user and the algorithm employed by the search engine. You can get your company’s website to appear at the top of a user’s organic search results by optimizing your website using SEO.

2.   Search Engine Marketing and Pay-Per-Click Advertising (PPC): Search Engine Marketing or SEM covers paid traffic from search engines. To use SEM, you purchase advertisement space that appears on a user’s Search Engine Result Page (SERP). The search engine charges a business a certain amount to display an advertisement in a number of places on an SERP generated from specific keywords or phrases. PPC is a digital marketing method by which search engines charge a company each time their advertisement is clicked.

3.   Social Media Marketing: Using social media marketing you’ll gain more reach when you post quality content. Everything you do to increase traffic or business on your social media channels is a part of social media marketing. Whether you’re on Facebook, Twitter, Snapchat, or LinkedIn, all your efforts on these sites amount to social media marketing. Almost everyone benefits from social media marketing, but Business-to-consumer (B2C) companies stand to gain the most.

4.   Content Marketing: Content marketing is the practice of delivering a piece of high quality content to your users to generate sales and leads. This content can be live anywhere online. Tweets, a YouTube video, an Instagram post and blogs on your website, etc all comprise content marketing. Content Marketing combines exceptional content with other types of digital marketing like SEO and Social Media Marketing.

5.   Affiliate Marketing: Suppose you are a business selling products and services on your site. Now, say a blogger X posts details about your products on his own blog. When internet users click on product advertisements on X’s blog, they are directed to your business site and if users complete a purchase, X gets a commission from you according to an agreement between you and the affiliate, namely X.

6.  Influencer Marketing: Influencer marketing uses people with tremendous online popularity who are considered experts by your target market to drive traffic and sales. Influencer marketing is popular on social media channels like Instagram and Snapchat as well as behemoths like Amazon. Companies hire influencers with large followings to publicize their brand through posts.

7.   Email Marketing: Email marketing allows you to update your email subscribers on a regular basis about your company through newsletters for example. This fosters a relationship with the subscribers. Your email updates provide value to your consumer and as a result, you build trust and brand loyalty.

8.   Viral Marketing: Viral marketing involves a post that is trendy, funny, or strange enough to garner a massive number of shares online. Viral marketing causes an enormous increase in website traffic over a short period of time. B2C companies gain the most from viral marketing.

9.   Mobile Phone Advertising: Each of the types of digital advertising can target a mobile device. Some types of marketing using a mobile such as SMS advertising can prove an asset to local marketing efforts. You can prompt your consumers to use SMS to receive special offers, coupons, and updates from your company.

Why Businesses Postpone the Adoption of Digital Marketing plans

Small businesses may feel that they don’t have the time or the money to be competitive online. They think they can only face so many challenges all at once when they are still learning the ins and outs of business in general. Many of them may prefer to take things slowly and steadily. They wish to stick with one or two basic forms of advertising, assuming that their business will evolve as time passes. Since they are a small business, they may think they only need a small number of customers to begin with. This is not an effective approach. There is no guarantee that your business will attract customers just by existing and even if it does, you may not attract enough customers to make your business profitable and sustainable.

The Benefits and Importance of Digital Marketing

When small businesses get started, they often focus on how to get their first customers through the door. They often rely on traditional forms of advertising, such as print ads or road signs. They may believe that since people know that they offer a good product or service, it’s only a matter of time until customers will find their way to them. Although this strategy may bring in a trickle of business, small businesses should consider the huge marketplace of prospective customers online to improve their business prospects. Any business, no matter how new or how small, should not overlook this vast marketplace. Larger businesses, which have grown in the pre-digital era, have the potential to grow even more through digital marketing. Indeed, they may also need a digital marketing strategy to remain relevant in the face of increased competition and changing technology.

Benefits.

The group of potential customers who are found online is a much larger group of people than what you can attract locally. Using digital marketing, you can reach an enormous audience in a way that is both cost-effective and quantifiable.
Other benefits of digital marketing include:

• The ability to interact with your prospective customers and learn about their preferences. You will be able to improve customer satisfaction by iteratively modifying your product or service according to these insights.

• The ability to reach a global marketplace. This is the largest pool of potential customers.

• Reach more customers for less money than traditional marketing methods.

• Get to know your audience and allow them to know you personally which can help to build a relationship with the customers and create brand loyalty.

• Track responses to your marketing efforts in real time through means such as analytics.

• Communicate your brand identity on social media, thereby piggybacking on the popularity of those social media services.

• Reach out to users of diverse software and devices. Smartphones are a user segment that has witnessed explosive growth recently.

• Compete with larger companies. Don’t get pushed out of the marketplace!

• Get higher marketing Return On Investment (ROI) and conversion rates.

Importance.

The following are the reasons why you can ignore digital marketing only at your own peril:

Your customers are online: To tell you the truth, your customers are already online, even though you don’t know it. And so are your potential customers. If your business is not found online easily, these potential customers will flock to your competitors. At the minimum, they will expect you to have a website and a social media presence.

Your competitors may already be online: To succeed in the business world, you need to look over your shoulder at what your competitors are doing and learn from it. Regardless of your niche, your competitors have likely established a web presence already. You can learn what is working or not working from your competitors. You can study what kind of content they are using, whether they are using more graphics and video, like a YouTube channel. A sound digital marketing strategy will position you to compete in the digital world.
If your prospective customers begin to search for a business similar to yours and are able to find your competitors’ website but not yours, they can’t choose you because they don’t know about you.

You need to be accessible: In today’s digital world, the first place the average consumer looks for what they want is online. They will most likely start their search with Google, no matter what product or service they are looking for. If you have no online presence at all, you won’t be found, and you can’t compete. If you have an online presence but your competitors are easier to find and are found first, you might still go unnoticed. To remedy this, you can hire an SEO expert, for example, to make sure that when prospective customers search with certain keywords, they find your site first.

You want to make customers come to you: By creating a web presence, your business is open 24×7 even when it’s closed for the day! You can create a business environment in which your customers can come to you any time, day or night. Existing and prospective customers can send you emails with questions, make purchases and browse your inventory, at their convenience. Potential customers who have no way to physically come to you can still do business with you, whether they are limited by disability, transportation or are simply living too far away. So, with digital marketing, the scope of your business exceeds the boundaries of your shop floors!

You must get to know your target audience: Digital marketing allows you to gradually get to know your prospective customers and what they are hoping to find. You can start a conversation with them on a blog or social media, or even conduct a survey. Their responses will help you improve your business. By interacting with people digitally, you can start to get to know what they are looking for and what solutions you can offer to them. With digital marketing, there is no guesswork involved. It allows you to methodically find out who your customers are and what they really want.

Be more than just a business concern: By responding to customer feedback, by solving the consumers’ problems and building a relationship with them, you become more than a business. You become a trusted partner. Trust means that not only will more people buy from you, but also your previous customers might buy again from you. A digital presence also puts your dealings on the record.

Conclusion

In the current business environment, it is extremely important to foray into digital marketing and develop a digital marketing strategy due to its immense benefits. Digital marketing has the potential to increase your revenue. If you ignore digital marketing, you may fall behind the competition and lose your business!


REFERENCES:

1. https://en.wikipedia.org/wiki/Digital_marketing

2. https://digitalmarketinginstitute.com/blog/why-digital-marketing-is-important-for-small-business

3. https://www.sparklogix.com/9-types-of-digital-marketing-and-how-to-use-them/

A Simple IP Blocker Plugin for WordPress

In my post here, I had shown how to create a basic “Hello World” plugin that greets the user with a simple “hello world” message in the admin dashboard. Now, let me show you how to create a wordpress plugin that actually does something more useful. In this post, I shall discuss a plugin that restricts the number of login attempts a user can make to login to the admin dashboard of your wordpress site. It makes sense to do this to secure your dashboard from being broken into because an unauthorized user can do just about anything to your site if he manages to access your admin dashboard. This includes defacing your site, deleting your content and God knows what else!

We will call our plugin “Simple IP Blocker”. It will restrict the number of failed login attempts to a fixed number, say three. On the fourth attempt, the user will see an error message “IP address blocked”. The user will be blocked for the remainder of the day on which he made the three unsuccessful login attempts. He will be able to try again on the following day.

Now, let’s get down to the nuts and bolts of the actual plugin. The steps are:

  1. Create a folder for the plugin
  2. Create a PHP file for the code called index.php in that folder.
  3. Create a header for the plugin.
  4. Initialize the required constants.
  5. Create a database table through the activation hook.
  6. Create a function that hooks into wp_login_failed action.
    It logs the failed attempts in the database table and blocks the IP address of the user.
  7. Create a function that displays the logged data from the table.
  8. Hook the function in 7 into the admin_menu action so that the logged data can be displayed.
  9. Create a function that hooks into the login action ‘wp_authenticate’
    that will give an error on trying to login in after ip is blocked.
  10. Activate your plugin and test it.

Let us discuss these steps in detail:

1. Navigate to the wp-content folder in your wordpress installation. Go to the plugins sub folder in it.
Create a folder called “simple-ip-blocker”.

2. Create a blank file titled index.php using your text editor and save it in the folder created in step 1

3. Now, let’s create the header in the index.php file.
Print the following code in after the opening php tag in the index.php file:

<?php 
/ * 
* Plugin Name: My Simple IP Blocker 
*/ 
?>

4. We will initialize the following constants:

<?php 
global $wpdb; 
define("LOGIN_FAILURES", 3); 
define("IPBLOCKER_TABLE", $wpdb-&gt;prefix.'ip_blocker');
?>

5. The above step will create a new line in the plugins section of your wordpress installation and define
the necessary constants.

We need to create a database table to log and count failed login attempts.
We will do this by using the “register_activation_hook” function.
We will create a PHP function named “simple_ip_blocker_create_table”.
In this function, we will write a “CREATE TABLE” MYSQL query. We will execute it by calling $wpdb->query
function on the global $wpdb variable by passing the query in it as a parameter.

We will then pass the “simple_ip_blocker_create_table” function name in the “register_activation_hook” function.

The code is as follows:

<?php 

function simple_ip_blocker_create_table() { 

     global $wpdb, $table_prefix; 
     //mysql query $create_tab_query = 
"CREATE TABLE IF NOT EXISTS `".IPBLOCKER_TABLE."`( 
`id` bigint(20) NOT NULL AUTO_INCREMENT, 
`ip_addr` varchar(20) NOT NULL, `attempts` int(4) NOT NULL, 
`try_date` date NOT NULL, `is_blocked` tinyint(1) NOT NULL, 
PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; 

$wpdb->query($create_tab_query); } 

register_activation_hook( __FILE__, 'simple_ip_blocker_create_table' ); ?>

 

Explanation of table structure:

id – PRIMARY KEY
ip_addr – IP address of user trying to log in.
attempts – number of failed logins per user.
try_date – date on which user s trying to log in.
is_blocked – flag too indicate whether the user is blocked or not.

6. Next, we will create a function that will hook into “wp_login_failed”. We will call
this function simple_ip_blocker_reset_bruteforce. This function will fire whenever the
user tries to login but fails. We will maintain a counter in the $_SESSION. Each failed
login will increment the counter. On reaching 3 attempts, the IP blocked flag, is_blocked
will be marked as 1 to indicate that the particular user is blocked for the remainder of
the day. However, the user can try again on the next day. Each attempt is logged in the
database table we created. For the first failed attempt, a new row will be created in the
table. For subsequent attempts, that row will be updated.For the third failed login,
the “is_blocked” field of that row will be updated to 1.

Check out the code below:

<?php 

function simple_ip_blocker_reset_bruteforce() { 

@session_start(); 
global $wpdb, $table_prefix; 
if(!isset($_SESSION["brute_count"])) { 
$_SESSION["brute_count"] = 1; 
$query = "INSERT INTO ".IPBLOCKER_TABLE."(ip_addr, attempts, try_date, is_blocked) VALUES(%s, %d, %s, %d)"; 
$try_date = gmdate("Y-m-d"); 

$wpdb-&gt;query( $wpdb-&gt;prepare( 
        $query, 
        $_SERVER["REMOTE_ADDR"], 
        $_SESSION["brute_count"], 
        $try_date,
        0
      ) );
      
     }
     else
     {
      $_SESSION["brute_count"] = $_SESSION["brute_count"] + 1;
     
      $try_date = gmdate("Y-m-d"); 
       
       //check limit
        
      $check_query = "SELECT attempts FROM ".IPBLOCKER_TABLE." WHERE ip_addr = %s AND try_date = %s";
        
      $attempt_count = $wpdb-&gt;get_var($wpdb-&gt;prepare($check_query, $_SERVER['REMOTE_ADDR'], $try_date ));
    
       if($attempt_count &gt;= LOGIN_FAILURES)
       {
         unset($_SESSION["brute_count"]);
         
         $update_query = "UPDATE ".IPBLOCKER_TABLE." SET is_blocked = 1 WHERE ip_addr = %s AND try_date = %s";
         
         $wpdb-&gt;query($wpdb-&gt;prepare($update_query, $_SERVER['REMOTE_ADDR'], $try_date ));
         
         wp_redirect(site_url('/wp-admin/'));
         
         exit;
         
       }
       else{
         
        $query = "UPDATE ".IPBLOCKER_TABLE." SET attempts = %d WHERE ip_addr = %s AND try_date = %s";
        
        $wpdb-&gt;query( $wpdb-&gt;prepare( 
          $query,  
          $_SESSION["brute_count"],
          $_SERVER['REMOTE_ADDR'],
          $try_date
         ) ); 
         
         
       }
     } 
  }  

  add_action("wp_login_failed", "simple_ip_blocker_reset_bruteforce");
?>

 

7. So far so good. Now we will create a function to display the data of
failed logins in the wordpress backend. We will call this function
“simple_ipblocker_menu_callback”. It will simply query the database table
that we created and list out the information in tabular form.

See the code below:

<?php 

function simple_ipblocker_menu_callback() { 

  global $wpdb; 
  $get_history = "SELECT * FROM ".IPBLOCKER_TABLE; //&quot; LIMIT $offset, 10; 
  
  $history = $wpdb->get_results($get_history, ARRAY_A); ?> 
  <h1>Simple IP Blocker active!</h1> 
  <table border="0" cellspacing="5" cellpadding="5" class="widefat" > 
  <tr>
    <td>S. No.</td>
    <td>IP Address</td>
    <td>Login Attempts</td> 
    <td>Try Date</td>
    <td>Blocked</td> 
  </tr> 
  <?php foreach($history as $row){ ?>
    <tr>
      <td><?php echo $row["id"]; ?></td>
      <td><?php echo $row["ip_addr"]; ?></td>
      <td><?php echo $row["attempts"]; ?></td>
      <td><?php echo $row["try_date"]; ?></td> 
      <td><?php echo ($row["is_blocked"] == 1)?"blocked":"unblocked"; ?></td>
    </tr>
  <?php } ?> 
  </table> 
<?php } ?>

 

8. In this step, we will simply write some code to call the function created above whenever the user
clicks the link for the plugin in the admin sidebar on the left. See below:

<?php 

function simple_ipblocker_menu_add() { 

     add_menu_page("Simple IP Blocker", "Simple IP Blocker", "administrator", "simple-ip-blocker", "simple_ipblocker_menu_callback" ); 

} 

add_action("admin_menu", "simple_ipblocker_menu_add"); 

?>

 

9. The last function to be created is the function that checks if the user’s IP is blocked. If so,
the user will not be able to login to the admin dashboard on that day. However, the user may try
logging in on the next day again.
We will call this function “simple_ip_blocker_check_ip”. In this function, we will check if the user’s
IP address is marked 1 in the is_blocked field. If so, the user will be prevented from logging in.
The function hooks into “wp_authenticate” and hence will fire before every login attempt.

The code is as follows:

<?php 
       function simple_ip_blocker_check_ip() { 
               global $wpdb; 
               $try_date = gmdate("Y-m-d"); 
               $check_IP = "SELECT is_blocked FROM ".IPBLOCKER_TABLE." WHERE ip_addr = %s AND try_date = %s"; 
               $blocked = $wpdb-&gt;get_var( $wpdb-&gt;prepare( 
          $check_IP,  
          $_SERVER['REMOTE_ADDR'],
          $try_date
         ) );
         
    if($blocked == 1)
    {
      wp_die("IP address blocked!");
    }
  }

  add_action("wp_authenticate", "simple_ip_blocker_check_ip");
?>

 

10. Lastly, now that the coding is complete, we need to activate the “Simple IP Blocker” plugin listed in the
wp-admin and test it according to the functionality in the steps above.

The full listing is as follows:

<?php  
/*
* Plugin Name: My Simple IP Blocker
*/  
global $wpdb;

define("LOGIN_FAILURES", 3);
define("IPBLOCKER_TABLE", $wpdb->prefix.'ip_blocker');

function simple_ip_blocker_create_table()
{
  global $wpdb, $table_prefix;
  
  $create_tab_query = "CREATE TABLE IF NOT EXISTS `".IPBLOCKER_TABLE."`(
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
    `ip_addr` varchar(20) NOT NULL,
    `attempts` int(4) NOT NULL,
    `try_date` date NOT NULL,
    `is_blocked` tinyint(1) NOT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
  
  $wpdb->query($create_tab_query);
}

register_activation_hook( __FILE__, 'simple_ip_blocker_create_table' );


function simple_ip_blocker_reset_bruteforce()
{ 
   @session_start(); 
   
   global $wpdb, $table_prefix;
   
   if(!isset($_SESSION["brute_count"]))
   {
    $_SESSION["brute_count"] = 1; 
    
    $query = "INSERT INTO ".IPBLOCKER_TABLE."(ip_addr, attempts, try_date, is_blocked) VALUES(%s, %d, %s, %d)";
    
    $try_date = gmdate("Y-m-d");
    
    $wpdb->query( $wpdb->prepare( 
      $query, 
      $_SERVER["REMOTE_ADDR"], 
      $_SESSION["brute_count"], 
      $try_date,
      0
    ) );
    
   }
   else
   {
    $_SESSION["brute_count"] = $_SESSION["brute_count"] + 1;
   
    $try_date = gmdate("Y-m-d"); 
     
     //check limit
      
    $check_query = "SELECT attempts FROM ".IPBLOCKER_TABLE." WHERE ip_addr = %s AND try_date = %s";
      
    $attempt_count = $wpdb->get_var($wpdb->prepare($check_query, $_SERVER['REMOTE_ADDR'], $try_date ));
  
     if($attempt_count >= LOGIN_FAILURES)
     {
       unset($_SESSION["brute_count"]);
       
       $update_query = "UPDATE ".IPBLOCKER_TABLE." SET is_blocked = 1 WHERE ip_addr = %s AND try_date = %s";
       
       $wpdb->query($wpdb->prepare($update_query, $_SERVER['REMOTE_ADDR'], $try_date ));
       
       wp_redirect(site_url('/wp-admin/'));
       
       exit;
       
     }
     else{
       
      $query = "UPDATE ".IPBLOCKER_TABLE." SET attempts = %d WHERE ip_addr = %s AND try_date = %s";
      
      $wpdb->query( $wpdb->prepare( 
        $query,  
        $_SESSION["brute_count"],
        $_SERVER['REMOTE_ADDR'],
        $try_date
       ) ); 
       
       
     }
   } 
}  

add_action("wp_login_failed", "simple_ip_blocker_reset_bruteforce");  //plugin admin panel


//pre-authentication

function simple_ip_blocker_check_ip()
{
  //die('done');
  global $wpdb;
  
  $try_date = gmdate("Y-m-d");
  
  $check_IP = "SELECT is_blocked FROM ".IPBLOCKER_TABLE." WHERE ip_addr = %s AND try_date = %s";
  
  $blocked = $wpdb->get_var( $wpdb->prepare( 
        $check_IP,  
        $_SERVER['REMOTE_ADDR'],
        $try_date
       ) );
       
  if($blocked == 1)
  {
    wp_die("IP address blocked!");
  }
}

add_action("wp_authenticate", "simple_ip_blocker_check_ip");

function simple_ipblocker_menu_callback()
{ 

  global $wpdb;
  
  /* $page = (isset($_GET['pg']))?$_GET['pg']:1;
  
  $offset = ($page - 1) * 10; */
  
  $get_history = "SELECT * FROM ".IPBLOCKER_TABLE; //" LIMIT $offset, 10";
  
  $history = $wpdb->get_results($get_history, ARRAY_A);
  
  ?>
  <h1>Simple IP Blocker active!</h1>
    <table border="0" cellspacing="5" cellpadding="5" class="widefat">
      <tr>
        <td>S. No.</td>
        <td>IP Address</td>
        <td>Login Attempts</td>
        <td>Try Date</td>
        <td>Blocked</td>
      </tr>
      <?php 
        foreach($history as $row)
        {
          ?>
          <tr>
            <td><?php echo $row["id"]; ?></td>
            <td><?php echo $row["ip_addr"]; ?></td>
            <td><?php echo $row["attempts"]; ?></td>
            <td><?php echo $row["try_date"]; ?></td>
            <td><?php echo ($row["is_blocked"] == 1)?"blocked":"unblocked"; ?></td>
          </tr>
          <?php 
        }
      ?>
    </table>
  <?php
  
  
  
}  

function simple_ipblocker_menu_add()
{
  add_menu_page("Simple IP Blocker", "Simple IP Blocker", "administrator", "simple-ip-blocker", "simple_ipblocker_menu_callback" );
}  

add_action("admin_menu", "simple_ipblocker_menu_add");
//plugin admin panel end

?>

 

Create a Basic WordPress Plugin From Scratch

In my post here, I had shown you how to create a plugin from existing code. In this post, I will show how to create a basic ‘Hello World’ wordpress plugin from scratch.

First of all, create a ‘hello-world’ folder in your plugins subfolder under the wp-content folder of your wordpress installation.
Then, create a blank file in the ‘hello-world’ folder and name it ‘index.php’.
After that, open your index.php file and put the following code in it:

<?php
/*
Plugin Name: Hello World Plugin
Plugin URI: http://myexamplesite.com/hello-world
Description: A simple WordPress Hello World plugin
Version: 1.0
Author: Author Name 
Author URI: http://myownsite.com
License: GPL2
*/
 ?>

 

This will create a descriptive header in the listing of plugins under the plugins section in wp-admin.

Now create a simple hello_world function in the example index.php page like so:

<?php 

function hello_world()
{
     echo "<h1>Hello World!</h1>"; 
}

?>

But this function needs to be called somewhere to get its output.

To get the output, we need to add the following code to our index.php file.

<?php

function hello_world_callback()
{
      add_menu_page("Hello World", "Hello World", "administrator", "hello-world", "hello_world");
}

add_action("admin_menu", "hello_world_callback");

?>

The add_action function hooks into ‘admin_menu’ to create a link to the plugin in the admin sidebar on the left of your dashboard. On clicking this link, the ‘hello_world’ function is called and the output is displayed on that page.

We will get the output in wp-admin under the “Hello World” tab once we activate the plugin.

So the complete code that needs to be there in the index.php is the following:

<?php
/*
Plugin Name: Hello World Plugin
Plugin URI: http://myexamplesite.com/hello-world
Description: A simple WordPress Hello World plugin
Version: 1.0
Author: Author Name 
Author URI: http://myownsite.com
License: GPL2
*/

function hello_world()
{
     echo "<h1>Hello World!</h1>"; 
} 

function hello_world_callback() { 
     add_menu_page("Hello World", "Hello World", "administrator", "hello-world", "hello_world"); 
} 

add_action("admin_menu", "hello_world_callback");

?>

 

The video above shows the installation and working of the plugin.

Click the following link for a more detailed tutorial.

GUI Tic-Tac-Toe in Java Revisited

In my post found here I discussed a tic-tac-toe game coded in Java which was a version using a Graphical User Interface. The code listing for the classes and interfaces can be found in the same post. In this post I will discuss a Graphical User Interface (GUI) version of the same application with some additional features. The GUI tic-tac-toe app is based on a console application version found here. I shall only provide the changes and additions to the code listings here. Note that I will use the NetBeans IDE.

We will primarily make changes to the AWTBoard class. After making these changes, the user will be asked whether he really wants to quit when a game is in progress. If he clicks Cancel, the game will continue. If he clicks OK, the game will be terminated. If the game is over or not yet begun, the user will be able to stop the game as usual. See the video below the code listing to understand how it works.

package com.tictactoe.components;

import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Dell
 */
public class AWTBoard extends Board implements ActionListener{
    
    private Button[][] buttons = new Button[3][3];
    private Frame f;
    private Label l;
    
    private Move currMove;
    private Game myGame;
    
    public AWTBoard()
    {
        super();
        f = new Frame("Tic-Tac-Toe");
        f.setSize(300, 300);
        
        
        Panel topPanel = new Panel();
        
        topPanel.setLayout(new BorderLayout());
        
        Panel p = new Panel();
        
        GridLayout grd = new GridLayout(3,3);
        
        p.setLayout(grd);
        
        for(int i = 0; i &lt; 3; i++)
        {
            for(int j = 0; j &lt; 3; j++)
            {
                buttons[i][j] = new Button();
                
                buttons[i][j].addActionListener(this);
                
                p.add(buttons[i][j], i, j); //problem
                
            }
        }
        
        topPanel.add(p, BorderLayout.CENTER);
        
        l = new Label();
        
        topPanel.add(l, BorderLayout.SOUTH);
        
        f.add(topPanel);

        /****Begin changes****/
        f.addWindowListener(new WindowAdapter(){ 
            
            public void windowClosing(WindowEvent e){ 
                
                if(myGame.isGameOver() || Game.getMovesTillNow() == 0)
                {
                    f.dispose(); 
                    System.exit(0);
                }else{
                    int result = JOptionPane.showConfirmDialog((Component) null, "Game in progress. Are you sure you want to quit?",
        "Message", JOptionPane.OK_CANCEL_OPTION);
            
                    if(result == 0)
                    {
                        f.dispose(); 
                        System.exit(0);
                    }
            
                }
            } 
            
        });
        /****End changes****/        

        //f.pack();
        f.setBounds(200, 200, f.getWidth(), f.getHeight());
        
        f.setVisible(true);
    }
    
    public void setGame(Game game)
    {
        myGame = game;
    }
    
    public void display()
    {
        for(int i = 0; i &lt; 3; i++)
        {
            for(int j = 0; j &lt; 3; j++) 
            {  

                buttons[i][j].setLabel( ""+cells[i][j] );
               
            } 
             
        }  
    }
    
    public void markCell(Move move, char mark)
    {
        if(move.isIsValid())
        {
            int i = move.getRow(); 
            int j = move.getColumn(); 
            cells[i - 1][j - 1] = mark;
            
            buttons[i - 1][j - 1].setLabel(""+mark);
        }
        else
        {
            //System.out.println("INVALID MOVE!\n\n");
            l.setText("INVALID MOVE!");
        }
    }
    
    public Label getStatusLabel()
    {
        return l;
    }
    
    public void actionPerformed(ActionEvent e)
    {
        Button b = (Button)e.getSource();
        
        for(int i = 0 ; i &lt; 3; i++ )
        {
            for(int j = 0; j &lt; 3; j++)
            {
                if(b == buttons[i][j])
                {
                    currMove = new Move();
                    currMove.setRow(i + 1);
                    currMove.setColumn(j + 1);
                    currMove.setIsValid(true);
                }
            }
        }
        
        
        synchronized(this)
        {
            this.notify();
        }
        
    }
    
    public Move getCurrMove()
    {
        return currMove;
    }
}

 

An elementary security plugin protecting admin dashboard

In this post, I shall discuss an elementary plugin that can protect your wordpress admin dashboard from frequent incorrect login attempts. The plugin redirects the user to the home page after a predetermined number of incorrect logins, three for example. However, if the user enters the correct password after three wrong attempts, the user is logged in to the dashboard. The code hooks into the wp_login_failed action hook and uses a counter variable stored in the session to keep track of the number of login attempts. The plugin backend only tells the administrator that the plugin is active (See image above). The code listing is given below:

<?php 
/* 
* Plugin Name: My Simple Security 
*/ 

function simple_security_reset_bruteforce($username){ 

  @session_start(); 
  if(!isset($_SESSION["brute_count"])) { 
    $_SESSION["brute_count"] = 1; 
  } else { 
    $_SESSION["brute_count"] = $_SESSION["brute_count"] + 1; 
    if($_SESSION["brute_count"] > 3) { 
    
      unset($_SESSION["brute_count"]); 
      wp_redirect(site_url()); 
      exit; 
    } 
  } 
} 

add_action("wp_login_failed", "simple_security_reset_bruteforce"); //plugin admin panel 

function simple_security_menu_callback() { 

  echo "<h1>Simple Security active!</h1>"; 
  
} 

function simple_security_menu_add() { 

  add_menu_page("Simple Security", "Simple Security", "administrator", "simple-security", "simple_security_menu_callback" ); 
  
} 

add_action("admin_menu", "simple_security_menu_add"); //plugin admin panel end 

?>

 

A recording of the plugin is given below:

 

To turn this into a plugin and use it in your wordpress:

  1. Create an empty folder in your plugins folder.
  2. Give it an easily understandable name.
  3. Then, create a blank file in any text editor.
  4. Copy the code from the code listing here, including the “<?php” at the start.
  5. Paste the code copied above in your blank file.
  6. Save this file as index.php in your empty folder created above.
  7. Go to the wp-admin and activate the plugin.
  8. Logout from admin and try logging in to wp-admin repeatedly with the wrong password.

It should work as shown in the video above.

Deploying Tic-Tac-Toe Java GUI app

In this post, we deploy our tic-tac-toe Java GUI app so that it can be invoked either by double-clicking it or through the command line. Note: These steps below were performed on a Windows system.

  1. First, assemble all the Java source files in a folder of your choice.
  2. Open your Command Prompt.
  3. Navigate to your chosen folder in the Command Prompt using the cd command. e.g. cd Java\progs\TicTacToeGUIDemo
  4. Compile all the Java source files with javac compiler. e.g. javac -d . *.java.
    * means all Java files in the current folder.
  5. After successful compilation, the root package of your app will appear as a folder. In our case it’s ‘com’.
  6. Now, we need to create a manifest file to help us create a java archive file or JAR file.
    This file can be used to launch the app just by double-clicking on it.
    It can also be invoked using the java command from Command Prompt. e.g. java -jar TicTacToe.jar
  7. Open Notepad and create a blank new file called manifest.mf
  8. In this file, type:Main-Class: com.tictactoe.gameplay.AWTTicTacToe. This is the main class name, qualified by the full package name.
  9. After step 8, be sure to add a blank new line in the text file manifest.mf
  10. Save the manifest file and close it.
  11. Go back to your Command Prompt.
    Type the following: jar cvmf manifest.mf  –jar file name–  –root package folder name–
    e.g. jar cvmf manifest.mf TicTacToe.jar com
  12. You will get some verbose output from the jar command. To open your jar file, you can follow either of the steps in step 6 above.

View the video below to see it all in action.

Coding Tic-Tac-Toe with a Graphical User Interface

In my post found here I discussed a tic-tac-toe game coded in Java which was a console application.
The code listing for the classes and interfaces can be found in the same post. In this post I will discuss a Graphical User Interface (GUI) version of the same application. I shall only provide the changes and additions to the code listings here. Note that I will use the NetBeans IDE.

First I shall discuss the changes to the Board class. Since we shall use inheritance, we shall change the accessibility of the cells from private to protected. This is the only change required. See the listing below.

package com.tictactoe.components;  
/**
 *
 * @author pratyush
 */
public class Board { 
 
    protected static char[][] cells; //change to Board class for inheritance
    
    public Board()
    {
        cells = new char[3][3]; 
        cells[0] = new char[]{' ', ' ', ' '}; 
        cells[1] = new char[]{' ', ' ', ' '}; 
        cells[2] = new char[]{' ', ' ', ' '};
    }
    
    public void display()
    {
        for(int i = 0; i &lt; 3; i++)
        {
            for(int j = 0; j &lt; 3; j++){ 
        if(cells[i][j] == ' ') 
        { 
          System.out.print((i+1)+", "+(j+1)+"\t"); 
        } 
        else{
          System.out.print(cells[i][j]+"\t"); 
        } 
      } 
      
      System.out.print("\n\n"); 
    } 
  } 
  
  public Move checkAvailable(Move move){ 
  
    int i = move.getRow(); 
    int j = move.getColumn(); 
    boolean boundValid = ((i >= 1 && i<= 3) && ( j >= 1 && j <= 3));
    
        boolean charValid = false; 
        if(boundValid)
        {
            charValid = (cells[i - 1][j - 1] == ' ');
        } 
        boolean netValid = (boundValid && charValid); 
        move.setIsValid(netValid); 
        return move;
    }
    
    public void markCell(Move move, char mark)
    {
        if(move.isIsValid())
        {
            int i = move.getRow(); 
            int j = move.getColumn(); 
            cells[i - 1][j - 1] = mark;
        }
        else
        {
            System.out.println("INVALID MOVE!\n\n");
        }
    } 
}

 

AWTBoard

Among the additions, we shall make a new Board class called AWTBoard which shall inherit all the properties of the Board class. However it shall add the functionalities of GUI from the Java Abstract Windowing Toolkit or AWT packages. The listing of this new class is given below. The AWT version of the Board will be a frame with a 3 X 3 grid of buttons with a status label at the bottom to display all the messages which were being outputted to the console in the console version of the application. The players will play their turns by clicking buttons in the grid.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tictactoe.components;

import java.awt.*;
import java.awt.event.*;

/**
 *
 * @author Dell
 */
public class AWTBoard extends Board implements ActionListener{
    
    private Button[][] buttons = new Button[3][3];
    private Frame f;
    private Label l;
    
    private Move currMove;
    
    public AWTBoard()
    {
        super();
        f = new Frame("Tic-Tac-Toe");
        f.setSize(300, 300);
        
        
        Panel topPanel = new Panel();
        
        topPanel.setLayout(new BorderLayout());
        
        Panel p = new Panel();
        
        GridLayout grd = new GridLayout(3,3);
        
        p.setLayout(grd);
        
        for(int i = 0; i &lt; 3; i++)
        {
            for(int j = 0; j &lt; 3; j++)
            {
                buttons[i][j] = new Button();
                
                buttons[i][j].addActionListener(this);
                
                p.add(buttons[i][j], i, j);
                
            }
        }
        
        topPanel.add(p, BorderLayout.CENTER);
        
        l = new Label();
        
        topPanel.add(l, BorderLayout.SOUTH);
        
        f.add(topPanel);
        
        f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ f.dispose(); System.exit(0);} });
        
        
        f.setBounds(200, 200, f.getWidth(), f.getHeight());
        
        f.setVisible(true);
    }
    
    public void display()
    {
        for(int i = 0; i &lt; 3; i++)
        {
            for(int j = 0; j &lt; 3; j++) 
            {  

                buttons[i][j].setLabel( ""+cells[i][j] );
               
            } 
             
        }  
    }
    
    public void markCell(Move move, char mark)
    {
        if(move.isIsValid())
        {
            int i = move.getRow(); 
            int j = move.getColumn(); 
            cells[i - 1][j - 1] = mark;
            
            buttons[i - 1][j - 1].setLabel(""+mark);
        }
        else
        {
            
            l.setText("INVALID MOVE!");
        }
    }
    
    public Label getStatusLabel()
    {
        return l;
    }
    
    public void actionPerformed(ActionEvent e)
    {
        Button b = (Button)e.getSource();
        
        for(int i = 0 ; i &lt; 3; i++ )
        {
            for(int j = 0; j &lt; 3; j++)
            {
                if(b == buttons[i][j])
                {
                    currMove = new Move();
                    currMove.setRow(i + 1);
                    currMove.setColumn(j + 1);
                    currMove.setIsValid(true);
                }
            }
        }
        
        
        synchronized(this)
        {
            this.notify();
        }
        
    }
    
    public Move getCurrMove()
    {
        return currMove;
    }
}

 

First, let us see the constructor of the new Board class AWTBoard. We create a Frame which is basically a window. We then create a Panel and add it to the content pane of the window created previously. We create a Border Layout for the previously added Panel with a top part and a bottom part. To the bottom part, we add a label to display any status messages needed to be displayed. To the top part of the Panel, we create a Panel with a Grid Layout to add a 3 X 3 Grid of Buttons and then add this panel to the main Panel. The Players play the game by taking turns to click the buttons in this grid.

We override the display method of the Board class to mark the buttons of the grid instead of outputting them to the console. Likewise, we override all those other methods which output to the console. The new method added is the actionPerformed method which is basically an event handler that tells Java what to do when the buttons in the 3 x 3 grid are clicked. getStatusLabel and getCurrMove are helper methods to enable passing data in and out of GUI Board.

AWTTicTacToe

Apart from the GUI Board, we need to introduce another class called AWTTicTacToe which will contain changes to invoke the GUI Board instead of the console.

package com.tictactoe.gameplay;

import com.tictactoe.components.*;

/**
 *
 * @author pratyush
 */
public class AWTTicTacToe {  /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        // TODO code application logic here 
        Game game = new Game(); 
        Player player1 = new Player(); 
        player1.setPlayerNum(1); 
        player1.setPlayerMark('X'); 
        player1.setGame(game); 
        Player player2 = new Player(); 
        player2.setPlayerNum(2); 
        player2.setPlayerMark('0'); 
        player2.setGame(game);
        
        //
        AWTBoard board = new AWTBoard();
        board.display();
        
        /*******/ 
        game.setWhoseTurn(player1); 
        game.setGameOver(false); 
        boolean status = game.isGameOver(); 
        // 
        do
        {
            int movesNow = Game.getMovesTillNow(); 
            if(movesNow == 9)
            {
                if(game.getWinner() == null)
                {
                    //
                    board.getStatusLabel().setText("TIE!\n");
                    break;
                }
            } 
            int turn = game.getWhoseTurn(); 
            //
            
            board.getStatusLabel().setText("PLAYER "+turn+" click a button\n"); 
            
            //
            try{
                synchronized(board)
                {
                    board.wait();
                }
            }
            catch(InterruptedException ie)
            {
                ie.printStackTrace();
            }
            
            Move move = board.getCurrMove();
            
            switch(turn)
            {
                case 1:
                    player1.makeMove(board, move); 
                    if(game.checkWinningMoves(player1))
                    {
                        game.setWinner(player1); 
                        //
                        board.getStatusLabel().setText("PLAYER 1 WINS!");
                        game.setGameOver(true);
                    }
                    else
                    {
                        if(move.isIsValid())
                        {
                            movesNow = Game.getMovesTillNow(); 
                            //
                            
                            board.getStatusLabel().setText("MOVE NUMBER "+movesNow+"\n");
                            game.setWhoseTurn(player2);
                        }
                    }
                break;
                case 2:
                    player2.makeMove(board, move); 
                    if(game.checkWinningMoves(player2))
                    {
                        game.setWinner(player2); 
                        //
                        
                        board.getStatusLabel().setText("PLAYER 2 WINS!");
                        game.setGameOver(true);
                    }
                    else
                    {
                        if(move.isIsValid())
                        {
                            movesNow = Game.getMovesTillNow(); 
                            // 
                            board.getStatusLabel().setText("MOVE NUMBER "+movesNow+"\n");
                            game.setWhoseTurn(player1);
                        }
                    }
                break;
                default:
                    //
                    board.getStatusLabel().setText("ERROR!\n");
                break;
            } 
            status = game.isGameOver();
        }
        while(!status); 
    } 
}

 

AWTTicTacToe is the main class containing the main method. It invokes the AWTBoard class instead of the Board class. It will not contain any statements to output to the console, although it may do so for debugging. To see the results of the invocation of this main class see the video below.

 

This GUI implementation of tic-tac-toe in Java is not perfect by any means. There is scope for improvement and new features can be added. Meanwhile, you can run this code and enjoy!

Convert Very Large Decimal Integers to Base 62 And Back

The other day I was trying to devise a way of converting arbitrarily large base 10 integers to the order of a billion billion to base 62 and did not get much help from the web. So I devised my own solution using the BC Math extension which ships with PHP by default. So, this solution works upto PHP_INT_MAX which is 9223372036854775807 for 64-bit platform. It also works upto 99 trillion on 32-bit-platform. I used an array as a stack to store successive remainders of division by the base, which is 62, and at the end popped them one by one from the stack to generate the converted base 62 number. The converse, multiplication by successive powers of 62 and addition of those powers helped to convert base 62 back to base 10.

First I used PHP OOPS to create a class called MyBase62Converter. The code is given below:

class MyBase62Converter
{
	private $base62StrVar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	private $baseInt = 62;
	
	function encode($decNum)
	{
		$base = $this->baseInt;
		
		$myStack = array();

		$remainder = 0;

		$base62Str = $this->base62StrVar;

		do 
		{
			
			$remainder = bcmod($decNum, $base);
			
			array_push($myStack, $remainder);
			
			$decNum = bcdiv(bcsub($decNum, $remainder), $base); 
			
		}
		while($decNum > 0);
		
		$binNum = '';

		while(count($myStack) > 0)
		{
			
			$binNum.= substr($base62Str, array_pop($myStack), 1);
		}

		return (strlen($binNum) >= 6)?$binNum: str_pad($binNum, 6, 0, STR_PAD_LEFT);
	}
	
	function decode($baseNum)
	{
		
		$base62Str = $this->base62StrVar;
		
		$base = $this->baseInt;

		$hashLen = strlen($baseNum);
		
		$decNum = '';
		
		for($i = 0; $i < $hashLen; $i++)
		{
			$decNum = bcadd($decNum, bcmul(bcpow($base, $i), strpos($base62Str , substr($baseNum, $hashLen - $i - 1, 1))));
		}
		
		return $decNum;
	}
	
}

Using the two simple encode and decode functions we can convert base 10 integers to base 62 representation and vice versa.

You can see the example below:

require_once("lib/class.MyBase62Converter.php"); 

$encoder = new MyBase62Converter();

echo "<br />";

echo PHP_INT_MAX." encoded is ".$encoded = $encoder->encode(PHP_INT_MAX);

echo "<br />";

echo $encoded." decoded is ".$decoded = $encoder->decode($encoded);

echo "<br />";
 
$largeNum = bcpow(62, 6) - 1; 

echo $largeNum." encoded is ".$encoded = $encoder->encode($largeNum); 

echo "<br />"; 

echo $encoded." decoded is ".$decoded = $encoder->decode($encoded); 

echo "<br />"; 

$veryLargeNum = bcpow(62, 7) - 1; //getting 0 due to num expressed in scientfic exponential notation 2.183401055849E+14 

echo $veryLargeNum." encoded is ".$encoded = $encoder->encode($veryLargeNum); 

echo "<br />"; 

echo $encoded." decoded is ".$decoded = $encoder->decode($encoded); 

echo "<br  />"; 

$max_num = 99999999999999; 

echo $max_num." encoded is ".$encoded = $encoder->encode($max_num , 62); //99999999999999 

echo "<br />"; 

echo $encoded." decoded is ".$decoded = $encoder->decode($encoded); 

echo "<br />"; 

$new_num = 63; 

echo $new_num." encoded is ".$encoded = $encoder->encode($new_num , 62);  

echo "<br />"; 

echo $encoded." decoded is ".$decoded = $encoder->decode($encoded);

The result of code execution is given below:

Simple File Searcher App: An Exercise in Concurrency

Here is a simple app for searching files on a computer. The app uses a recursive algorithm to compare names of files and folders with the search keyword and returns all the matches.

The procedure is as follows:

1.	list the roots of the filesystem
2.	for each root listed in step1:
	a.	list folders and files
	b.	for each file in a., compare keyword with file name.  
                If matched, list this file in results 
	c.	for each folder in a, 
		i.  compare keyword with folder name.  If matched, list this folder in results 
		ii. repeat 2a. for each folder
	d.	repeat a. to c. until no subfolders are found

The Java version is given below:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.filesearch.components;

import java.io.*;
import java.io.File.*;
import java.util.concurrent.*;
import java.util.Scanner;
/**
 *
 * @author Dell
 */
public class FileSearcherComponent implements Runnable{
    
    static String fileKeyword;
  
    static long count = 0;
  
    static File logFile;
  
    static BufferedWriter bw;
  
    private void logToFile(String path)
    {
  try{
    
    bw.write(path, 0, path.length());
    bw.newLine();
    
  }
  catch(IOException i)
  {
    i.printStackTrace();
  }
    }
    
    @Override
    public void run()
    {
  try{
      
    bw = new BufferedWriter(new FileWriter(logFile, true));
      
  }
  catch(IOException i)
  {
    i.printStackTrace();
  }
    
  long currTime = System.currentTimeMillis();
    
        File[] roots = File.listRoots(); //get drives
        
        for(File root:roots)
        {
            
            File rootFile = new File(root.getPath());
            
            traverseRoots(rootFile);
        }
    
  long endTime = System.currentTimeMillis();
    
  double seconds = (endTime - currTime) / 1000;
    
  System.out.printf("\n %d results in %f seconds.\n", count, seconds);
    
  try{
    
    bw.flush();
    
    bw.close();
  }
  catch(IOException i)
  {
    i.printStackTrace();
  }
    }
    
    private void traverseRoots(File root)
    {
        if(root.isDirectory())
        {
            
            String name = root.getName();

            if(name.contains(fileKeyword))
            {
                System.out.println(root.getAbsolutePath());
        
    logToFile(root.getAbsolutePath());
        
    count++;
            }
            
            File[] rootFolders = root.listFiles();

            if(rootFolders != null &amp;&amp; rootFolders.length &gt; 0){

                for(File rootFolder: rootFolders)
                {
                    if(rootFolder.isDirectory())
                    {
                        
                        String name1 = rootFolder.getName();

                        if(name1.contains(fileKeyword))
                        {
                            System.out.println(rootFolder.getAbsolutePath());
              
          logToFile(rootFolder.getAbsolutePath());
              
          count++;
                        }
                        
                        traverseRoots(rootFolder);
                    }
                    else if(rootFolder.isFile())
                    {
                        String name2 = rootFolder.getName();

                        if(name2.contains(fileKeyword))
                        {
                            System.out.println(rootFolder.getAbsolutePath());
              
          logToFile(rootFolder.getAbsolutePath());
              
          count++;
                        }
                    }
                    
                }
            }
        }
        else if(root.isFile())
        {
            String name3 = root.getName();

            if(name3.contains(fileKeyword))
            {
                System.out.println(root.getAbsolutePath());
        
    logToFile(root.getAbsolutePath());
        
    count++;
        
            }
        }
       
    }
    
    public static void main(String[] args)
    {
        FileSearcherComponent f = new FileSearcherComponent();
        
        ExecutorService es = Executors.newSingleThreadExecutor();
    
  logFile = new File("LOG.txt");
    
  if(logFile.exists())
  {
    logFile.delete();
  }
    
  try{
    
    logFile.createNewFile();
  }
  catch(IOException i)
  {
    i.printStackTrace();
  }
    
        System.out.print("Enter search keyword: ");
        
        fileKeyword  = new Scanner(System.in).nextLine();
    
        es.execute(f);	
    
    
    }
    
}

 

Copy, compile, run and ENJOY!