Wednesday, May 24, 2017

How to sign string as well sign request body with public key using Java

Below is a code snippet which will sign your request using Public key.


package com.pkm.src;

import Base64OutputStream;
import IOUtil;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * Created by pritom on 24/05/2017.
 */
public class SignatureSigner {
    public static void main(String[] args) throws Exception {
        String certificateFile = ".....\\publickey.cer";
        String requestBody = "Param1=Value_Of_Param1&Param2=Value_Of_param2";
        String signature = encodeRSASHA1(certificateFile, requestBody);
        System.out.println("Signature=" + signature);
    }

    protected static String encodeRSASHA1(String certificateFile, String requestBody) throws Exception {
        FileInputStream certIn1 = new FileInputStream(certificateFile);
        CertificateFactory e = CertificateFactory.getInstance("X509");
        X509Certificate myCertificate = (X509Certificate) e.generateCertificate(certIn1);

        MessageDigest hashGen = MessageDigest.getInstance("SHA1");
        byte[] hash = hashGen.digest(requestBody.getBytes("UTF-8"));
        Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsa.init(1, myCertificate);
        byte[] signature = rsa.doFinal(hash);

        ByteArrayInputStream sigIn = new ByteArrayInputStream(signature);
        ByteArrayOutputStream sigOut = new ByteArrayOutputStream();
        Base64OutputStream base64Out = new Base64OutputStream(sigOut, "");
        IOUtil.copy(sigIn, base64Out);
        base64Out.close();
        return new String(sigOut.toByteArray(), "US-ASCII");
    }
}

Which will output as below:

Signature=7GNccit4cY+rs4t/S0WBv.........+w1rYdiEO8PxuR3SQ=

Tuesday, May 23, 2017

Half Round Shape SVG Example

Below is a code snippet for half round shape SVG example:

<svg version="1.1" height="200px" width="200px"  xmlns="http://www.w3.org/2000/svg" >
      <clipPath id="cut-off-bottom">
          <rect x="0" y="0" width="200" height="100" fill="red"/>
      </clipPath>

      <circle cx="100" cy="100" r="100" clip-path="url(#cut-off-bottom)"  fill="red"/>
 
  <clipPath id="cut-off-bottom2">
          <rect x="0" y="0" width="200" height="100" fill="red"/>
      </clipPath>

      <circle cx="100" cy="100" r="80" clip-path="url(#cut-off-bottom2)"  fill="blue"/>
</svg>



Monday, May 22, 2017

Install Composer as Portable on Windows

Its sometimes we need Composer in our system but we don't want to install another extra software in our machine. So below is a simple nice script to do it without any hassle. Just you need to create an file named "Composer-installer.bat" with content below in any of your directory and double click on it. It will install composer in your system.

@ECHO OFF
REM Installs Composer as portable

REM Set Home folder as Composer Global Configuration Folder
SET COMPOSER_HOME=%~dp0Home
if not exist %COMPOSER_HOME% md "%COMPOSER_HOME%"

REM If PHP Path Not Set Yet
set PATH=%PATH%;c:\xampp\php

REM Download Composer
php -r "readfile('https://getcomposer.org/installer');" | php

SET COMPOSER_BAT=%~dp0composer.bat
if not exist "%COMPOSER_BAT" (
 echo @ECHO OFF> "%COMPOSER_BAT%"
 echo SET COMPOSER_HOME=%%~dp0Home>> "%COMPOSER_BAT%"
 echo if not exist %%COMPOSER_HOME%% md "%%COMPOSER_HOME%%">> "%COMPOSER_BAT%"
 echo php "%%~dp0composer.phar" %%*>> "%COMPOSER_BAT%"
 echo EXIT /B %%ERRORLEVEL%%>> "%COMPOSER_BAT%"

)
call composer --version | findstr /i /r /c:"Composer......version"

REM Increases Composer Time-out
call composer --quiet config --global process-timeout 3000

REM Set Local folder for Composer Internal Cache
SET COMPOSER_LOCAL=%~dp0Local
if not exist %COMPOSER_LOCAL% md "%COMPOSER_LOCAL%"
call composer --quiet config --global cache-dir "%COMPOSER_LOCAL%"
pause

Thursday, May 18, 2017

Growl Notification Example Web Application

Its now very easy to show our error or other types of messages in our web application easily. Growl is a nice plugin to display our target messages nicely in our web application. 

