Friday, May 2, 2014

Java Custom Annotations Example

Annotation: ClassAnnotation.java


package com.pkm.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //can use in class only.
public @interface ClassAnnotation {
    public enum Priority {
        LOW, MEDIUM, HIGH
     }

     Priority priority() default Priority.HIGH;

     String[] tags() default "";

     String name() default "Pritom";

     String date() default "02/05/2014";
}

Annotation: MethodAnnotation.java


package com.pkm.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //can use in method only.
public @interface MethodAnnotation {
    public boolean enabled() default false; 
}

Annotation: FieldAnnotation.java


package com.pkm.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //can use in field only.
public @interface FieldAnnotation {
    public boolean required() default false; 
    public boolean blank() default true;
    public int min() default 0;
    public int max() default 255;
}

Example Usage Of Custom Annotation: Example.java


package com.pkm.annotation;

@ClassAnnotation(name = "Pritom Kumar Mondal", priority = ClassAnnotation.Priority.MEDIUM, 
        tags = {"Pritom", "Kumar", "Mondal"})
public class Example {    
    @FieldAnnotation(required = true, blank = false, min = 10, max = 15)
    String name;
    
    @MethodAnnotation(enabled = true)
    void method1() {
        if(true) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
    
    @MethodAnnotation(enabled = false)
    void method2() {
        if(true) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
    
    @MethodAnnotation()
    void method3() {
        if(true) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}

Example Runner Class: RunExample.java


package com.pkm.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class RunExample {
    public static void main(String[] args) throws Exception {
        RunExample runExample = new RunExample();
        Example example = new Example();
        example.name = "Pritom Kumar Mondal";
        try {
            RunExample.validate(example);
            System.out.println("\n\nInfo: Validation successful");
        } catch (Exception ex) {
            System.out.println("\n\nError: " + ex.getMessage());
        }
    }
    
    public static boolean validate(Object object) throws Exception {
        Class obj = object.getClass();
        /* Process @ClassAnnotation */
        if (obj.isAnnotationPresent(ClassAnnotation.class)) {
            Annotation annotation = obj.getAnnotation(ClassAnnotation.class);
            ClassAnnotation classAnnotation = (ClassAnnotation) annotation;
            
            System.out.printf("%nPriority :%s", classAnnotation.priority());
            System.out.printf("%nCreatedBy :%s", classAnnotation.name());
            System.out.printf("%nTags :");
            int tagLength = classAnnotation.tags().length;
            for (String tag : classAnnotation.tags()) {
                if (tagLength > 1) {
                    System.out.print(tag + " ||| ");
                } else {
                    System.out.print(tag);
                }
                tagLength--;
            }

            System.out.printf("%nDate :%s%n%n", classAnnotation.date());
        }
        
        /* Process @MethodAnnotation */
        for (Method method : obj.getDeclaredMethods()) {
            if (method.isAnnotationPresent(MethodAnnotation.class)) {
                Annotation annotation = method.getAnnotation(MethodAnnotation.class);
                MethodAnnotation methodAnnotation = (MethodAnnotation) annotation;
                if(methodAnnotation.enabled()) {
                    System.out.println(method.getName() +" is enabled");
                } else {
                    System.out.println(method.getName() +" is not enabled");
                }
            }
        }
        
        /* Process @FieldAnnotation */
        for (Field field : obj.getDeclaredFields()) {
            if (field.isAnnotationPresent(FieldAnnotation.class)) {
                Annotation annotation = field.getAnnotation(FieldAnnotation.class);
                FieldAnnotation methodAnnotation = (FieldAnnotation) annotation;
                field.setAccessible(true);
                Object value = field.get(object);
                
                /* Checking: required */
                if(methodAnnotation.required()) {
                    System.out.println(field.getName() +" is required with value: " + value);
                    if(value == null) {
                        throw new Exception(field.getName() + " is required");
                    }
                } else {
                    System.out.println(field.getName() +" is not required");
                }
                
                /* Checking: blank */
                if(!methodAnnotation.blank()) {
                    System.out.println(field.getName() +" not blank with value: " + value);
                    if(value == null || value.toString().trim().length() == 0) {
                        throw new Exception(field.getName() + " not blank");
                    }
                } else {
                    System.out.println(field.getName() +" can blank");
                }
                
                /* Checking: min */
                System.out.println(field.getName() +" min length: " + methodAnnotation.min());
                if(value != null && value.toString().trim().length() < methodAnnotation.min()) {
                    throw new Exception(field.getName() + " must min length: " + methodAnnotation.min());
                }
                
                /* Checking: max */
                System.out.println(field.getName() +" max length: " + methodAnnotation.max());
                if(value != null && value.toString().trim().length() > methodAnnotation.max()) {
                    throw new Exception(field.getName() + " must max length: " + methodAnnotation.max());
                }
            }
        }
        return true;
    }
}

Example Output:


Priority :MEDIUM
CreatedBy :Pritom Kumar Mondal
Tags :Pritom ||| Kumar ||| Mondal
Date :02/05/2014

method1 is enabled
method2 is not enabled
method3 is not enabled
name is required with value: Pritom Kumar Mondal
name not blank with value: Pritom Kumar Mondal
name min length: 10
name max length: 15


Error: name must max length: 15

Monday, April 7, 2014

Create Refund Using PayPal Api

REST API Reference - PayPal

Create a file such named 'createRefund.php' using following contents:


<?php
session_start();
require './PaypalBase.php';
$paymentId = "";
$amount = 0;
if(isset($_GET["paymentId"]) && PaypalBase::isValidString($_GET["paymentId"])) {
    $paymentId = $_GET["paymentId"]; 
    $dataArray = array();
    if(isset($_GET["amount"]) && PaypalBase::isValidString($_GET["amount"]) 
            && floatval($_GET["amount"]) > 0) {
        $amount = floatval($_GET["amount"]);
        $dataArray = array(
            "amount" => array(
                "total" => floatval($_GET["amount"]),
                "currency" => "USD"
            )
        );
    }
    $refundArray = PaypalBase::createRefund($paymentId, $dataArray);
    PaypalBase::printR($refundArray);
    if($refundArray != NULL) {
        return;
    } else {
        echo "<br/><b>Error in refund</b>";
    }
}
?>
<form>
    Payment: <input type="text" name="paymentId" value="<?php echo $paymentId; ?>"/><br/>
    Amount: <input type="text" name="amount" value="<?php echo $amount; ?>"/><br/>
    <input type="submit" value="Process..."/>
</form>

createRefund method from 'PaypalBase.php'


<?php
public static function createRefund($paymentId, $dataArray = NULL) {
    self::info("createRefund");
    self::info("-----------------------------------------------");
    self::info("-----------------------------------------------");
    $accessToken = self::generateAccessToken(PPConstants::CLIENT_ID, PPConstants::CLIENT_SECRET);
    if(!$accessToken) {
        throw new Exception("Creating accessToken failed");
    }
    self::info("AccessToken: " . $accessToken);
    if(!$paymentId || strlen(trim($paymentId)) == 0) {
        throw new Exception("paymentId required");
    }
    self::info("Creating refund: $paymentId");

    $headers = array(
        'Content-Type: application/json',
        'Authorization: Bearer '.$accessToken,
        "PayPal-Request-Id" => self::generateRequestId(),
        "User-Agent" => self::getUserAgent()
    );
    if($dataArray != NULL && is_array($dataArray) && count($dataArray) > 0) {
        array_push($headers, "Content-Length: " . strlen(json_encode($dataArray)));
        self::info($dataArray);
    }
    if($dataArray != NULL && !is_array($dataArray) && strlen($dataArray) > 0) {
        array_push($headers, "Content-Length: " . strlen($dataArray));
        self::info($dataArray);
    }
    $paymentUrl = PPConstants::REST_SANDBOX_ENDPOINT.
            PPConstants::PAYMENT_GET_URL.$paymentId.PPConstants::PAYMENT_REFUND_URL;
    if(!self::$testMode) {
        $paymentUrl = PPConstants::REST_LIVE_ENDPOINT.
                PPConstants::PAYMENT_GET_URL.$paymentId.PPConstants::PAYMENT_REFUND_URL;
    }
    self::info("Payment url:$paymentUrl");
    $result = self::makeCurlCall($paymentUrl, "POST", json_encode($dataArray), NULL, $headers);
    $returnResult = NULL;
    if($result != NULL && is_array($result) 
            && isset($result["code"]) && isset($result["response"])) {
        $result = json_decode($result["response"]);
        if($result != NULL) {
            $returnResult = $result;
        }
    }
    self::info("Result: ");
    if($returnResult) {
        self::info($returnResult);
    } else {
        self::info($result);
    }
    return $returnResult;
}
?>

Output would be like this from valid refund:


stdClass Object
(
    [id] => 3E1338310M1546933
    [create_time] => 2014-04-07T13:08:52Z
    [update_time] => 2014-04-07T13:08:52Z
    [state] => completed
    [amount] => stdClass Object
        (
            [total] => 20.00
            [currency] => USD
        )

    [sale_id] => 6RE41122CN245801J
    [parent_payment] => PAY-99S90613BC814724UKNBKCVI
    [links] => Array
        (
            [0] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/refund/3E1338310M1546933
                    [rel] => self
                    [method] => GET
                )

            [1] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-99S90613BC814724UKNBKCVI
                    [rel] => parent_payment
                    [method] => GET
                )

            [2] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/sale/6RE41122CN245801J
                    [rel] => sale
                    [method] => GET
                )

        )

)

