Thursday, November 29, 2012

ExtJS ComboBox with local store and change action listener.

new Ext.form.ComboBox({
    fieldLabel: '',
    id: 'searchtypeforcontacts',
    name: 'searchtype',
    x:200,
    labelSeparator :'',
    editable: false,
    store: new Ext.data.SimpleStore({
        fields: ['id', 'header'],
        data: [
            ['id', 'Contact Id'],
            ['first_name', 'Given Name'],
            ['email', 'Email'],
            ['country', 'Country'],
            ['state', 'State'],
            ['suburb_city', 'Suburb/City'],
            ['post_zip_code', 'Post/Zip Code']
        ]
    }),
    displayField: 'header',
    valueField: 'id',
    emptyText:'Search Contacts',
    typeAhead: true,
    mode: 'local',
    anchor: '40%',
    triggerAction: 'all',
    allowBlank: false,
    selectOnFocus: true,
    blankText: 'Select search type',
    listeners:{
        'select':function() {
            if (this.value == 'status') {
                //statusCombo.show();
                searchText.hide();
                $(".customerSearch").css({'margin-left':'210px','width':'auto'});
            } else {
                //statusCombo.hide();
                searchText.show();
                $(".customerSearch").removeAttr("style").css("width:auto;");
            }
        }
    }
})

Tuesday, November 27, 2012

How to find the length of a chinese phrase in a MySQL database with SQL

create table word(
  en_word text null,
  zh_word text null
);

insert into word values('Internet', '互联网');
insert into word values('Hello', '你好');

INVALID QUERY:
select
  LENGTH(en_word) as 'English Length',
  LENGTH(zh_word) 'Zh word length'
from word;

VALID QUERY:
select
  CHAR_LENGTH(en_word) as 'English Length',
  CHAR_LENGTH(zh_word) 'Zh word length'
from word;


















LENGTH returns length in bytes (and chinese is multibyte)
Use CHAR_LENGTH to get length in characters

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_length

phpWhois -base class to do whois queries with php

Code block:
        $pathMain = WWW_ROOT."..\\libs\\phpwhois\\whois.main.php";
        $pathUtils = WWW_ROOT."..\\libs\\phpwhois\\whois.utils.php";
        if(file_exists($pathMain) && file_exists($pathUtils)) {
            include_once($pathMain);
            include_once($pathUtils);
            $whois = new Whois();
            $whois->non_icann = true;
            $result = $whois->Lookup("yourcause22.com");
            print_r($result);
        }

Download WHOIS from:
http://www.phpwhois.org/
http://sourceforge.net/projects/phpwhois/?source=dlp

jQuery Back Button (go to previous page)

You can check history length by jQuery and if can not possible to go back you can remove it.

First in html page introduce a hyperlink:
<a href="javascript:void(0)" class="back_link">Back</a>

Then add the jQuery code block:
<script type='text/javascript'>
    if(history.length <= 1) {
        jQuery(".back_link").remove();
    }
    jQuery(".back_link").bind("click", function() {
        if(history.length > 1) {
            parent.history.back();
        }
        return false;
    });
</script>

Saturday, November 24, 2012

Get xml from a php webservice url using android

public String getXML(){
    String line = null;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet("http://example.com/a.php");

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        line = EntityUtils.toString(httpEntity);
    } catch (Exception ex) {
        Log.d("Error reading xml", ex.toString());
    }
    return line;
}
 
But if u are using your local host as test purpose then use 10.0.2.2
instead of localhost/127.0.0.1  

Replace a string in file using shell script

Suppose my file a.conf is as following
Include /1
Include /2
Include /3
I want to replace "Include /2" with a new line, I write the code in .sh file : 
line="Include \\/2"
rep=""
sed "s/${line}/${rep}/g" /root/new_scripts/a.conf > /tmp/a.conf-new
 
mv /tmp/a.conf-new /root/new_scripts/a.conf 

Encrypt a file using bash shell script

openssl des3 -salt -in /pritom/input.sql -out /pritom/output.pk -pass pass:pritom
 
where:
 /pritom/input.sql is the input file
 /pritom/output.pk is encrypted output file
 -pass pass: pritom (pritom is used as password) 

Insert arabic word to mysql database using java

    Connection con = null;
    String unicode= "?useUnicode=yes&characterEncoding=UTF-8"; 
    String url = "jdbc:mysql://localhost/";
    String db = "students";
    String driver = "com.mysql.jdbc.Driver";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url+db+unicode,"root","");
        Statement st = con.createStatement();
        String name = new String(txtName.getText().getBytes(), "UTF-8");
        int val = st.executeUpdate("insert into student(name, roll) "+
            " VALUES('"+name+"','"+txtRoll.getText()+"')");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
 
You have to create your database as a UTF-8 table otherwise no matter what you 
add it will never be able to store it... 


Ensure that your MySQL configuration encoding is defined correctly. Add these lines to either my.cnf "in the case if using linux" or my.ini "case you using windows"
[client] 
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
default-character-set=utf8
character-set-server=utf8

Thursday, November 22, 2012

Encrypt and decrypt string using AES 128 and PKCS7 algorithm using Php

Encrypt and decrypt string using AES algorithm executed by PHP script is given below:


<?php
function encrypt($key, $to_encrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
    $pad = $iv_size - (strlen($to_encrypt) % $iv_size);
    $to_encrypt = str_pad($to_encrypt, ($iv_size * (floor(strlen($to_encrypt) / $iv_size) + 1)), chr($pad));
    return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $to_encrypt, MCRYPT_MODE_CBC, $iv));
}

function decrypt($key, $to_decrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = substr($to_decrypt, 0, $iv_size);
    $to_decrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, substr($to_decrypt, $iv_size), MCRYPT_MODE_CBC, $iv);
    $pad = ord($to_decrypt[strlen($to_decrypt) - 1]);
    return substr($to_decrypt, 0, -$pad);
}

$key = "1111111111111111";

$str = "Value to be encrypt";
$enc = encrypt($key, $str);
$dec = decrypt($key, base64_decode($enc));

echo "Original=" . $str;
echo "<BR>Encrypted=" . $enc;
echo "<BR>Decrypted=" . $dec;

Below is output:

Original=Value to be encrypt
Encrypted=fyqhmBCGLVXcT5tvq38G/MAlpgP2FYq29wgC7KIMT8jt6Z45cq63oJeY8kGgv9QP
Decrypted=Value to be encrypt
 
 

Encrypt and decrypt string using AES algorithm using Java

Encrypt and decrypt string or bytes using AES algorithm performed by Java code. below is the code snippet. 

package com.pkm;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtils {
    private static String algorithm = "AES";
    private static byte[] keyValue = "1111111111111111".getBytes();
    private static SecureRandom iv = new SecureRandom("192837465UTYELBN".getBytes());
    
    public static void main(String[] args) throws Exception {
        String valueToEncrypt = "Some value";
        String encryptedValue = encrypt(valueToEncrypt);
        System.out.println("Encrypted=" + encryptedValue);
        
        String afterDecrypt = decrypt(encryptedValue);
        System.out.println("Decrypted=" + afterDecrypt);
    }

    static String encrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte [] encByte = cipher.doFinal(value.getBytes());
        String encString = new BASE64Encoder().encode(encByte);
        return encString;
    }

    static String decrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte [] decByte64 = new BASE64Decoder().decodeBuffer(value);
        byte [] decByte = cipher.doFinal(decByte64);
        String decString = new String(decByte);
        return decString;
    }

    static private Key generateKey() throws Exception {
        return new SecretKeySpec(keyValue, algorithm);
    }
}


Below is output:

Original=Some value
Encrypted=i4he5mR49eRkWmQRVh12yg==
Decrypted=Some value



Install Qmail and Vpopmail in Linux Server



1. For Linux Server
2. Required packages

There are four packages needed for this qmail install.

2.1 netqmail-1.06.tar.gz
qmail is a secure, reliable, efficient, simple message transfer agent. It is designed for typical Internet-connected UNIX hosts. As of October 2001, qmail is the second most common SMTP server on the Internet, and has by far the fastest growth of any SMTP server.