$('.error').click(function(event) {
    return $.growl.error({
        message: "Growl Error Message!"
    });
});
$('.notice').click(function(event) {
    return $.growl.notice({
        message: "Growl Notice Message!"
    });
});
$('.warning').click(function(event) {
    return $.growl.warning({
        message: "Growl Warning Message!"
    });
});








Download full example from here

AngularJS How to call controller function from outside of controller component

Its not a good practice to call AngularJS function from outside of its scope. But sometimes we need it badly. So there is a way around to do this easily.

You should note that scopes are initialized after the page is fully loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all. Below is a small code snippet to how you can achieve this easily:

var targetID = document.getElementById("AngularController");
angular.element(targetID).scope().init("Outside Controller");

Where "init" is function named in your controller as below:

var app = angular.module("myApp", []);
app.controller("AngularController", function($scope, $window) {
    $scope.init = function(res) {
        console.log("INIT INVOKED=" + res);
    };

    $scope.init("Controller Itself");
});








You can download full example from the link.


jQuery UI Popup Dialog Simple Example

Its fairly easy to implement jQuery popup dialog. You just need to include jQuery UI JS and CSS in your project and need to call the method as follows:

.dialog() with additional options as you want.

$("#dialog-form").dialog({
    title: "Dialog Title",
    width: 500,
    height: 400,
    autoOpen: false,
    modal: true,
    buttons: {
        "Ok": function() {
            $('#buttonExecute').val("Show Dialog - Yes");
            $(this).dialog("close");
        },
        "Cancel": function() {
            $('#buttonExecute').val("Show Dialog - No");
            $(this).dialog("close");
        }
    },
    close: function( event, ui ) {
        console.log(event);
        console.log(ui);
    },
    open: function( event, ui ) {
        $('#buttonExecute').val("Show Dialog - Open");
    }
});

$('#buttonExecute').click(function() {
    $("#dialog-form").dialog("open");
});


Which will show dialog as below screenshot:




You can download full example from below link:

Click here to download.


Monday, May 15, 2017

How to add header/footer to multipage pdf on Laravel SnappyPDF WkHtmlToPdf

I am sure you already install WkhtmlToPDF with Snappy in your Laravel project. If not yet please visit the link below to install WkhtmltoPDF in your Laravel project:

Click here.

Now add margin for your page if not added yet because header and footer need some space to visible in PDF header and footer area by editing the file named "config/snappy.php".

<?php
return array(
    'pdf' => array(
        'enabled' => true,
        'binary'  => 'C:\PROGRA~1\wkhtmltopdf\bin\wkhtmltopdf.exe',
        'timeout' => false,
        'options' => array(
            'margin-top'    => 15,
            'margin-right'  => 8,
            'margin-bottom' => 20,
            'margin-left'   => 5
        ),
        'env'     => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary'  => 'C:\PROGRA~1\wkhtmltopdf\bin\wkhtmltoimage.exe',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    )

);


And then append header and footer html in your PDF as follows:

$header_html = file_get_contents(resource_path() . "/" . "pdf-header.html");
$footer_html = file_get_contents(resource_path() . "/" . "pdf-footer.html");

$pdf = SnappyPDF::loadView('home.pdf');
$pdf->setOption('header-html', $header_html);
$pdf->setOption('footer-html', $footer_html);

return $pdf->stream('invoice.pdf');

You have to create two file named "pdf-header.html" and "pdf-footer.html" in your "resource" folder as below.

pdf-header.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body style="border: 1px solid blue;margin-left: 18px;margin-right: 0px;padding:10px">
<div style="color: red">
    THIS IS <b>PAGE HEADER</b>
</div>
</body>

</html>

pdf-footer.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body style="border: 1px solid blue;margin-left: 18px;margin-right: 0px;padding:10px">
<div style="color: red">
    THIS IS <b>PAGE FOOTER</b>
    Page=<span id="page"></span>|
    Total Page=<span id="topage"></span>|
    Date=<span id="date"></span>|
    Time=<span id="time"></span>
</div>
<script type="text/javascript">
    var vars={};
    var x=window.location.search.substring(1).split('&');
    for (var i in x) {
        var z=x[i].split('=',2);
        vars[z[0]] = unescape(z[1]);
    }
    document.getElementById('page').innerHTML = vars.page;
    document.getElementById('topage').innerHTML = vars.topage;
    document.getElementById('date').innerHTML = vars.date;
    document.getElementById('time').innerHTML = vars.time;
</script>
</body>

</html>




PDF will look like below images: