Monday, February 10, 2014

Use grails service from java class


package com.groovy.exception

import com.services.TestService
import org.springframework.context.ApplicationContext
import org.codehaus.groovy.grails.web.util.WebUtils

/**
 * Created by pritom on 9/02/14.
 */
class CustomException extends RuntimeException {
    private static TestService testService;
    String message;
    List args = [];

    public CustomException(String message, List args) {
        this.message = message;
        this.args = args;
    }

    public String getMessage() {
        return this.toString();
    }

    public List getArgs() {
        return this.args;
    }

    public String toString() {
        String _message = testService.getMessage(this.message, this.args);
        return _message
    }

    static {
        if(!testService) {
            ApplicationContext applicationContext = WebUtils.retrieveGrailsWebRequest().getApplicationContext();
            testService = applicationContext.getBean("testService");
        }
    }
}

Friday, February 7, 2014

Get gmt time and gmt diferrence using jQuery


<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function() {
        var rightNow = new Date();
        $("div").append("Local time: " + rightNow + "<br/>");
        var temp = rightNow.toGMTString();
        $("div").append("GMT time: " + temp + "<br/>");
        var visitorTimeZone = "GMT " + -(rightNow.getTimezoneOffset() / 60);
        $("div").append(visitorTimeZone + "<br/>");
    });    
</script>
<div class="div"></div>

Thursday, February 6, 2014

Place auto complete address form using google api and jQuery

Google api link || Live example || Download autocomplete-address-form.js

Example screen shots:
Html Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Place Auto Complete Address Form</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
            html, body, #map-canvas {
                height: 100%;
                margin: 0px;
                padding: 0px
        }
        </style>
        <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="autocomplete-address-form.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                app.autoCompleteAddress.initialize($(this).find("#html-body"));
            });
        </script>

        <style>
            #locationField, #controls {
                position: relative;
                width: 480px;
            }
            #autocomplete {
                position: absolute;
                top: 0px;
                left: 0px;
                width: 99%;
            }
            .label {
                text-align: right;
                font-weight: bold;
                width: 100px;
                color: #303030;
            }
            #address {
                border: 1px solid #000090;
                background-color: #f0f0ff;
                width: 480px;
                padding-right: 2px;
            }
            #address td {
                font-size: 10pt;
            }
            .field {
                width: 99%;
            }
            .slimField {
                width: 80px;
            }
            .wideField {
                width: 200px;
            }
            #locationField {
                height: 20px;
                margin-bottom: 2px;
            }
        </style>
    </head>

    <body style="padding-left: 50px; padding-top: 50px;" id="html-body">
        <div id="locationField">
            <input id="autocomplete" class="auto-complete-address"
                   placeholder="Enter your address" type="text"></input>
        </div>

        <table id="address">
            <tr>
                <td class="label">Street address</td>
                <td class="slimField"><input class="field" id="street_number"/></td>
                <td class="wideField" colspan="2"><input class="field" id="route"/></td>
            </tr>
            <tr>
                <td class="label">City</td>
                <td class="wideField" colspan="3"><input class="field" id="locality"/></td>
            </tr>
            <tr>
                <td class="label">State</td>
                <td class="slimField"><input class="field"/></td>
                <td class="label">Zip code</td>
                <td class="wideField"><input class="field" id="postal_code"/></td>
            </tr>
            <tr>
                <td class="label">Country</td>
                <td class="wideField" colspan="3"><input id="country" class="field"/></td>
            </tr>
            </tr>
                <td class="label">Other Address Type</td>
                <td class="wideField" colspan="3"><div id="otherType" class="field"></div></td>
            </tr>
        </table>
    </body>
</html>

Tuesday, February 4, 2014

Secure pay xml api credit card payment


<?php 
#Test Merchant ID: abc0001
#Test Merchant Password: acb123
#Test URL (no SSL):     http://test.securepay.com.au/xmlapi/payment
#Test URL (SSL):        https://test.securepay.com.au/xmlapi/payment
#Live URL:              https://api.securepay.com.au/xmlapi/payment
$xml = '<?xml version="1.0" encoding="UTF-8"?>
    <SecurePayMessage>
        <MessageInfo>
            <messageID>8af793f9af34bea0cf40f5fb5c630c</messageID>
            <messageTimestamp>20041803161306527000+660</messageTimestamp>
            <timeoutValue>60</timeoutValue>
            <apiVersion>xml-4.2</apiVersion>
        </MessageInfo>
        <MerchantInfo>
            <merchantID>abc0001</merchantID>
            <password>abc123</password>
        </MerchantInfo>
        <RequestType>Payment</RequestType>
        <Payment>
            <TxnList count="1">
                <Txn ID="1">
                    <txnType>0</txnType>
                    <txnSource>0</txnSource>
                    <amount>1000</amount>
                    <currency>AUD</currency>
                    <purchaseOrderNo>test</purchaseOrderNo>
                    <CreditCardInfo>
                        <cardNumber>4444333322221111</cardNumber>
                        <expiryDate>09/15</expiryDate>
                    </CreditCardInfo>
                </Txn>
            </TxnList>
        </Payment>
    </SecurePayMessage>';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://test.securepay.com.au/xmlapi/payment");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // Return the HTTP response from the curl_exec function

$response = curl_exec($curl);
curl_close($curl);

header('Content-type: text/xml');
echo $response;

$responseIsLikeThis = '
<SecurePayMessage>
    <MessageInfo>
        <messageID>8af793f9af34bea0cf40f5fb5c630c</messageID>
        <messageTimestamp>20140402171039522000+660</messageTimestamp>
        <apiVersion>xml-4.2</apiVersion>
    </MessageInfo>
    <RequestType>Payment</RequestType>
    <MerchantInfo>
        <merchantID>ABC0001</merchantID>
    </MerchantInfo>
    <Status>
        <statusCode>000</statusCode>
        <statusDescription>Normal</statusDescription>
    </Status>
    <Payment>
        <TxnList count="1">
            <Txn ID="1">
                <txnType>0</txnType>
                <txnSource>0</txnSource>
                <amount>1000</amount>
                <currency>AUD</currency>
                <purchaseOrderNo>test</purchaseOrderNo>
                <approved>Yes</approved>
                <responseCode>00</responseCode>
                <responseText>Approved</responseText>
                <thinlinkResponseCode>100</thinlinkResponseCode>
                <thinlinkResponseText>000</thinlinkResponseText>
                <thinlinkEventStatusCode>000</thinlinkEventStatusCode>
                <thinlinkEventStatusText>Normal</thinlinkEventStatusText>
                <settlementDate>20140204</settlementDate>
                <txnID>576566</txnID>
                <CreditCardInfo>
                    <pan>444433...111</pan>
                    <expiryDate>09/15</expiryDate>
                    <cardType>6</cardType>
                    <cardDescription>Visa</cardDescription>
                </CreditCardInfo>
            </Txn>
        </TxnList>
    </Payment>
</SecurePayMessage>';
?>

Monday, January 27, 2014

PHP replace char with Unicode value inside string


<?php
$originalString = "Pritom K Mondal, 0154785";
function ord2($s2) {
    return "&#" . ord($s2) . ";";
}
echo preg_replace("/[^a-zA-Z0-9]/e", "ord2('\\0')", $originalString) ?>

And output will be as:

Pritom&#32;K&#32;Mondal&#44;&#32;0154785

Sunday, January 26, 2014

eWay xml and direct payment url, account and credit card details


eWayServiceLinkURL:
 TEST: https://www.eway.com.au/gateway/ManagedPaymentService/test/managedCreditCardPayment.asmx
 LIVE: https://www.eway.com.au/gateway/ManagedPaymentService/managedCreditCardPayment.asmx
 
eWayProcessPaymentURL:
 TEST: https://www.eway.com.au/gateway/managedpayment/ProcessPayment
 LIVE: https://www.eway.com.au/gateway/managedpayment/ProcessPayment
 
eWaySOAPActionURL
 TEST: https://www.eway.com.au/gateway/managedpayment
 LIVE: https://www.eway.com.au/gateway/managedpayment
 
