Friday, May 15, 2015

Create Zip File Using Java From List Of Files


package com.pkm.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void main(String[] args) throws Exception {
         List<String> fileList = new ArrayList<>();
         fileList.add("ImageName.png");
         fileList.add("ImageName.jpg");
         fileList.add("ImageName.gif");
         createZip(fileList, "Output.zip");
    }

    public static void createZip(List<String> fileList, String zipFileName) 
              throws Exception {
         FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
         ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
  
         for(String inputFileName : fileList) {
             File file = new File(inputFileName);
             FileInputStream fileInputStream = new FileInputStream(file);
             ZipEntry zipEntry = new ZipEntry(inputFileName);
             zipOutputStream.putNextEntry(zipEntry);

             byte[] bytes = new byte[1024];
             int length;
             while ((length = fileInputStream.read(bytes)) >= 0) {
                 zipOutputStream.write(bytes, 0, length);
             }

             zipOutputStream.closeEntry();
             fileInputStream.close();
         }
  
         zipOutputStream.close();
         fileOutputStream.close();
    }
}

Using Java Create An Image And Save To File

package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Main {
    public static void main(String args[]) throws Exception {
 try {
     int width = 200, height = 200;
     // TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
     // into integer pixels
     BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     Graphics2D ig2 = bi.createGraphics();
  
     ig2.setColor(Color.red);
     ig2.fillRect(0, 0, width, height);
  
     ig2.setColor(Color.green);
     ig2.fillOval(0, 0, width, height);
 
     Font font = new Font("TimesRoman", Font.BOLD, 80);
     ig2.setFont(font);
     String message = "PKM";
     FontMetrics fontMetrics = ig2.getFontMetrics();
     int stringWidth = fontMetrics.stringWidth(message);
     int stringHeight = fontMetrics.getAscent();
     ig2.setPaint(Color.black);
   
     ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4); 
   
     ImageIO.write(bi, "PNG", new File("ImageName.PNG"));   
     ImageIO.write(bi, "JPEG", new File("ImageName.JPG"));   
     ImageIO.write(bi, "gif", new File("ImageName.GIF"));   
     System.out.println("Image Create Done");  
 }  
 catch (Exception ex) {  
     ex.printStackTrace();  
 } 
    }
}

Output


Saturday, May 9, 2015

jQuery get an elements position or offset according to some parent element


$.fn.offsetRelative = function(top){
    var $this = $(this);
    var $parent = $this.offsetParent();
    var offset = $this.position();
    
    // add scroll
    offset.top += $this.scrollTop()+$parent.scrollTop();
    offset.left += $this.scrollLeft()+$parent.scrollLeft();
    if(!top) {
        // Didn't pass a 'top' element
        return offset;
    } else if($parent.get(0).tagName == "BODY") {
        // Reached top of document
        return offset;
    } else if($($(top), $parent).length) {
        // Parent element contains the 'top' element we want the offset to be relative to
        return offset;
    } else if($parent[0] == $(this).closest(top)[0]) {
        // Reached the 'top' element we want the offset to be relative to
        return offset;
    } else {
        // Get parent's relative offset
        var parent_offset = $parent.offsetRelative(top);
        offset.top += parent_offset.top;
        offset.left += parent_offset.left;
        return offset;
    }
};

JSFiddle link


Friday, January 16, 2015

eWay Shared Rapid Payment Using PHP

First, create an api from eway api setup page for online hosted rapid payment



Then download source code.


Browse http://localhost/ewayHosted/index.php and fill up Api Key & Password field and following by other fields and click 'Pay...' button. 
If all details are correct you would get data like below from eway:


stdClass Object
(
    [SharedPaymentUrl] => https://secure-au.sandbox.ewaypayments.com/sharedpage/sharedpayment?AccessCode=F9802jxD7ElfeXKsdljElP1OKxSJyKZHJuaRB8qf97fzPPiDGFS-JmlfVug7kAvkctMALC0cSrVtKdomIp0DPlJv0CdRAl4apAHgJNzFMo5TXfQ804a8-5BP80gWFSmOLsLgeXOGFrjiuBvfYPjjs8F1zBw==
    [AccessCode] => F9802jxD7ElfeXKsdljElP1OKxSJyKZHJuaRB8qf97fzPPiDGFS-JmlfVug7kAvkctMALC0cSrVtKdomIp0DPlJv0CdRAl4apAHgJNzFMo5TXfQ804a8-5BP80gWFSmOLsLgeXOGFrjiuBvfYPjjs8F1zBw==
    [Customer] => stdClass Object
        (
            [CardNumber] => 
            [CardStartMonth] => 
            [CardStartYear] => 
            [CardIssueNumber] => 
            [CardName] => 
            [CardExpiryMonth] => 
            [CardExpiryYear] => 
            [IsActive] => 
            [TokenCustomerID] => 
            [Reference] => KU060238
            [Title] => Mr.
            [FirstName] => Pritom
            [LastName] => Kumar
            [CompanyName] => WEB ACTIVE
            [JobDescription] => Developer
            [Street1] => 15 Smith St
            [Street2] => 
            [City] => Phillip
            [State] => ACT
            [PostalCode] => 2602
            [Country] => au
            [Email] => 
            [Phone] => 1800 10 10 65
            [Mobile] => 1800 10 10 65
            [Comments] => Some comments here
            [Fax] => 02 9852 2244
            [Url] => http://www.yoursite.com
        )

    [Payment] => stdClass Object
        (
            [TotalAmount] => 100
            [InvoiceNumber] => INVOICE1001
            [InvoiceDescription] => Individual Invoice Description
            [InvoiceReference] => 513456
            [CurrencyCode] => AUD
        )

    [FormActionURL] => https://secure-au.sandbox.ewaypayments.com/AccessCode/F9802jxD7ElfeXKsdljElP1OKxSJyKZHJuaRB8qf97fzPPiDGFS-JmlfVug7kAvkctMALC0cSrVtKdomIp0DPlJv0CdRAl4apAHgJNzFMo5TXfQ804a8-5BP80gWFSmOLsLgeXOGFrjiuBvfYPjjs8F1zBw==
    [CompleteCheckoutURL] => 
    [Errors] => 
)

Then collect 'AccessCode' from data returned and redirect to 'SharedPaymentUrl' where your original payment would process.




Need to fill up all fields and click on 'PAY NOW' button above.



Now click on 'FINALIZE TRANSACTION' button to redirect back to your original site from where you went.



And finally your transaction in eWay portal:



Php & MySql oAuth2 Server & Client Example

Download source code and install


Add a new client secret pair to server side:


Start authorize from client side:



Authorize application from server side, add your login functionality by own to make the page restricted.


Now, you are getting your data from server using the access token. After expire access token, program automatically can collect new access token using refresh token.



Saturday, December 13, 2014

jQuery rounding number to nearest, flooring or ceiling as expected decimal point


function roundNumber(value, exp) {
    return decimalAdjust('round', value, exp);
}

function floorNumber(value, exp) {
    return decimalAdjust('floor', value, exp);
}

function ceilNumber(value, exp) {
    return decimalAdjust('ceil', value, exp);
}

function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
        return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
        return NaN;
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}

jQuery Rounding Number To Nearest Interval Such: 0.05, 0.5, 0.1, 5, 10, 100

JSFIDDLE LINK ||| TEXT LINK

Html Content:
<input type='text' name='number' style='width: 150px;' value='10.21'/>
<input type='text' name='round' style='width: 50px;' value='0.25'/>
<input type='text' name='dp' style='width: 50px;' value='2'/>
<input type='button' name='check' value='Check'/>
<div></div>

jQuery Content:


var div = $("div");
log("---------------------------------------------------------");

