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.