Wednesday, July 10, 2013

Shell Script to check tomcat status and restart

The below script checks the status of a particular tomcat status and restarts it if the tomcat does not respond....


is_Running ()

        wget -O - >& /dev/null
 if( test $? -eq 0 ) then
  return 0
  return 1

kill_Hanged_Processes ()
 echo "killing hanged processes......"
 javaProcs=`ps -efl| grep -v grep | grep java`
 if(test ! -z "$javaProcs") then
  echo "nonzero"
  processId=`echo $javaProcs | awk '{ print $2} '`
  echo "$processId"
  kill -9 $processId
stop_Tomcat ()
 echo "shutting down......"

start_Tomcat ()
 echo "starting......"

restart ()
 sleep 10
 sleep 60

send_Mail ()
# script to send simple email
# email subject
SUBJECT=" went down"
# Email To ?
# Email text/message
#echo "This is email text" >>$EMAILMESSAGE
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE


moniter_Tomcat_Health ()
  sleep $1
  if(test $? -eq 0 ) then
   echo "Tomcat is running properly........."
   echo "Tomcat not Responding........."
   if(test $? -eq 0 ) then
    msg=" Tomcat Server was down at $downat and was  restarted successfully at $upat"
    echo "$msg"
    send_Mail "$msg"
    msg=" Tomcat Server was down at $downat. Restart failed"
    echo "$msg"
    send_Mail "$msg"   
    exit 0

#usage: moniter_Tomcat_Health  frequency
moniter_Tomcat_Health 5

Wednesday, May 1, 2013

How to search and replace string in all files in folders recursively in linux

Just use this command....

rpl -x'.php' -x'.html' -pR "old_tring" "new_string" *

To install rpl in linux use...

apt-get install rpl  (For debian users)


yum install rpl (For Cent OS or RED HAT)

How to search and replace string in VI editor Linux

Find each occurrence of 'old_string' (in all lines), and replace it with 'new_string'.

Find each occurrence of 'old_string' (in the current line only), and replace it with 'new_string'.

Change each 'old_string' to 'new_string', but ask for confirmation first.

Change only whole words exactly matching 'old_string' to 'new_string'; ask for confirmation.

Change each 'old_string' (case insensitive) to 'new_string'; ask for confirmation.

This may be wanted after using :set noignorecase to make searches case sensitive (the default).
Change each 'old_string' (case sensitive) to 'new_string'; ask for confirmation.

