String cardNumber = "4444 3333 2222 111"); cardNumber = cardNumber.trim(); cardNumber = cardNumber.replaceAll("\\D+", ""); Output: 4444333322221111
Wednesday, November 13, 2013
Java - Replace all non digits with an empty character in a string
Validate credit card and get card type by java code
import org.apache.commons.validator.GenericValidator def getCreditCardType(String cardNumber) throws AutobillException { cardNumber = "" + cardNumber; cardNumber = cardNumber.trim(); cardNumber = cardNumber.replaceAll("\\D+", ""); if(!GenericValidator.isCreditCard(cardNumber)) { throw new InvalidPropertyException("cardNumber"); } if(cardNumber.matches(("^4[0-9]{12}(?:[0-9]{3})?\$"))) { return "VISA"; } else if(cardNumber.matches(("^5[1-5][0-9]{14}\$"))) { return "MASTERCARD"; } else if(cardNumber.matches(("^3[47][0-9]{13}\$"))) { return "AMEX"; } else if(cardNumber.matches(("^3(?:0[0-5]|[68][0-9])[0-9]{11}\$"))) { return "DINERS"; } else if(cardNumber.matches(("^6(?:011|5[0-9]{2})[0-9]{12}\$"))) { return "DISCOVER"; } else if(cardNumber.matches(("^(?:2131|1800|35\\d{3})\\d{11}\$"))) { return "JCB"; } return null; }
Wednesday, November 6, 2013
Merge two hashmap by multiple keys using java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xmlparser; import java.util.HashMap; /** * * @author Pritom K Mondal */ public class HashMapMerge { public static void main(String[] args) { HashMap a = new HashMap(); /** * First row */ HashMap b = new HashMap(); b.put("name", "name-1"); b.put("roll_0", "roll-11"); b.put("roll_1", "roll-12"); HashMap b10 = new HashMap(); b10.put("item_0", 0); b10.put("item_1", 1); b.put("item_0", b10); HashMap c = new HashMap(); c.put("name", "name-2"); c.put("roll", "roll-2"); HashMap d = new HashMap(); d.put("student_0", b); d.put("student_1", c); d.put("student_2", "TATA"); /** * Second row */ HashMap b1 = new HashMap(); b1.put("grade", "grade-1"); HashMap c10 = new HashMap(); c10.put("item_2", 33); c10.put("item_3", 44); b1.put("item_0", c10); HashMap c1 = new HashMap(); c1.put("grade", "grade-2"); HashMap d1 = new HashMap(); d1.put("student_0", b1); d1.put("student_1", c1); d1.put("student_2", b1); System.out.println(d); System.out.println(d1); HashMapMerge hashMapMerge = new HashMapMerge(); a = hashMapMerge.merge(d, d1); System.out.println(a); } public HashMap merge(HashMap a, HashMap b) { HashMap c = new HashMap(); for(Object key : a.keySet()) { String key2 = (String) key; Object dup = a.get(key2); c.put(key2, dup); } for(Object key : b.keySet()) { String key2 = (String) key; Object dup = b.get(key2); if(dup instanceof HashMap && c.containsKey(key2) && c.get(key2) instanceof HashMap) { HashMap kk = (HashMap) c.get(key2); HashMap p = merge(kk, (HashMap) dup); c.put(key2, p); } else if(dup instanceof HashMap && c.containsKey(key2) && !(c.get(key2) instanceof HashMap)) { HashMap kk = new HashMap(); kk.put(key2, c.get(key2)); HashMap p = merge(kk, (HashMap) dup); c.put(key2, p); } else { c.put(key2, dup); } } return c; } }
Input map 1:
{ student_1={ roll=roll-2, name=name-2 }, student_0={ item_0={ item_1=1, item_0=0 }, roll_0=roll-11, roll_1=roll-12, name=name-1 }, student_2=TATA }
Input map 2:
{ student_1={ grade=grade-2 }, student_0={ item_0={ item_3=44, item_2=33 }, grade=grade-1 }, student_2={ item_0={ item_3=44, item_2=33 }, grade=grade-1 } }
And result map after merge:
{ student_1={ roll=roll-2, name=name-2, grade=grade-2 }, student_0={ item_0={ item_1=1, item_0=0, item_3=44, item_2=33 }, roll_0=roll-11, name=name-1, roll_1=roll-12, grade=grade-1 }, student_2={ student_2=TATA, item_0={ item_3=44, item_2=33 }, grade=grade-1 } }
Friday, November 1, 2013
How to send DELETE HTTP request in HttpURLConnection java
In a DELETE request, the parameters are sent as part of the URL and you can not send request body.
This code should get you started:
String urlParameters = "param1=1¶m2=2"; String request = "http://api.server.com"; URL url = new URL(request + "?" + urlParameters); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches (false);
Print out response code and get response from server:
System.out.println("Response code: " + connection.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line, responseText = ""; while ((line = br.readLine()) != null) { System.out.println("LINE: "+line); responseText += line; } br.close(); connection.disconnect();
Wednesday, October 30, 2013
Transactions in Grails to roll back inconsistent data
The
If you think the method you are developing should or could participate in some larger transaction with multiple separate db writes, then you should use
In regards to your question two, these two will behave the same if they are the only calls being made in an action as they would both start up a new transaction.
withTransaction
function will participate in an existing transaction if one already has been started and would start a new one if not. The withNewTransaction
method will always start a new transaction regardless of if one has
already been started, isolating the code inside that block into it's own
transaction (with it's own commit/rollback).If you think the method you are developing should or could participate in some larger transaction with multiple separate db writes, then you should use
withTransaction
so that you can
participate in a larger transaction if necessary. If you want your
write here to be totally isolated from other db writes if another
transaction is going on (and not potentially roll back that other
transaction if this code fails), then use withNewTransaction
.In regards to your question two, these two will behave the same if they are the only calls being made in an action as they would both start up a new transaction.
def saveInstance = { /* Assume 'User' and 'Role' are two difference domain. Where Role is as a belongsTo of User. So need to first save Role and then User. But if Role saved and User not saved for any reason, then what happened??? Role exists in database??? For this we need to roll back data. Everything inside this block is run in a transaction as the name indicates. */ User.withTransaction { status -> try { def role = new Role(rollName: "Role Name").save(flush: true); def user = new User(username: "pritom", name: "Pritom K Mondal", role: role).save(flush: true); } catch (Exception ex) { ex.printStackTrace(); try { /* Rolling back data if any exception happens */ status.setRollbackOnly(); } catch (Exception ex2) { ex2.printStackTrace(); } } } }
Sort an ArrayList base on multiple attributes using java/grails
I have an ArrayList of object. The object contain attributes
name
and classValue
. So I want to sort the objects on the classValue
, and for all objects in the same classValue
I want to sort them on name
.import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; /** * * @author Pritom Kumar */ public class MapSort { public static void main(String[] args) { MapSort mapSort = new MapSort(); mapSort.sort(); } public void sort() { List keys = new ArrayList(); HashMap map1 = new HashMap(); map1.put("name", "Pritom"); map1.put("classValue", 5); keys.add(map1); HashMap map2 = new HashMap(); map2.put("name", "Bappi Lahiri"); map2.put("classValue", 10); keys.add(map2); HashMap map3 = new HashMap(); map3.put("name", "Ashok Kumar"); map3.put("classValue", 5); keys.add(map3); Collections.sort(keys, new Comparator() { public int compare(Object left, Object right) { HashMap leftMap = (HashMap) left; HashMap rightMap = (HashMap) right; Integer classValue1 = Integer.parseInt(leftMap.get("classValue").toString()); Integer classValue2 = Integer.parseInt(rightMap.get("classValue").toString()); int comp = classValue1.compareTo(classValue2); return comp == 0 ? leftMap.get("name").toString().compareTo(rightMap.get("name").toString()) : comp; } }); //List the values Object[] keyList = keys.toArray(); for(Integer index = 0; index < keyList.length; index++) { System.out.println(keyList[index]); } } }
And the output is as following. At first sorts by classValue and then by name.
{name=Ashok Kumar, classValue=5} {name=Pritom, classValue=5} {name=Bappi Lahiri, classValue=10}
Tuesday, October 29, 2013
Grails/GORM createCriteria.list to get specific/selected columns only | Alias To Entity Map ALIAS_TO_ENTITY_MAP | Grails Projections | Projections Data
Grails/GORM createCriteria.list to get specific/selected columns only | Alias To Entity Map ALIAS_TO_ENTITY_MAP | Grails Projections | Projections Data.
Below is a example of get some specific field instead of all fields for domain.
And you can left join another domain that is belongsTo or hasMany of parent domain.
You have to import below reference:
import org.hibernate.criterion.CriteriaSpecification
Below is a example of get some specific field instead of all fields for domain.
And you can left join another domain that is belongsTo or hasMany of parent domain.
You have to import below reference:
import org.hibernate.criterion.CriteriaSpecification
List list = DomainName.createCriteria().list {
resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
"in"("id", [1L, 2L])
createAlias('x', 'x_alias', CriteriaSpecification.LEFT_JOIN)
projections {
property("id", "id")
property("x_alias.field", "field_reference");
}
}
Output would be like below:
[
[id:1, field_reference:value1],
[id:2, field_reference:value2]
]
Subscribe to:
Posts (Atom)