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....

TOMCAT_HOME=/usr/local/tomcat-folder/

is_Running ()
{

        wget -O - http://yourserver.com/ >& /dev/null
 if( test $? -eq 0 ) then
  return 0
 else
  return 1
 fi
}


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
 fi
}
stop_Tomcat ()
{
 echo "shutting down......"
 $TOMCAT_HOME/bin/shutdown.sh
}

start_Tomcat ()
{
 echo "starting......"
 $TOMCAT_HOME/bin/startup.sh
}

restart ()
{
 stop_Tomcat
 sleep 10
 kill_Hanged_Processes
 start_Tomcat
 sleep 60
}

send_Mail ()
{
#!/bin/bash
# script to send simple email
# email subject
SUBJECT="Telegraphindia.com went down"
# Email To ?
EMAIL="mailid1@gmail.com,mailid2@gmail.com"
# Email text/message
EMAILMESSAGE="/tmp/emailmessage.txt"
echo $1 > $EMAILMESSAGE
#echo "This is email text" >>$EMAILMESSAGE
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE


}


moniter_Tomcat_Health ()
{
 while(true)
 do
  sleep $1
  is_Running
  if(test $? -eq 0 ) then
   echo "Tomcat is running properly........."
  else
   echo "Tomcat not Responding........."
   downat=`date`
   restart
   upat=`date`
   is_Running
   if(test $? -eq 0 ) then
    msg=" Tomcat Server was down at $downat and was  restarted successfully at $upat"
    echo "$msg"
    send_Mail "$msg"
   else
    msg=" Tomcat Server was down at $downat. Restart failed"
    echo "$msg"
    send_Mail "$msg"   
    exit 0
   fi
  fi
 done
}


#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)

or

yum install rpl (For Cent OS or RED HAT)

How to search and replace string in VI editor Linux


:%s/old_string/new_string/g
Find each occurrence of 'old_string' (in all lines), and replace it with 'new_string'.

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

:%s/old_string/new_string/gc
Change each 'old_string' to 'new_string', but ask for confirmation first.

:%s/\<old_string\>/new_string/gc
Change only whole words exactly matching 'old_string' to 'new_string'; ask for confirmation.

:%s/old_string/new_string/gci
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).
:%s/old_string/new_string/gcI
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="http://java.sun.com/portlet_2_0" 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="http://liferay.com/tld/theme" 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>
</div>
<%}%>

<%}%>

<%}%>

<%}%>







</div>

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...

 Liferay.fire(eventName, data)
 Liferay.on(eventName, function, [scope])


The bind method works like below...

 Liferay.bind(
   'nameOfEvent', 
   function(event, data){
     // Your javascript
     // data contains data.plid and data.portletId
   }
 );

The triggering of events are like below....