Output would be like this from invalid refund:


stdClass Object
(
    [name] => TRANSACTION_REFUSED
    [message] => The request was refused.{0}
    [information_link] => https://developer.paypal.com/webapps/developer/docs/api/#TRANSACTION_REFUSED
    [debug_id] => 58299c9502f28
)

Sunday, April 6, 2014

Create Payment Using PayPal Api

REST API Reference - PayPal

Create a form such named 'createPayment.php' using following contents:


<?php
session_start();
require './PaypalBase.php';

if(count($_POST) > 0) {
    $dataArray = array(
        "intent" => "sale",
        "payer" => array(
            "payment_method" => "credit_card",
            "funding_instruments" => array(
                array (
                    "credit_card" => array(
                        "number" => $_POST["card"],
                        "type" => "visa",
                        "expire_month" => $_POST["cardMonth"],
                        "expire_year" => $_POST["cardYear"],
                        "cvv2" => $_POST["cardCvv"],
                        "first_name" => $_POST["firstName"],
                        "last_name" => $_POST["lastName"]
                    )
                )
            )
        ),
        "transactions" => array(
            array(
                "amount" => array(
                    "total" => floatval($_POST["subTotal"]) + floatval($_POST["tax"]) + floatval($_POST["shipping"]),
                    "currency" => $_POST["currency"],
                    "details" => array(
                        "subtotal" => floatval($_POST["subTotal"]),
                        "tax" => floatval($_POST["tax"]),
                        "shipping" => floatval($_POST["shipping"])
                    )
                )
            )
        )
    );
    $paymentArray = PaypalBase::createPayment($dataArray);
    if($paymentArray != NULL) {
        PaypalBase::printR($paymentArray); return;
    } else {
        echo "<b>Error in payment</b>";
    }
} else {
    $_POST["card"] = "4417119669820331"; /* Test credit card */
    $_POST["firstName"] = "Pritom";
    $_POST["lastName"] = "Kumar Mondal";
    $_POST["cardMonth"] = "06";
    $_POST["cardYear"] = "2018";
    $_POST["cardCvv"] = "123";
    $_POST["subTotal"] = "20";
    $_POST["tax"] = "10";
    $_POST["shipping"] = "10";
    $_POST["currency"] = "USD";
}
?>
<form method="POST">
    <table>
        <tr>
            <td colspan="2"><i>Card Information</i></td>
        </tr>
        <tr>
            <td>Card Number</td>
            <td><input name="card" value="<?php echo $_POST["card"]; ?>"/></td>
        </tr>
        <tr>
            <td>Card Name</td>
            <td>
                <input name="firstName" value="<?php echo $_POST["firstName"]; ?>"/>
                <input name="lastName" value="<?php echo $_POST["lastName"]; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Card Expiry</td>
            <td>
                <input name="cardMonth" value="<?php echo $_POST["cardMonth"]; ?>"/>
                <input name="cardYear" value="<?php echo $_POST["cardYear"]; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Card CVV</td>
            <td><input name="cardCvv" value="<?php echo $_POST["cardCvv"]; ?>"/></td>
        </tr>
        <tr>
            <td colspan="2"><i>Product Information</i></td>
        </tr>
        <tr>
            <td>Currency</td>
            <td><input name="currency" value="<?php echo $_POST["currency"]; ?>"/></td>
        </tr>
        <tr>
            <td>Sub Total</td>
            <td><input name="subTotal" value="<?php echo $_POST["subTotal"]; ?>"/></td>
        </tr>
        <tr>
            <td>Tax</td>
            <td><input name="tax" value="<?php echo $_POST["tax"]; ?>"/></td>
        </tr>
        <tr>
            <td>Shipping</td>
            <td><input name="shipping" value="<?php echo $_POST["shipping"]; ?>"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Pay..."/></td>
        </tr>
    </table>