$("input[type='button']").click(function() {
    var number = parseFloat($("input[name='number']").val());
    var round = parseFloat($("input[name='round']").val());
    var dp = parseFloat($("input[name='dp']").val());
    if (!isNaN(number) && !isNaN(round) && !isNaN(dp)) {
        var nn = roundInterval(number, round, dp, "up");
        
        log("<br/>Rounding: " + numberToString(number, dp, true) + 
            " using: " + round + 
            "/" + "<span class='up-down'>Up</span>" + 
            " as: " + numberToString(nn, dp, true));
        
        var nn = roundInterval(number, round, dp, "down");
        
        log("<br/>Rounding: " + numberToString(number, dp, true) + 
            " using: " + round + 
            "/" + "<span class='up-down'>Down</span>" + 
            " as: " + numberToString(nn, dp, true));
        
        log("---------------------------------------------------------");
    }
});
$("input[type='button']").trigger("click");

function roundInterval(number, interval, round, roundType) {
    if (round > 9) {
        round = 9;
    }
    else if (round < 0) {
        round = 0;
    }
    number = number > 999999999999999 ? 999999999999999 : number;
    var isMinus = false;
    if (number < 0) {
        isMinus = true;
        number = number * -1;
    }
    number = parseFloat(numberToString(number, round));
    interval = parseFloat(numberToString(interval, round));
    var multiplier = roundType == 'up' ? Math.ceil(number / interval) : Math.floor(number / interval);
    
    log("Multiplier: " + multiplier);
    log("As: " + number + "/" + interval + " :: " + (number/interval));
    
    number = multiplier * interval;
    
    number = multiplier * interval;
    if (isMinus) {
        number = number * -1;
    }
    return parseFloat(number.toFixed(round));
}

function numberToString(number, dp, asDp) {
    var format = '#';
    if (asDp === undefined || asDp == null) {
        asDp = false;
    }
    if (dp !== undefined && dp != null && !isNaN(dp)) {
        if (dp > 9) {
            dp = 9;
        }
    }
    else {
        dp = 0;
    }
    if (dp > 0 && asDp) {
        format += ".";
        format += "0000000000".substr(0, dp);
    }
    else if (dp > 0) {
        format += ".";
        format += "##########".substr(0, dp);
    }
    number = number.toString();
    var minus = number.substr(0, 1) == '-' ? '-' : '';
    var ln = "";
    if (number.lastIndexOf("e+") > -1) {
        ln = number.substr(0, number.lastIndexOf("e+"));
        for (var i = ln.length - 2; i < parseInt(number.substr(number.lastIndexOf("e+") + 1)); i++) {
            ln += "0";
        }
        ln = ln.replace(/[^0-9]/g, '');
        number = ln;
    }
    var tail = format.lastIndexOf('.'), nail = number.lastIndexOf('.');
    if (nail < 0 && tail >= 0) {
        number = number + "." + format.substr(tail + 1, 1);
        nail = number.lastIndexOf('.');
    }
    tail = tail > -1 && nail > -1 ? format.substr(tail) : '';
    var numtail = number.substr(number.indexOf(".") ) ;
    if(tail.length > 0 && dp !== undefined && dp > 0) {
        tail = tail.substr(0, dp + 1);
        var tails = tail.split(''), ntail = "", canPop = true;
        for (var i = 1; i < tails.length; i++) {
            if ((tails[i] == '#' || tails[i].match(/([0-9])/g)) && numtail.length > i) {
                ntail += numtail.substr(i, 1);                    
            }
            else if(tails[i] == '#') {
                ntail += '0';
            }
            else {
                ntail += tails[i];
            }
        }
        var ttail = ntail.split(''), ptail = tail.substr(1).split('');
        for(var i = ttail.length - 1; i > -1; i--){
            if (ptail[i] == '#' && canPop && (ttail[i] == '0' || ttail[i] == '#')) {
                ntail = ntail.substr(0, ntail.length - 1);
            }
            else {
                canPop = false;
            }
        }
        if (ntail.length > 0) {
            tail = "." + ntail;
        }
        else {
            tail = "";   
        }
    }
    number = number.replace(/\..*|[^0-9]/g,'').split('');
    format = format.replace(/\..*/g,'').split('');
    for(var i = format.length - 1; i > -1; i--){
        if(format[i] == '#') {
            format[i]=number.pop()
        }
    }
    number = minus + number.join('') + format.join('') + tail;
    return number;
}

function log(m) {
    div.prepend(m + "<br/>");
}