Friday, May 2, 2014

Iterate over each Entry in HashMap in Java Or loop Map to remove Entries

Example Class: HashMapIterator.java

package com.pkm.annotation;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author Pritom
 */
public class HashMapIterator {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1", "Value 1");
        map.put("key2", "Value 2");
        map.put("key3", "Value 3");
        map.put("key4", "Value 4");
        map.put("key5", "Value 5");
        
        /* Using Iterator */
        System.out.println("Using Iterator");
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iterator.next();
            System.out.println("Key: " + mapEntry.getKey() + ", Value: " + 
                    mapEntry.getValue());
            if(mapEntry.getKey().toString().equals("key3")) {
                /* Removing without ConcurrentModificationException */
                iterator.remove(); 
            }
        }
        
        /* Using Direct Entry Set */
        System.out.println("\nUsing Direct Entry Set");
        for (Object entry : map.entrySet()) {
            Map.Entry mapEntry = (Map.Entry) entry;
            System.out.println("Key : " + mapEntry.getKey() + ", Value : "
                    + mapEntry.getValue());
        }
        
        /* Using Direct Key Set */
        System.out.println("\nUsing Direct Key Set");
        for (Object entry : map.keySet()) {
            System.out.println("Key : " + entry + ", Value : "
                    + map.get(entry));
        }
    }
}

Example Output:

Using Iterator
Key: key4, Value: Value 4
Key: key3, Value: Value 3
Key: key5, Value: Value 5
Key: key2, Value: Value 2
Key: key1, Value: Value 1

Using Direct Entry Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Using Direct Key Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Getting All Field Names and their corresponding values using Java Reflection

A Java Class: User.java

package com.pkm.reflection;

public class User {
    String firstName;    
    String lastname;
}

Example Runner Class: GetAllFieldsAndValues.java

package com.pkm.reflection;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GetAllFieldsAndValues {
    public static void main(String[] args) {
        User user = new User();
        user.firstName = "Pritom";
        user.lastname = "Mondal";
        try {
            Map dataMap = GetAllFieldsAndValues.collectFieldValues(user);
            for (Object entry : dataMap.entrySet()) {
                Map.Entry mapEntry = (Map.Entry) entry;
		System.out.println("Key : " + mapEntry.getKey() + ", Value : "
			+ mapEntry.getValue());
            }
        } catch (Exception ex) {
            System.out.println("\n\nError: " + ex.getMessage());
        }
    }
    
    public static Map collectFieldValues(Object object) throws Exception {
        Map dataMap = new HashMap();
        Class obj = object.getClass();
        for (Field field : obj.getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(object);
            dataMap.put(field.getName(), value);
        }
        
        return dataMap;
    }
}

Example Output:

Key : lastname, Value : Mondal
Key : firstName, Value : Pritom

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
                )

        )

)