2.2 ucspi-tcp-0.88.tar.gz
It is a tool similar to inetd. ucspi-tcp listens in 25 port and spawns qmail-smtpd when required. ucspi-tcp stands for Unix Client Server Program Interface for TCP.

2.3 daemontools-0.76.tar.gz
daemontools is actually a tool to manage & monitor daemons linux. It is used in qmail as well to manage qmail daemons.

2.4 checkpassword-0.90.tar.gz
checkpassword provides a simple, uniform password-checking interface to all root applications. It is suitable for use by applications such as login, ftpd, and pop3d.

3. Qmail Install

3.1 Get the files

Download files and place them into the /usr/local/src directory. This document refers to that directory for install procedures.

========================================================
cd /usr/local/src
wget
http://www.qmail.org/netqmail-1.06.tar.gz
wget
http://cr.yp.to/ucspi-tcp/ucspi-tcp-0.88.tar.gz
wget
http://cr.yp.to/daemontools/daemontools-0.76.tar.gz
wget
http://cr.yp.to/checkpwd/checkpassword-0.90.tar.gz
=========================================================

Now create /package directory and move daemontools-0.76.tar.gz to /package.

=========================================================
mkdir /package
mv -iv /usr/local/src/daemontools-0.76.tar.gz /package
=========================================================

3.2 Create users and groups

Run following commands one by one, to create required users & groups

==============================================
groupadd nofiles
useradd -g nofiles -d /var/qmail qmaild
useradd -g nofiles -d /var/qmail qmaill
useradd -g nofiles -d /var/qmail qmailp
useradd -g nofiles -d /var/qmail/alias alias
groupadd qmail
useradd -g qmail -d /var/qmail qmailq
useradd -g qmail -d /var/qmail qmailr
useradd -g qmail -d /var/qmail qmails
==============================================

3.3 Compile & Install

Untar the Qmail source

============================
cd /usr/local/src
tar -xzvf netqmail-1.06.tar.gz
===========================

Compile the source

===================================
cd /usr/local/src/netqmail-1.06
make setup check
===================================

4. Configure Qmail

4.1 Post Installation setup

Post installation configuration can be done by running following script.

=============
./config;
==============

4.2 Configure Qmail aliases.

Create a user named "adminmails" to receive all administrator emails.

================================================
useradd adminmails;
cd ~alias;
echo "adminmails" > .qmail-postmaster;
echo "adminmails" > .qmail-mailer-daemon;
echo "adminmails" > .qmail-root;
echo "adminmails" > .qmail-postmaster;
echo "adminmails" > .qmail-abuse;
chmod 644 ~alias/.qmail* ;
==============================================

Create Maildir for "adminmails" user

========================================
su - adminmails
/var/qmail/bin/maildirmake ~/Maildir
========================================


4.3 Configure Qmail to use Maildir

Now we need to configure qmail to use the Maildir Format.

Create "/var/qmail/rc" with following contents.

====================================================================================

#!/bin/sh

# Using stdout for logging
# Using control/defaultdelivery from qmail-local to deliver messages by default

exec env - PATH="/var/qmail/bin:$PATH" \
qmail-start "`cat /var/qmail/control/defaultdelivery`"

=====================================================================================

Make "/var/qmail/rc" executable

============================

chmod 755 /var/qmail/rc

============================

Create "/var/qmail/control/defaultdelivery" file.

=====================================================

echo ./Maildir/ >/var/qmail/control/defaultdelivery

=====================================================

4.4 Replace Sendmail binaries

======================================================
chmod 0 /usr/lib/sendmail ;
chmod 0 /usr/sbin/sendmail ;
mv /usr/lib/sendmail /usr/lib/sendmail.bak ;
mv /usr/sbin/sendmail /usr/sbin/sendmail.bak ;
ln -s /var/qmail/bin/sendmail /usr/lib/sendmail ;
ln -s /var/qmail/bin/sendmail /usr/sbin/sendmail
=======================================================

5. Install ucspi-tcp

Untar the ucspi-tcp source.

=============================================================
cd /usr/local/src/
tar -xzvf ucspi-tcp-0.88.tar.gz
==============================================================

Patch ucspi-tcp with "ucspi-tcp-0.88.errno.patch" provided with net qmail.

==============================================================================
cd ucspi-tcp-0.88
patch < /usr/local/src/netqmail-1.06/other-patches/ucspi-tcp-0.88.errno.patch
===============================================================================

Install ucspi-tcp.

========================
make
make setup check
=========================

6. Install checkpassword

Untar checkpassword source.

=========================================
cd /usr/local/src
tar -xzvf checkpassword-0.90.tar.gz
=========================================

Patch checkpassword with "checkpassword-0.90.errno.patch" provided with net qmail.

================================================================
cd checkpassword-0.90
patch < /usr/local/src/netqmail-1.06/other-patches/checkpassword-0.90.errno.patch
================================================================

Install checkpassword.

==================================
make ;
make setup check
==================================

7. Install daemontools

Untar the daemontools source

=========================================
cd /package
tar -xzvf daemontools-0.76.tar.gz
=========================================

Patch daemontools with "daemontools-0.76.errno.patch" provided with net qmail.

=========================================================================
cd /package/admin/daemontools-0.76/src
patch < /usr/local/src/netqmail-1.06/other-patches/daemontools-0.76.errno.patch
=========================================================================

Install daemontools

====================
cd ..
package/install
====================

8. Qmail Startup script

The "qmailctl" script is used as startup script for qmail.

8.1 Download qmailctl

===========================================================
cd /var/qmail/bin/
wget
http://lifewithqmail.org/qmailctl-script-dt70
===========================================================

8.2 Setup qmailctl

========================================
mv -iv qmailctl-script-dt70 qmailctl
chmod 755 /var/qmail/bin/qmailctl
ln -s /var/qmail/bin/qmailctl /usr/bin
========================================

8.3 Modify qmailctl for qmail-pop3d

Add following lines to qmailctl's "start" section.

========================================================================
if svok /service/qmail-pop3d ; then
svc -u /service/qmail-pop3d /service/qmail-pop3d/log
else
echo qmail-pop3d supervise not running
fi
========================================================================

Add following lines to qmailctl's "stop" section.

======================================================================
echo " qmail-pop3d"
svc -d /service/qmail-pop3d /service/qmail-pop3d/log
======================================================================

Add following lines to qmailctl's "stat" section.

=======================================
svstat /service/qmail-pop3d
svstat /service/qmail-pop3d/log
=======================================

Add the following lines to qmailctl's "pause" section.

=======================================
echo "Pausing qmail-pop3d"
svc -p /service/qmail-pop3d
=======================================

Add following lines to qmailctl's "cont" section.

=======================================
echo "Continuing qmail-pop3d"
svc -c /service/qmail-pop3d
=======================================

Add following lines to qmailctl's "restart" section.

=========================================================
echo "* Restarting qmail-pop3d."
svc -t /service/qmail-pop3d /service/qmail-pop3d/log
=========================================================


9. Setup qmail-send & qmail-smtpd

9.1 Create supervise script directories for qmail daemons

Create supervise directories for qmail-send, qmail-smtpd & qmail-pop3d.

======================================================
mkdir -p /var/qmail/supervise/qmail-send/log
mkdir -p /var/qmail/supervise/qmail-smtpd/log
mkdir -p /var/qmail/supervise/qmail-pop3d/log
======================================================

9.2 Create supervise script for qmail-send

Create supervise script for qmail-send with name "/var/qmail/supervise/qmail-send/run".

The file should have following contents.

====================
#!/bin/sh
exec /var/qmail/rc
====================

9.3 qmail-send log daemon supervise script

Create qmail-send log daemon supervise script with name "/var/qmail/supervise/qmail-send/log/run".

The script should have following contents

===========================================================
 #!/bin/sh
exec /usr/local/bin/setuidgid qmaill /usr/local/bin/multilog t /var/log/qmail
======================================================================================

9.4 qmail-smtpd daemon supervise script

Create qmail-smtpd daemon supervise script with name "/var/qmail/supervise/qmail-smtpd/run".

The script should have following contents

=========================================================================================
#!/bin/sh

QMAILDUID=`id -u qmaild`
NOFILESGID=`id -g qmaild`
MAXSMTPD=`cat /var/qmail/control/concurrencyincoming`
LOCAL=`head -1 /var/qmail/control/me`

