Thursday, November 30, 2017

MYSQL Backup Database Using Command Line | MYSQL Import / Restore Database Using Command Line

To take backup database, you need to execute following command:

mysqldump -u root -p password db_name > /tmp/sql_file.sql


And you can import/restore database using following command:

mysql -u root -p password db_name < /tmp/sql_file.sql



Simple try & catch TagLib | Tag Library for Grails GSP views

First you have to create a TagLib as below:









With following contents:


package com.pkm.taglib

class TryCatchTagLib {
    static namespace = "ui"

    def Try = { attrs, body ->
        try {
            out << body()
            request.exception = null
        }
        catch (Throwable e) {
            request.exception = e
        }
    }

    def Catch = { attrs, body ->
        if (request.exception) {
            out << body(exception: request.exception)
            request.exception = null
        }
    }
}


And use of try-catch as below:


<ui:try>
    SOME WORK I AM TRYING
</ui:try>
<ui:catch>
    GOT EXCEPTION=${exception}
</ui:catch>


Tuesday, November 21, 2017

Grails Groovy Sample DataSource Configuration For Database Connection

You need to edit DataSource.groovy file as below:


dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}



Grails Groovy Use Groovy Source Class As Singleton Bean | Custom Bean Definition | Transactional Bean



This will act as a transnational bean

First put the below settings to 'Config.groovy'

grails.hibernate.cache.queries = true
grails.databinding.convertEmptyStringsToNull = true

Need to add/modify below contents to 'BuildConfig.groovy' to enable database connection using MYSQL:

grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve
    legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        mavenLocal()
        grailsCentral()
        mavenCentral()
        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
        mavenRepo "https://oauth.googlecode.com/svn/code/maven"
    }

    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        compile "org.springframework:spring-orm:$springVersion"
        runtime 'mysql:mysql-connector-java:5.1.29'
        runtime 'org.springframework:spring-test:4.0.5.RELEASE'
        runtime "commons-httpclient:commons-httpclient:3.1"
        runtime "org.apache.httpcomponents:httpclient:4.3.3"
        runtime 'net.oauth.core:oauth-httpclient4:20090913'
    }

    plugins {
        build ":tomcat:7.0.55"
        runtime ":hibernate4:4.3.6.1"
        compile ":rendering:1.0.0"
        compile ":browser-detection:0.4.3"
        compile ':cache:1.1.8'
        compile ":mail:1.0.5"
        compile ":asset-pipeline:1.9.9"
        compile ':quartz:1.0.2'
    }
}

Below may be you database configuration (DataSource.groovy):

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}

Now create a domain class like below:

package com.pritom

class Home {
    Long id
    String name
    String roll

    static constraints = {
        name blank: false
        roll blank: false, unique: true
    }
}

Below is the most important class which will be act as a singleton bean in our system:

package com.pritom

import org.springframework.transaction.annotation.Transactional
/**
 * Created by pritom on 21/11/2017.
 */
@Transactional(rollbackFor = [Exception, NoClassDefFoundError])
class MyBean {
    {
        println("BEAN-INITIALIZATION----------------$from------------------")
    }

    private String from = null

    void setFrom(String x) {
        this.from = x
    }

    void testPrint(String a) {
        println("Bean-class=${this.toString()}===${a}-----------$from")
        Thread.sleep(2000L)
        if (true) new Home(name: "Home-" + Home.count(), roll: String.valueOf(System.currentTimeMillis())).save()
        println("Home-count=${Home.count()}")
        if (true) throw new NoClassDefFoundError("Yeah!!!")
    }
}

We are not completed yet, need to initialize bean from resource.groovy as below:

beans = {
    myBean(MyBean) { bean ->
        bean.scope = 'singleton' // Set bean as singleton
        from = "Resource.groovy" // Set value to a field of class MyBean when initializing
    }
}

And finally test bean from some controller like below:

package com.pritom

class HomeController {
    def myBean

    def index() {
        try {
            myBean.testPrint("1")
            myBean.testPrint("2")
        }
        catch (Throwable ex) {
            println("Error=${ex.getMessage()}")
        }
        render ""
    }
}

And you can download source code from here

Monday, November 20, 2017

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

I'm using a basic implementation of Jquery UI Tabs that are working fine but I want to set (or reset) the active tab dynamically based on a user action.