jQuery(
    function () {
      jQuery('a.someHtmlIdentifier').click(
        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........



 Liferay.bind(
   'nameOfEvent',
   function(event, data) {
     var userVar = data.Key;
     jQuery('.article-results').html('');
     if (userId) {
       jQuery.ajax(
         {
           url: '/our/portlet/url',
           data: {
           userVar: userVar
         },
         error: function() {
           jQuery('.article-results').html('' + 
                   Liferay.Language.get('sorry-there-was-an-error') + '');
         },
         success: function(message) {
           jQuery('.article-results').html(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

[mysqld]

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

bind-address=YOUR-SERVER-IP

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


Here
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 20.20.20.20 then you need to type following commands at mysql> prompt:mysql> CREATE DATABASE db1;
mysql> GRANT ALL ON db1.* TO user1@'20.20.20.20' IDENTIFIED BY 'SOME STRONG PASSWORD';


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

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

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;

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 10.2.70.3:

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

OR only allow remote connection from your lan subnet 21.21.21.21/24:

/sbin/iptables -A INPUT -i eth0 -s 21.21.21.21/24 -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 10.2.70.3:

pass in on $ext_if proto tcp from 10.2.70.3 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 23.23.23.23 –p
Where,

* -u user1: user1 is MySQL username
* -h IP or hostname:23.23.23.23 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

#top
(kill process f) option k

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


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(”mail.smtp.host”, “smtp.gmail.com”);
props.put(”mail.smtp.socketFactory.port”, “465″);
props.put(”mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”);
props.put(”mail.smtp.auth”, “true”);
props.put(”mail.smtp.port”, “465″);
ArrayList fileNames = new ArrayList();
fileNames.add(”C:/Write.txt”);
fileNames.add(”C:/Write1.txt”);
fileNames.add(”C:/Write2.txt”);
fileNames.add(”C:/Write3.txt”);
fileNames.add(”C:/25148.jpg”);

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(”from@no-spam.com”));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(”tomail@mail.com”));
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);
       System.out.println(fileNames.size());
       Multipart multipart = new MimeMultipart();
       BodyPart messageBodyPart = new MimeBodyPart();
       for(int i=0;i            {
                System.out.println(fileNames.get(i));
               
         
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource((String)fileNames.get(i));
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName((String)fileNames.get(i));
                multipart.addBodyPart(messageBodyPart);
                //message.setContent(multipart);
            }
     
       //multipart.addBodyPart(messageBodyPart);
       message.setContent(multipart);

Transport.send(message);

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 …….
<Resource
                     name=”mail/MailSession”

                     auth=”Container”
                     type=”javax.mail.Session”
                     mail.imap.host=”localhost”
                     mail.pop.host=”localhost”
                     mail.store.protocol=”imap”
                     mail.transport.protocol=”smtp”

mail.smtp.host=”smtp.gmail.com”
                     mail.smtp.port=”465″
                     mail.smtp.auth=”true”
                     mail.smtp.starttls.enable=”true”
                     mail.smtp.user=”your_user_id”
                     password=”your_password”
                     mail.smtp.socketFactory.class=”javax.net.ssl.SSLSocketFactory”
   />
   Now send mail from ur code using liferay mail engine util class…
String from = “mailidsomemail.com”;

String to = “tomailidsomemail.com”;

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…

<html>
<head>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js” type=”text/javascript”></script>

<script type =”text/javascript”>
var num = 1;
var jsonData = ” “;
function parseJSONDATA() {
  $(”#loaderDiv”).css(”display”, “block”);
  $(’.placeHolder’).html(”");
  num = 1;
  jsonData = $.trim($(”#txtData”).val());
  $.getJSON(jsonData, function (data) {
    $.each(data, function (key, val) {
      getJson(val);
    });
    $(”#loaderDiv”).css(”display”, “none”);
  });
}
function getJson(JData) {
$.each(JData, function (Jsonkey, Jsonval) {
    if (Jsonval && typeof Jsonval == “object”) {
      getJson(Jsonval);
    } else {
      if (num == 1) {
        $(’.placeHolder’).append(”<tr><th>Key</th><th>Value</td></th>”);
      }
      $(’.placeHolder’).append(”<tr><td>” + Jsonkey + “</td><td>” + Jsonval + “</td></tr>”);
      num = num + 1;
    }
  });
}
</script>
<title>
JSON Parser Example
</title>
</head>
<body>
<p>Enter JSON URL:</p>
<textarea rows=”3″ cols=”100″ id=”txtData”>
http://api.songkick.com/api/3.0/artists/219230/calendar.json?apikey=n93OW1Ys0trZKoSr&jsoncallback=?</textarea>
<br />
<input type=”button” value=”Submit” onClick=”javascript:parseJSONDATA();” />
<p></p>
<div id=”loaderDiv” style=”display:none;”>
loading… Please wait&nbsp;&nbsp;&nbsp;<img src=”http://trac.astrometry.net/export/18699/trunk/src/astrometry/net/static/images/loading.gif” />
</div>
<table border=”1″>
<tr class=”placeHolder”>
</tr>
</table>
</body>
</html>