Tuesday, December 4, 2012

How to download and save a file from url using Java

Give a try to Java NIO:

try {
    URL url = new URL("http://portal.com/img/logo-header.gif");
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\src\\a.gif");
    fileOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (Exception ex) {
    ex.printStackTrace();
}

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html 

Sunday, December 2, 2012

jQuery Tabs Tutorial

See total result in jsFiddle

Html for tab

<ul class='tabs'>
    <li><a href='#tab1'>Tab 1</a></li>
    <li><a href='#tab2'>Tab 2</a></li>
    <li><a href='#tab3'>Tab 3</a></li>
</ul>
<div style='clear: both;'>&nbsp;</div>
<div class='tab_div' id='tab1'>
    <p>Hi, this is the first tab.</p>
</div>
<div class='tab_div' id='tab2'>
    <p>This is the 2nd tab.</p>
</div>
<div class='tab_div' id='tab3'>
    <p>And this is the 3rd tab.</p>
</div>

jQuery code to make tab


$('ul.tabs').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // If the location.hash matches one of the links, use that as the active tab.
    // If no match is found, use the first link as the initial active tab.
    $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.closest("ul").find(".active").removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $active.closest("li").addClass("active");
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
});

Css


ul {
    display: inline;
}
ul.tabs li {
    float: left;
    margin: 10px 15px 10px 0;
    list-style-type: none;
    border: 1px solid gray;
}
ul.tabs li a {
    text-decoration: none;
    padding: 5px;
}
ul.tabs li a.active {
    font-weight: bold;
    color: blue;
}
div.tab_div {
    background-color: gray;
    padding: 20px;
}

Output is as following

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