</form>

createPayment method from 'PaypalBase.php'


<?php
public static function createPayment($dataArray) {
    self::info("createpayment");
    self::info("---------------------------------------------------------");
    self::info("---------------------------------------------------------");
    $accessToken = self::generateAccessToken(PPConstants::CLIENT_ID, PPConstants::CLIENT_SECRET);
    if(!$accessToken) {
        throw new Exception("Creating accessToken failed", NULL, NULL);
    }
    self::info("AccessToken: " . $accessToken);
    $headers = array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen(json_encode($dataArray)), 
        'Authorization: Bearer '.$accessToken,
        "PayPal-Request-Id" => self::generateRequestId(),
        "User-Agent" => self::getUserAgent()
    );
    $paymentUrl = PPConstants::REST_SANDBOX_ENDPOINT.  PPConstants::PAYMENT_CREATE_URL;
    if(!self::$testMode) {
        $paymentUrl = PPConstants::REST_LIVE_ENDPOINT.  PPConstants::PAYMENT_CREATE_URL;
    }
    self::info("Url: " . $paymentUrl);
    $result = self::makeCurlCall($paymentUrl, "POST", json_encode($dataArray), NULL, $headers);
    $returnResult = NULL;
    if($result != NULL && is_array($result) && isset($result["code"]) && isset($result["response"]) && $result["code"] == 201) {
        $result = json_decode($result["response"]);
        if($result != NULL) {
            $returnResult = $result;
        }
    }
    self::info("Result: ");
    if($returnResult) {
        self::info($returnResult);
    } else {
        self::info($result);
    }
    return $returnResult;
}
?>