<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Tab 1</a></li>
        <li><a href="#tabs-2">Tab 2</a></li>
        <li><a href="#tabs-3">Tab 3</a></li>
    </ul>
    <div id="tabs-1">
        First tab
    </div>
    <div id="tabs-2">
        Second tab
    </div>
    <div id="tabs-3">
        Third tab
    </div>
</div>
<div class='log'></div>



$(function ($) {
    $("#tabs").tabs({
        active: 1,
        create: function (event, ui) {
            var newIndex = ui.tab.parent().children().index(ui.tab);
            $(".log").prepend("<div>Created fired for child=" + newIndex + "</div>");
        },
        activate: function (event, ui) {
            //  Get future value
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Activate fired for child=" + newIndex + "</div>");
        },
        beforeActivate: function (event, ui) {
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Before activate fired for child=" + newIndex + "</div>");
        }
    });
});







You can manually active a tab using below code (2 is index of tab):
$("#tabs").tabs("option", "active", 2);




Sunday, November 19, 2017

JQuery Load Javascript Dynamically | Dynamic JS Loading

JQuery Load Javascript Dynamically | Dynamic JS Loading



var script = document.createElement("SCRIPT");
script.src = '//code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
script.onload = function() {
    var nj = jQuery.noConflict(true);
    alert(jn.find("body").length);
};
document.getElementsByTagName("head")[0].appendChild(script);














Saturday, November 18, 2017

Finding the IP Number and MAC Address of a Network Card

At first need to open command prompt, press windows button and type cmd and open command prompt:




Now type "ipconfig" and below output would be generated:




You’ll see your IP address listed right above the subnet mask. Usually, it will say IPv4 Address and follow the prefix 192.168.1.# or 192.168.0.# for home networks as shown in the screenshot above.

Friday, November 17, 2017

JQuery Custom Checkbox Example | Checkbox Customization

It's easy to customize checkbox.



if (app === undefined) var app = {};
app.customCheckBox = (function() {
    var prop = null;

    function base() {
        if (!prop) {
            prop = $.prototype.prop;
            $.prototype.prop = function() {
                var elem = $(this), result = prop.apply(this, arguments);
                if (elem.is(".custom-checkbox-base-element")) {
                    elem.trigger("update_view");
                }
                return result;
            };
        }
    }

    return {
        convert: function(page) {
            base();

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').each(function() {
                var cb = $(this);
                cb.after("<span class='custom-checkbox-selection'></span>");
                if (cb.is(":checked")) cb.next().addClass("selected");
                cb.hide();
            });

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').change(function() {
                var cb = $(this);
                cb.next().trigger("update_view");
            });

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').on("update_view", function() {
                $(this).next().trigger("update_view");
            });

            page.find(".custom-checkbox-selection:not(.complete-event-compile)").click(function() {
                var elem = $(this), cb = elem.prev();
                if (elem.is(".selected")) {
                    elem.removeClass("selected").trigger("update_view");
                    cb.prop("checked", false).trigger("change");
                }
                else {
                    elem.addClass("selected").trigger("update_view");
                    cb.prop("checked", true).trigger("change");
                }
            });

            page.find('.custom-checkbox-selection:not(.complete-event-compile)').on("update_view", function() {
                var elem = $(this), cb = elem.prev();
                if (cb.is(":checked")) {
                    elem.addClass("selected");
                }
                else {
                    elem.removeClass("selected");
                }
            });
            page.find(".custom-checkbox-selection").addClass("complete-event-compile");
            page.find('input[type="checkbox"]').addClass("custom-checkbox-base-element");
        }
    };
}());








Thursday, November 16, 2017

JQuery form submission dynamically | Dynamic form submission

Below is the JQuery code snippet shows how to submit form dynamically:



<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("button").click(function () {
            var form = $("<form>", {
                'action': 'your-desired-url-here',
                'target': '_top'
            });
            $(document.body).append(form.hide());
            form.submit();
        });
    });
</script>

<button>Submit</button>










JavaScript Regex To Match Domain Name | Domain Validator Regex

Below is the required regex to validate any domain name, its simple so you can modify if you need to extend it.

^((http|https):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,10})$








Tuesday, November 14, 2017