if [ -z "$QMAILDUID" -o -z "$NOFILESGID" -o -z "$MAXSMTPD" -o -z "$LOCAL" ]; then
echo QMAILDUID, NOFILESGID, MAXSMTPD, or LOCAL is unset in
echo /var/qmail/supervise/qmail-smtpd/run
exit 1
fi

if [ ! -f /var/qmail/control/rcpthosts ]; then
echo "No /var/qmail/control/rcpthosts!"
echo "Refusing to start SMTP listener because it'll create an open relay"
exit 1
fi

exec /usr/local/bin/softlimit -m 9000000 \
/usr/local/bin/tcpserver -v -R -l "$LOCAL" -x /etc/tcp.smtp.cdb -c "$MAXSMTPD" \
-u "$QMAILDUID" -g "$NOFILESGID" 0 smtp /var/qmail/bin/qmail-smtpd 2>&1
==========================================================================================

Create the concurrencyincoming control file.

======================================================
echo 20 > /var/qmail/control/concurrencyincoming
chmod 644 /var/qmail/control/concurrencyincoming
======================================================

9.5 qmail-smtpd log daemon supervise script

Create qmail-smtpd log daemon supervise script with name "/var/qmail/supervise/qmail-smtpd/log/run".

The script should have following contents

========================================================================================
#!/bin/sh
exec /usr/local/bin/setuidgid qmaill /usr/local/bin/multilog t /var/log/qmail/smtpd
========================================================================================

9.6 qmail-pop3d daemon supervise script

Create qmail-pop3d daemon supervise script with name "/var/qmail/supervise/qmail-pop3d/run" .

The script should have contents.

=================================================================================
#!/bin/sh
exec /usr/local/bin/softlimit -m 9000000 \
/usr/local/bin/tcpserver -v -R -H -l 0 0 110 /var/qmail/bin/qmail-popup \
FQDN /bin/checkpassword /var/qmail/bin/qmail-pop3d Maildir 2>&1
=================================================================================

Please replace FQDN with fully qualified domain name of the POP server
E.g: pop.example.com

9.7 qmail-pop3d log daemon supervise script

Create qmail-pop3d log daemon supervise script with name "/var/qmail/supervise/qmail-pop3d/log/run".

The script should have following contents

====================================================================
#!/bin/sh
exec /usr/local/bin/setuidgid qmaill /usr/local/bin/multilog t \
/var/log/qmail/pop3d
====================================================================

9.8 Create the log directories and add execute permissions on the run scripts.

=====================================================
mkdir -p /var/log/qmail/smtpd
mkdir /var/log/qmail/pop3d

chown qmaill /var/log/qmail
chown qmaill /var/log/qmail/smtpd
chown qmaill /var/log/qmail/pop3d

chmod 755 /var/qmail/supervise/qmail-send/run
chmod 755 /var/qmail/supervise/qmail-send/log/run

chmod 755 /var/qmail/supervise/qmail-smtpd/run
chmod 755 /var/qmail/supervise/qmail-smtpd/log/run

chmod 755 /var/qmail/supervise/qmail-pop3d/run
chmod 755 /var/qmail/supervise/qmail-pop3d/log/run
======================================================

10. Create soft link for the daemons in /service folder

10.1 Add qmail-send to /service folder

=================================================================
ln -s /var/qmail/supervise/qmail-send /service/qmail-send
=================================================================

10.2 Add qmail-smtpd to /service folder

===================================================================
ln -s /var/qmail/supervise/qmail-smtpd /service/qmail-smtpd
===================================================================

10.3 Add qmail-pop3d in /service folder.

=====================================================================
ln -s /var/qmail/supervise/qmail-pop3d /service/qmail-pop3d
=====================================================================

Note 1: The /service directory is created when daemontools is installed.

Note 2: The qmail system will start automatically shortly after these links are created.

If you don't want it running now, do: qmailctl stop



Reference
1.
http://tac-au.com/howto/qmail-mini-HOWTO.txt
4. http://kmaiti.blogspot.com/2010/05/how-to-install-qmail.html