Output would be like this from valid payment:


stdClass Object
(
    [id] => PAY-3H999973GM723222TKNAVENY
    [create_time] => 2014-04-06T13:10:15Z
    [update_time] => 2014-04-06T13:10:30Z
    [state] => approved
    [intent] => sale
    [payer] => stdClass Object
        (
            [payment_method] => credit_card
            [funding_instruments] => Array
                (
                    [0] => stdClass Object
                        (
                            [credit_card] => stdClass Object
                                (
                                    [type] => visa
                                    [number] => xxxxxxxxxxxx0331
                                    [expire_month] => 6
                                    [expire_year] => 2018
                                    [first_name] => Pritom
                                    [last_name] => Kumar Mondal
                                )

                        )

                )

        )

    [transactions] => Array
        (
            [0] => stdClass Object
                (
                    [amount] => stdClass Object
                        (
                            [total] => 40.00
                            [currency] => USD
                            [details] => stdClass Object
                                (
                                    [subtotal] => 20.00
                                    [tax] => 10.00
                                    [shipping] => 10.00
                                )

                        )

                    [related_resources] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [sale] => stdClass Object
                                        (
                                            [id] => 0HU38682D5581260D
                                            [create_time] => 2014-04-06T13:10:15Z
                                            [update_time] => 2014-04-06T13:10:30Z
                                            [state] => completed
                                            [amount] => stdClass Object
                                                (
                                                    [total] => 40.00
                                                    [currency] => USD
                                                )

                                            [parent_payment] => PAY-3H999973GM723222TKNAVENY
                                            [links] => Array
                                                (
                                                    [0] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/sale/0HU38682D5581260D
                                                            [rel] => self
                                                            [method] => GET
                                                        )

                                                    [1] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/sale/0HU38682D5581260D/refund
                                                            [rel] => refund
                                                            [method] => POST
                                                        )

                                                    [2] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-3H999973GM723222TKNAVENY
                                                            [rel] => parent_payment
                                                            [method] => GET
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

    [links] => Array
        (
            [0] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-3H999973GM723222TKNAVENY
                    [rel] => self
                    [method] => GET
                )

        )

)

Friday, March 28, 2014

Using php get GMT time by changing server timezone


<?php
date_default_timezone_set("UTC");
$timezone = date_default_timezone_get();
echo "Current server timezone: " . $timezone;
echo "<br/>Current server time: " . date("Y-m-d H:i:s", time());
?>

Wednesday, March 26, 2014

Create/edit crn for nab transact

/**
* crn is the key of the token payment system of NAB transact.
* It must be a unique key against one account.
* And must be less than 20 characters length.
* Can contains a-z, A-Z, 0-9, space, underscore.
* To edit existing customer in NAB account, please 
* find the block '<actionType>addcrn</actionType>' in xml below
* and replace 'addcrn' with 'editcrn' and please provide 
* a valid crn existing against provided merchant account.
*/


<?php
/* TEST MERCHANT ID=XYZ0010 */
/* TEST PASSWORD=abcd1234 */
/* Replace this parameters when using in real transaction */
$nabXml = "<NABTransactMessage>
    <MerchantInfo>
        <merchantID>XYZ0010</merchantID>
        <password>abcd1234</password>
    </MerchantInfo>
    <RequestType>Periodic</RequestType>
    <Periodic>
        <PeriodicList count='1'>
            <PeriodicItem ID='1'>
                <actionType>addcrn</actionType>
                <periodicType>5</periodicType>
                <crn>ABDNK3D389D</crn>
                <CreditCardInfo>
                    <cardNumber>4444333322221111</cardNumber>
                    <expiryDate>01/15</expiryDate>
                </CreditCardInfo>
            </PeriodicItem>
        </PeriodicList>
    </Periodic>
</NABTransactMessage>";
/* LIVE URL=https://transact.nab.com.au/xmlapi/periodic */
$result = makeCurlCall(
    "https://transact.nab.com.au/xmlapidemo/periodic", /* CURL URL */
    "POST", /* CURL CALL METHOD */
    array( /* CURL HEADERS */
        "Content-Type: text/xml; charset=utf-8",
        "Accept: text/xml",
        "Pragma: no-cache",
        "Content_length: ".strlen(trim($nabXml))
    ),
    null, /* CURL GET PARAMETERS */
    $nabXml /* CURL POST PARAMETERS AS XML */
);
header('Content-type: text/xml');
echo $result["response"];
function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}
?>

