Monday, August 28, 2017

CLEditor Auto Grow Example



Very first position of cleditor:

After grow (change of content) of cleditor:




$(document).ready(function () {
    var panel = $(document.body).find(".editor-container");

    //https://premiumsoftware.net/cleditor/gettingstarted
    panel.find(".editor").cleditor().on("change", function () {
        this.$area.trigger("rich_editor_content_changed");
    });
    var iframe = panel.find("iframe"), iframe_body = iframe.contents().find("body");
    iframe.parent().css("height", "auto");
    iframe.attr("scrolling", "no");

    iframe.contents().find("body").bind("wheel", function(e, delta) {
        iframe.css("pointer-events", "none");
        clearTimeout($.data(this, 'mousewheel'));
        $.data(this, 'mousewheel', setTimeout(function() {
            iframe.css("pointer-events", "auto");
        }, 200));
    });

    panel.find(".cleditorMain").on('mousedown', function(e, delta) {
        iframe.css("pointer-events", "auto");
    });

    setTimeout(function () {
        panel.find("textarea").on("rich_editor_content_changed", function () {
            iframe.css("height", iframe_body.height() + 30);
        }).trigger("rich_editor_content_changed");
    }, 100);
});



Perfect Scrollbar Example

Perfect Scrollbar Example




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Perfect Scrollbar Example</title>
    <script src="jquery-1.11.1.min.js"></script>
    <script src="perfect-scrollbar.jquery.min.js"></script>
    <link rel="stylesheet" href="perfect-scrollbar.css"/>
    <style type="text/css">
        .scroll {
            top: 100px;
            left: calc(50% - 250px);
            position: relative;
            padding-right: 9px;
        }

        .scroll p {
            padding: 20px;
            margin-left: 7px;
            border: 2px solid #404040;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".scroll").perfectScrollbar();
            $(".scroll").perfectScrollbar("update");
        });
    </script>
</head>
<body>
    <div class="scroll" style="height:500px;width:500px;border:1px solid red;overflow:scroll">
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <p>Paragraph 3</p>
        <p>Paragraph 4</p>
        <p>Paragraph 5</p>
        <p>Paragraph 6</p>
        <p>Paragraph 7</p>
        <p>Paragraph 8</p>
        <p>Paragraph 9</p>
        <p>Paragraph 10</p>
        <p>Paragraph 11</p>
        <p>Paragraph 12</p>
        <p>Paragraph 13</p>
        <p>Paragraph 14</p>
        <p>Paragraph 15</p>
        <p>Paragraph 16</p>
        <p>Paragraph 17</p>
        <p>Paragraph 18</p>
        <p>Paragraph 19</p>
        <p>Paragraph 20</p>
    </div>
</body>
</html>


Tuesday, August 22, 2017

Grails render view from service | Grails Goodness: Render GSP Views And Templates Outside Controllers | Cannot use the session in non-request rendering operations in grails

Grails render view from service | Grails Goodness: Render GSP Views And Templates Outside Controllers | Cannot use the session in non-request rendering operations in grails.


import grails.util.Holders
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib

class PageRenderedUtils {
    static final String gPath = "org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib"

    static void example() {
        renderTemplate("/user/info", [id: 1L, name: "Pritom Kumar"])
    }

    static String renderTemplate(String template, Map model) {
        return g.render(template: template, model: model)
    }

    static ApplicationTagLib getG() {
        return (ApplicationTagLib) Holders.applicationContext.getBean(gPath)
    }
}

Saturday, August 5, 2017

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body.
Note:-
  • Make sure the returned value from the method call is returned from the closure as well
  • Might be a expensive of a class has number of methods with heavy implementation
  • If selective execution is required, then check for the method name and then intercept the call


class Dummy {
    def method1() { 
        System.out.println "In method 1"
    }

    def method2(String str) { 
        System.out.println "In method 2"
    }
    
    static def method3(int a, int b) {
        System.out.println "In static method 3" 
    }    
}

Dummy.metaClass.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after $name was called with args $args")

   return result
}

Dummy.metaClass.'static'.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before static method $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after static method $name was called with args $args")

   return result
}

def dummy = new Dummy()
dummy.method1()
dummy.method2('Test')
Dummy.method3(1, 2)

Saturday, July 29, 2017

Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel

At first need to create an Job class inside "project/app/jobs" directory. Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel.

Sample job class:


<?php
namespace App\Jobs;

use Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class MyTestJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels, Queueable;

    private $param1;
    private $param2;

    public function __construct($param1, $param2)
    {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }

    public function handle(Mailer $mailer)
    {
        /* After 3 Times Failed, Job Will Be Released From Queue */
        if ($this->attempts() > 3) {
            Log::info("Max try failed");
            return;
        }
        $to_email = "pritomkucse@gmail.com";
        $mailer->send('emails.some_file_name',
            [
                'param1' => "Param1 value",
                'param2' => "Param2 value"
            ],
            function ($message) use ($to_email) {
                $message->from('from@address.domain', 'From Text');
                $message->subject("Test Subject");
                $message->to($to_email);
            });
    }
}

Below line is to schedule job with 30 seconds delay:

app("Illuminate\\Contracts\\Bus\\Dispatcher")->dispatch((new MyTestJob("1", "2"))->delay(30)); 

And this is time to start queue for job listen. Open command prompt and navigate to "laravel_project"/"project" and execute following command:

php artisan queue:listen --timeout=120

And every time a new job scheduled, this command will execute them on time. 

Friday, July 28, 2017

How to encode BASE64 via MySQL | MySQL from BASE64 | BASE64 ENCODE AND DECODE IN MySQL | BASE64 encode in MySQL

How to encode BASE64 via MySQL | MySQL from BASE64 | BASE64 ENCODE AND DECODE IN MySQL | BASE64 encode in MySQL

I want to select a blob col from one table, BASE64 encode it and insert it into another tables. Is there any way to do this without round tripping the data out of the DB and through my app?

I was looking for the same thing and I've just seen that MySQL 5.6 has a couple of new string functions supporting this functionality: TO_BASE64 and FROM_BASE64.

SELECT FROM_BASE64('YmFzZTY0IGVuY29kZWQgc3RyaW5n');


SELECT TO_BASE64(field_name) FROM table_name;

Thursday, July 27, 2017

Grails Groovy SessionFactory EnityKey SessionStatistics | Grails Get SQL Table Name From Domain Class | Grails Get SQL Table Field Name From Domain Class

Grails Groovy SessionFactory EnityKey SessionStatistics | Grails Get SQL Table Name From Domain Class | Grails Get SQL Table Field Name From Domain Class.


import org.hibernate.SessionFactory
import grails.util.Holders
import org.hibernate.engine.spi.EntityKey
import org.hibernate.stat.SessionStatistics
/**
 * Created by pritom on 27/07/2017.
 */
class HibernateSessionUtil {
    private static SessionFactory _sessionFactory

    public static void main(String[] args) {
        def domainInstance = "DomainClass".proxy(100L)
        checkIfObjectExistsInSession(domainInstance)
    }

    static void evictAllEntities() {
        SessionStatistics sessionStatistics = sessionFactory.currentSession.getStatistics()
        sessionStatistics.getEntityKeys().asList().each { EntityKey entityKey ->
            evict(entityKey.persisterClass.proxy(entityKey.identifier.toString().toLong()))
        }
    }

    static void evict(def instance) {
        sessionFactory.currentSession.evict(instance)
    }

    static Boolean checkIfObjectExistsInSession(def domainInstance) {
        SessionStatistics sessionStatistics = sessionFactory.currentSession.getStatistics()
        println("Total ${sessionStatistics.getEntityKeys().asList().size()} Object Exists in Session")
        Boolean exists = false
        sessionStatistics.getEntityKeys().asList().find { EntityKey entityKey ->
            println("EntityName=${entityKey.entityName},EntityId=${entityKey.identifier.toString()}")
            if (domainInstance.class.canonicalName.equals(entityKey.entityName) && domainInstance.id.toString().equals(entityKey.identifier.toString())) {
                exists = true
            }
        }
        return exists
    }

    static String getTableFieldName(Class clazz, String fieldName) {
        return sessionFactory.getClassMetadata(clazz).propertyMapping.getColumnNames(fieldName)[0]
    }

    static String getTableName(Class clazz) {
        return sessionFactory.getClassMetadata(clazz).getTableName()
    }

    static boolean flushAndClearCache() {
        try {
            sessionFactory.currentSession.flush()
            sessionFactory.currentSession.clear()
            sessionFactory.getCache().evictEntityRegions()
            sessionFactory.getCache().evictCollectionRegions()
            sessionFactory.getCache().evictDefaultQueryRegion()
            sessionFactory.getCache().evictQueryRegions()
            return true
        }
        catch (Exception ex) {
            ex.printStackTrace()
            return false
        }
    }

    static SessionFactory getSessionFactory() {
        _sessionFactory = _sessionFactory ?: (_sessionFactory = Holders.applicationContext.getBean(SessionFactory))
    }

    static {
        EntityKey.metaClass.getPersisterClass = {
            return persister.entityTuplizer.mappedClass
        }
    }
}

c