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

Monday, January 13, 2014

Html5 & jQuery form validation and get all error at a time


Html code


<form method='post'>
    <ul class="errorMessages"></ul>
    <div class="one">
        <label for="name">Name:</label>
        <input id="name" type="text" required="required"/>
    </div>
    <div class="two">
        <label for="comments">Comments:</label>
        <textarea id="comments" required="required"></textarea>
    </div>
    <div class="three">
        <label for="roll">Name:</label>
        <input id="roll" type="text" required="required"/>
    </div>
    <div class="four">
        <label for="email">Email:</label>
        <input id="email" type="email" required="required"/>
    </div>
    <div class="five">
        <label>Group:</label>
        <input type='radio' name='group' required="required"/> Group 1
        <input type='radio' name='group' required="required"/> Group 2
        <input type='radio' name='group' required="required"/> Group 3
    </div>
    <div class="buttons">
        <button type="submit" class="submit">Submit</button>
        <button type="button">Check</button>
    </div>
</form>

jQuery code


var createAllErrors = function() {
    var form = $( this ), errorList = $( "ul.errorMessages", form);
    var showAllErrorMessages = function() {
        errorList.empty();
        
        // Find all invalid fields within the form.
        var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
            // Find the field's corresponding label
            var label = $( "label[for=" + node.id + "] ").html();
            if(label === undefined) {
                label = "";
            }
            // Opera incorrectly does not fill the validationMessage property.
            var message = node.validationMessage || 'Invalid value.';
            errorList.append( "<li><span>" + label + "</span> " + message + "</li>" );
        });
        errorList.show();
        return errorList.find("li").size();
    };

    form.find("button[type='button']").click(function() {
        var errorLength = showAllErrorMessages();
        errorList.show().prepend( "<li><span>Total Errors: </span> " + errorLength + "</li>" );
        form.find( "button.submit").click();
    });
    
    // Support Safari
    form.on( "submit", function( event ) {
        if ( this.checkValidity && !this.checkValidity() ) {
            $( this ).find( ":invalid" ).first().focus();
            event.preventDefault();
        }
    });
};
$( "form" ).each( createAllErrors );

Sunday, January 12, 2014

Using php download a temporary file


<?php
$dataArray = array(
    "name" => "Pritom K Mondal",
    "company" => "Some Company"
);
$tmpName = tempnam(sys_get_temp_dir(), 'data');

$tmpFile = fopen($tmpName, 'w');
fputcsv($tmpFile, $dataArray);

header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=download.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpName));

ob_clean();
flush();
readfile($tmpName);
unlink($tmpName);
?>

Saturday, January 11, 2014

Using java copy array using copyOf

byte[] src = {1, 2, 3, 4};
byte[] dst = Arrays.copyOf(src, src.length);
System.out.println(Arrays.toString(dst));

Wednesday, January 8, 2014

Grails, finding available views (.gsp's) at runtime

This is not a important post. I just need to do some googling to achieve this and i found at: http://stackoverflow.com/questions/1577872/grails-finding-available-views-gsps-at-runtime. Thanks Burt Beckwith. I put this here to not search in google again.


import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH

def viewGsp() {
    List gspFileList = []
    if (grailsApplication.isWarDeployed()) {
        findWarGspList ('/WEB-INF/grails-app/views', gspFileList);
    } else {
        findDevGspList ('grails-app/views', gspFileList);
    }
    gspFileList.each {
        render it.toString() + "<br/>";
    }
    render "";
}
private void findDevGspList(String location, List gspFileList) {
    for (file in new File(location).listFiles()) {
        if (file.path.endsWith('.gsp')) {
            gspFileList << file.path - 'grails-app/views/';
        } else {
            findDevGspList (file.path, gspFileList);
        }
    }
}

private void findWarGspList(String location, List gspFileList) {
    def servletContext = SCH.servletContext
    for (path in servletContext.getResourcePaths(location)) {
        if (path.endsWith('.gsp')) {
            gspFileList << path - '/WEB-INF/grails-app/views/';
        } else {
            findWarGspList (path, gspFileList);
        }
    }
}