And valid output would be like this:

<NABTransactMessage>
    <MessageInfo>
        <messageID/>
        <messageTimestamp>20142603215200606000+660</messageTimestamp>
        <apiVersion/>
    </MessageInfo>
    <MerchantInfo>
        <merchantID>XYZ0010</merchantID>
    </MerchantInfo>
    <Status>
        <statusCode>0</statusCode>
        <statusDescription>Normal</statusDescription>
    </Status>
    <RequestType>Periodic</RequestType>
    <Periodic>
        <PeriodicList count="1">
            <PeriodicItem ID="1">
                <actionType>addcrn</actionType>
                <crn>ABDNK3D389D</crn>
                <responseCode>00</responseCode>
                <responseText>Successful</responseText>
                <successful>yes</successful>
                <DirectEntryInfo>
                    <bsbNumber/>
                    <accountNumber/>
                    <accountName/>
                    <creditFlag>no</creditFlag>
                </DirectEntryInfo>
                <CreditCardInfo>
                    <pan>444433...111</pan>
                    <expiryDate>01/15</expiryDate>
                    <recurringFlag>no</recurringFlag>
                </CreditCardInfo>
                <currency>AUD</currency>
                <periodicType>5</periodicType>
                <paymentInterval/>
                <numberOfPayments/>
            </PeriodicItem>
        </PeriodicList>
    </Periodic>
</NABTransactMessage>