eWayDirectPaymentURL:
 TEST: https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp
 LIVE: https://www.eway.com.au/gateway/xmlpayment.asp
 
eWAYCustomerID:
 TEST: 87654321
 
Username:
 TEST: test@eway.com.au
 
Password:
 TEST: test123
 
Credit Card:
 TEST: 4444333322221111
 
Credit Card CVV:
 TEST: 123 (or any other 3 or 4 digit number)
 
Credit Card Expiry:
 TEST: 01/15 (any valid date)
 
Credit Card Name:
 TEST: test (or any other valid name)

Tuesday, January 14, 2014

Setup Spring framework with Eclipse IDE and create first application


Step 1: Setup Java Development Kit (JDK)

Download the latest version of SDK from Oracle's Java site: Java SE Downloads. Install SDK as instruction from oracle site. After installation completed, set PATH and JAVA_HOME environment variables.
If you are running Windows and installed the JDK in "C:\Program Files\Java\jdk1.6.0_24", you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\Program Files\Java\jdk1.6.0_24\bin;%PATH%
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_24
Alternatively, on Windows XP, right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_24 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.6.0_24/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_24
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.

Step 2: Install Apache Common Logging API

Download the latest version of Apache Commons Logging API from here (version: 1.1.3) or from http://commons.apache.org/logging/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\commons-logging-1.1.3 on windows, or /usr/local/commons-logging-1.1.3 on Linux/Unix. This directory will have following jar files and other supporting documents etc.



Step 3: Setup Eclipse IDE

Download the latest Eclipse from http://www.eclipse.org/downloads/ and unpack the binary distribution into a folder for example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe
 %C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$/usr/local/eclipse/eclipse

Step 4: Setup Spring Framework Libraries

  1. Make a choice whether you want to install Spring on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
  2. Download the latest version of Spring framework binaries from http://repo.spring.io/release/org/springframework/spring/ or version 3.2.0 from here.
  3. Unzip the downloaded file, as for me, the extracted folder is 'D:\me\Apache Loggin Jars\spring-framework-3.2.0.RELEASE\libs'.


Step 5: Create Java Project

The first step is to create a simple Java Project using Eclipse IDE. Follow the option File -> New -> Project and finally select Java Project wizard from the wizard list. Now name your project as 'First Spring' using the wizard window as follows:





Step 6: Add Required Libraries

As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right click on your project name FirstSpring and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows:
Now use Add External JARs button available under Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories



Step 7: Create Source Files

Now let us create actual source files under the FirstSpring project. First we need to create a package called com.pritom.code. To do this, right click on src in package explorer section and follow the option : New -> Package.
Next we will create FirstSpring.java and MainApplication.java files under the 'com.pritom.code'.


Here is the content of FirstSpring.java file:


package com.pritom.code;

public class FirstSpring {
	private String message;

	public void setMessage(String message){
		this.message  = message;
	}

	public void getMessage(){
		System.out.println("I am writting from mainApplication: " + message);
	}
}


Following is the content of the second file MainApplication.java:


package com.pritom.code;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApplication {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

		FirstSpring obj = (FirstSpring) context.getBean("firstSpring");

		obj.getMessage();
		
		obj.setMessage("New Message");
		obj.getMessage();
	}
}



Step 8: Create Bean Configuration File:

You need to create a Bean Configuration file which is an XML file named 'Beans.xml' and acts as cement that glues the beans ie. classes together. This file needs to be created under the src directory as shown below: 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="firstSpring" class="com.pritom.code.FirstSpring">
       <property name="message" value="First Spring!"/>
   </bean>

</beans>


Step 9: Running the Program:

Once you are done with creating source and beans configuration files, you are ready for this step which is compiling and running your program. To do this, Keep MainApplication.Java file tab active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your MainApplication application. If everything is fine with your application, this will print the following message in Eclipse IDE's console:
I am writting from mainApplication: First Spring!
I am writting from mainApplication: New Message 

Congratulations, you have created your first Spring Application successfully. You can see the flexibility of above Spring application by changing the value of "message" property and keeping both the source files unchanged