This may be wanted after using :set ignorecase to make searches case insensitive.
The g flag means global – each occurrence in the line is changed, rather than just the first. This tip assumes the default setting for the 'gdefault' and 'edcompatible' option (off), which requires that the g flag be included in %s///g to perform a global substitute. Using :set gdefault creates confusion because then %s/// is global, whereas %s///g is not (that is, g reverses its meaning).
When using the c flag, you need to confirm for each match what to do. Vim will output something like: replace with old_stringnew_string (y/n/a/q/l/^E/^Y)? (where old_stringnew_string is the replacement part of the :s/.../.../ command. You can type y which means to substitute this match, n to skip this match, a to substitute this and all remaining matches ("all" remaining matches), q to quit the command, l to substitute this match and quit (think of "last"), ^E to scroll the screen up by holding the Ctrl key and pressing E and ^Y to scroll the screen down by holding the Ctrl key and pressing Y. However, the last two choices are only available, if your Vim is a normal, big or huge built or the insert_expand feature was enabled at compile time (look for +insert_expand in the output of :version).

Also when using the c flag, Vim will jump to the first match it finds starting from the top of the buffer and prompt you for confirmation to perform replacement on that match. Vim applies the IncSearch highlight group to the matched text to give you a visual cue as to which match it is operating on (set to reverse by default for all three term types as of Vim 7.3). Additionally, if more than one match is found and you have search highlighting enabled with :set hlsearch, Vim highlights the remaining matches with the Search highlight group. If you do use search highlighting, you should make sure that these two highlight groups are visually distinct or you won't be able to easily tell which match Vim is prompting you to substitute.

Wednesday, February 20, 2013

Getting access to menu from portlet in liferay

The below code describes the way of accessing menu items from the portlet. Here i have called it from jsp. The best thing about this is you can use the beautiful permission management of menu items of liferay as well without bothering about that. Writing services for fetching menu names from the layout tables will need more codes for permission managements......

Hope this helps.........

* Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
<%@ page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@ page import="com.liferay.portal.kernel.util.WebKeys"%>
<%@ taglib uri="" prefix="portlet" %>
<%@page import="java.util.*"%>
<%@page import="com.liferay.portal.model.Layout"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ taglib uri="" prefix="liferay-theme" %>
<%@ page import="com.liferay.portal.theme.NavItem" %>
<%@ page import="com.liferay.portal.theme.RequestVars" %>

<portlet:defineObjects />
<liferay-theme:defineObjects />

<div style="width:100%">

//ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
String title = themeDisplay.getLayout().getName(themeDisplay.getLocale());


List<NavItem> navItems = new ArrayList<NavItem>();
if (layout != null) {
RequestVars requestVars = new RequestVars(request, themeDisplay, layout.getAncestorPlid(), layout.getAncestorLayoutId()); 
navItems = NavItem.fromLayouts(requestVars, layouts);

<%for (NavItem navItem : navItems){
if (navItem.getName().equalsIgnoreCase(title)){%>

<%if (navItem.hasChildren()){%>

for(NavItem navChild : navItem.getChildren()){

 <div style="float:left;" class="newsMenuPortlet">
<a href="<%= navChild.getURL() %>" <%= navChild.getTarget() %>><%= navChild.getName() %></a>





Monday, February 18, 2013

Inter-portlet communication in liferay

In this article we will discuss about the Client-side Inter-Portlet Communication......

The JSR-286 (Portlet 2.0) specification gives a mechanism for inter-portlet communication (IPC).
it is mainly started and supported in Liferay since version 5.1.Though there is no perticular solution that fits all the requirments, so Liferay gives an additional method based on JavaScript to perform client side communication.

The client-side mechanism communicates portlets on events.

An event-based model allows one portlet to provide a notification that something of significance has happened, without establishing any kind of hard dependency. Other portlets on the same page that are interested/configured in that event and have registered listeners are then able to act accordingly.

The API is very simple and is mainly based on two methods....

 Liferay.trigger(eventName, data)
 Liferay.bind(eventName, function, [scope])

The above methods have been deprecated in Liferay 6 and replaced with..., data)
 Liferay.on(eventName, function, [scope])

The bind method works like below...

   function(event, data){
     // Your javascript
     // data contains data.plid and data.portletId

The triggering of events are like below....

    function () {
        function(event) {
          var userId = jQuery(this).next().val();
          Liferay.trigger('nameOfEvent', {Key: Value});
          return false;

so the bind method for the above event is like this........

   function(event, data) {
     var userVar = data.Key;
     if (userId) {
           url: '/our/portlet/url',
           data: {
           userVar: userVar
         error: function() {
           jQuery('.article-results').html('' + 
                   Liferay.Language.get('sorry-there-was-an-error') + '');
         success: function(message) {

Hope this helps...

How To Enable Remote Access To MySQL Server?

Mysql server by default disables the remote access of the server... To access it from a remote host follow the below steps.....

Step # 1: Login to your mysql server with SSH.

Step # 2: Enable the networking in the server.

Now open the my.cnf file using your favourite editor. I used vi.

# vi /etc/my.cnf

Step # 3:Then locate line follows


Make sure line skip-networking is commented (or remove line) and add following line


For example, if your MySQL server IP is then entire block should be look like as follows:
user = mysql
pid-file = /var/run/mysqld/
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address =
# skip-networking

bind-address : IP address to bind to.

Dont forget to comment the line skip-networking to enable communication over tcp/ip.

Step# 4 Save and Close the file

Restart your mysql service to take change in effect:# /etc/init.d/mysql restart
Step # 5 Then grant access to the remote IP address

# mysql -u root -p mysqlGrant access to new database

If you want to add new database called db1 for user user1 and remote IP then you need to type following commands at mysql> prompt:mysql> CREATE DATABASE db1;

To Grant access to existing database... Do the following...

mysql> update db set Host='' where Db='db1';
mysql> update user set Host=' where user='user1';
Step # 5: Logout of MySQL
Or Just Use This....


Type exit command to logout mysql:mysql> exit
Step # 6: Open port 3306

/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

OR only allow remote connection from your web server located at

/sbin/iptables -A INPUT -i eth0 -s -p tcp --destination-port 3306 -j ACCEPT

OR only allow remote connection from your lan subnet

/sbin/iptables -A INPUT -i eth0 -s -p tcp --destination-port 3306 -j ACCEPT

A sample FreeBSD / OpenBSD pf rule ( /etc/pf.conf)

pass in on $ext_if proto tcp from any to any port 3306

OR allow only access from your web server located at

pass in on $ext_if proto tcp from to any port 3306 flags S/SA synproxy state

Step # 7: Now it's time to test

From remote system or your desktop type the command:
$ mysql -u user1 –h –p

* -u user1: user1 is MySQL username
* -h IP or hostname: is MySQL server IP address or hostname (FQDN)
* -p : Prompt for password

Tuesday, January 8, 2013

Virus f Opyum Team

Symptoms :: 
Several processes running named f or i. 
Network choked
Apache Dead
Unknown entry  * * * * * root f Opyum Team in crontab

Investigate ::
Try to kill the f process and even root will be unable to kill it. Check file named f and i in /etc or  /bin or /usr/sbin directory. Try to delete, the file f  will not delete.  Some unknown .jpg files will be there in the same folder. 

Solve :: The root is unable to delete the file f because of the immutable bit in f
To remove it use ses or chattr
Follow the below steps to remove it completely.....

remove the unknown .jpg files in system folders

(kill process f) option k

#ses -i /bin/f
#rm /bin/f
#ses -i /etc/crontab
#vi /etc/crontab (and delete last line)

Precautions ::  In my case the server was hacked bu Brute-force attack
So set a good password with a combination of upper,lower case letters and special characters.

Post your feedback or any issues you may face removing the virus.  Very less number of good threads are there explaining this topic. Hope it helps..........

Friday, November 16, 2012

Java Send Mail Using Gmail with Multiple Attachments

Here I am sharing a class for sending mail using Gmail SSL with multiple attachments.
Just change the gmailUsername and gmailPass with actual gmail credentials. And also change the to and from address with your desired one.
Here we have used Gmail SSL smtp port for sending mail. You can change it with your own mailing server details. 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
Author Mridul Chatterjee
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
public static void main(String[] args) {
Properties props = new Properties();
props.put(””, “”);
props.put(”mail.smtp.socketFactory.port”, “465″);
props.put(”mail.smtp.auth”, “true”);
props.put(”mail.smtp.port”, “465″);
ArrayList fileNames = new ArrayList();

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(”gmailUsername”,”gmailPass”);

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(””));
message.setSubject(”Testing Subject”);
message.setText(”Dear Mail Crawler,” +
“nn No spam to my email, please!”);
     //  multipart.addBodyPart(messageBodyPart);
     //  DataSource source = new FileDataSource(filename);
    //   messageBodyPart.setDataHandler(new DataHandler(source));
    //   messageBodyPart.setFileName(filename);
       Multipart multipart = new MimeMultipart();
       BodyPart messageBodyPart = new MimeBodyPart();
       for(int i=0;i            {
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource((String)fileNames.get(i));
                messageBodyPart.setDataHandler(new DataHandler(source));


System.out.println(”Mail Sent Successfully….”);

} catch (MessagingException e) {
throw new RuntimeException(e);

Sunday, October 28, 2012

How to Send Mail From Portlet in Liferay

Sending emails from portlets in liferay.

Place the below settings in ROOT.xml …….

   Now send mail from ur code using liferay mail engine util class…
String from = “”;

String to = “”;

String subject=”Test Subject”;

String body=”Hello world”;

MailEngine.send(from, to, subject, body);

To sent complex mails or attachments… follow the below code…

send( InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
            InternetAddress[] bcc, String subject, String body,
            boolean htmlFormat, InternetAddress[] replyTo, String messageId,
            String inReplyTo, File[] attachments);

Tuesday, August 21, 2012

An Example of Json Parsing with Jquery

Giving a very simple example of json parser using jquery..
It can parse any json feed and prints in key-value pairs in a table…
Check out…

<script src=”” type=”text/javascript”></script>

<script type =”text/javascript”>
var num = 1;
var jsonData = ” “;
function parseJSONDATA() {
  $(”#loaderDiv”).css(”display”, “block”);
  num = 1;
  jsonData = $.trim($(”#txtData”).val());
  $.getJSON(jsonData, function (data) {
    $.each(data, function (key, val) {
    $(”#loaderDiv”).css(”display”, “none”);
function getJson(JData) {
$.each(JData, function (Jsonkey, Jsonval) {
    if (Jsonval && typeof Jsonval == “object”) {
    } else {
      if (num == 1) {
      $(’.placeHolder’).append(”<tr><td>” + Jsonkey + “</td><td>” + Jsonval + “</td></tr>”);
      num = num + 1;
JSON Parser Example
<p>Enter JSON URL:</p>
<textarea rows=”3″ cols=”100″ id=”txtData”></textarea>
<br />
<input type=”button” value=”Submit” onClick=”javascript:parseJSONDATA();” />
<div id=”loaderDiv” style=”display:none;”>
loading… Please wait&nbsp;&nbsp;&nbsp;<img src=”” />
<table border=”1″>
<tr class=”placeHolder”>