JQuery JavaScript Select All Text In Content Editable Div

JQuery JavaScript Select All Text In Content Editable Div


jQuery.fn.selectText = function(){
   var doc = document;
   var element = this[0];
   if (doc.body.createTextRange) {
       var range = document.body.createTextRange();
       range.moveToElementText(element);
       range.select();
   }
   else if (window.getSelection) {
       var selection = window.getSelection();        
       var range = document.createRange();
       range.selectNodeContents(element);
       selection.removeAllRanges();
       selection.addRange(range);
   }
};

JSFiddle link



Saturday, November 11, 2017

jQuery DataTable Example

My Data-Tables Initialization Script is

$('table').dataTable();

And output as below:



JSFiddle link for DataTable example.

JavaScript Interval Example | SetInterval And ClearInterval

JavaScript setInterval & clearInterval example:



var i = 3;

var interval = setInterval(function() {
  if (i > 0) {
    $("div").html("Running " + i--);
  }
  else {
    clearInterval(interval);

    $("div").html("Stopped");
  }
}, 2000);


JSFiddle example link

Thursday, November 9, 2017

jQuery Number Text Field Validation Using Regex On Input Field

jQuery Number Text Field Validation Using Regex

Below is the full example of how to validate number using regex


var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)");

$(document.body).on("keypress", "input[type='text'].number", function (e) {
    if (e.which == 0 || e.which == 8) return true;
    var v = getTextFieldValue(this, String.fromCharCode(e.which));
    $("div").html(v);
    return pattern.test(v);
});

document.addEventListener("paste", function (e) {
    var v, f = $(e.target), ov = f.val();
    if (window.clipboardData && window.clipboardData.getData) { // IE
        v = window.clipboardData.getData('Text');
    }
    else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
        v = e.originalEvent.clipboardData.getData('text/plain');
    }
    else if (e.clipboardData && e.clipboardData.getData) {
        v = e.clipboardData.getData('text/plain');
    }
    v = getTextFieldValue(f[0], v);
    if (!pattern.test(v)) e.preventDefault();
    $("div").html(v);
});

function getTextFieldValue(input, nv) {
    var v = input.value, i = input.selectionStart, j = input.selectionEnd;

    if (i == 0 && j == v.length) return nv;
    else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j);
    else if (i == 0) return nv + v;
    else return v + nv;
}

$("input[type='text'].number").focus();


And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$

You can experience above example in JsFiddle

You can also check in regex test environment





Saturday, November 4, 2017

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure


You need to create your own configuration class as below:


package com.multidb.gorm

import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration
import org.hibernate.HibernateException
import org.hibernate.cfg.Configuration
import org.hibernate.dialect.Dialect
import org.hibernate.tool.hbm2ddl.DatabaseMetadata
import org.hibernate.tool.hbm2ddl.SchemaUpdateScript

class MyDbConfigClass extends GrailsAnnotationConfiguration {
    private GrailsApplication grailsApplication
    public static Configuration configuration = null

    @Override
    protected void secondPassCompile() {
        super.secondPassCompile()
        if (!configuration) {
            configuration = this
        }
    }

    @Override
    String[] generateDropSchemaScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateDropSchemaScript(dialect));
    }

    @Override
    String[] generateSchemaCreationScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateSchemaCreationScript(dialect));
    }

    @Override
    List<SchemaUpdateScript> generateSchemaUpdateScriptList(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        return super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
    }

    @Override
    String[] generateSchemaUpdateScript(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        List<SchemaUpdateScript> scripts = super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
        return SchemaUpdateScript.toStringArray(scripts)
    }

    private static String[] checkAndRemoveIgnoredTables(String[] sqlStatements) {
        println(sqlStatements)
        return sqlStatements
    }

    @Override
    void setGrailsApplication(GrailsApplication application) {
        // Run superclass method
        super.setGrailsApplication(application)

        // Inject Grails application reference
        this.grailsApplication = application
    }
}


Below is DataSource configuration:


dataSource {
    configClass = com.multidb.gorm.MyDbConfigClass
    driverClassName = "com.mysql.jdbc.Driver"
    dbCreate = "create"
    url = "jdbc:mysql://localhost/grails_db"
    username = "grails"
    password = "grails"
}