category:primary is:unread
Sunday, January 15, 2017
Filter unread emails from Primary tab of Gmail
category:primary is:unread
Posted by
Vishnu Agrawal
at
3:50 PM
0
comments
Sunday, August 9, 2015
Java: Compare two JSON strings
Following is the code to parse two json strings and compare them
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJson3{
private static String srcJsonStr = "SRC JSON String here";
private static String destJsonStr = "Dest JSON String here";
public static void main(String[] args){
try{
JSONObject srcJson = new JSONObject(srcJsonStr);
JSONObject destJson = new JSONObject(destJsonStr);
compareJson(srcJson, destJson);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void compareJson(JSONObject srcJson, JSONObject destJson){
StringBuilder diffLog = new StringBuilder();
try{
Map srcJsonMap = new LinkedHashMap();
Map destJsonMap = new LinkedHashMap();
srcJsonMap = parseJson("", srcJson, srcJsonMap);
destJsonMap = parseJson("", destJson, destJsonMap);
//union
Set union = new HashSet(srcJsonMap.keySet());
union.addAll(destJsonMap.keySet());
//h1-h2
Set diff1 = new HashSet(srcJsonMap.keySet());
diff1.removeAll(destJsonMap.keySet());
//h1-h2
Set diff2 = new HashSet(destJsonMap.keySet());
diff2.removeAll(srcJsonMap.keySet());
//intersection
Set intersect = new HashSet(srcJsonMap.keySet());
intersect.retainAll(destJsonMap.keySet());
if(intersect.size() > 0){
for(String key: intersect){
Object srcData = srcJsonMap.get(key);
Object destData = destJsonMap.get(key);
if( ! srcData.toString().equals(destData.toString())){
diffLog.append("KEY :: " + key + "\n");
diffLog.append("SRC DATA :: " + srcData + "\n");
diffLog.append("DEST DATA :: " + destData + "\n");
}
}
}
if(diff1.size() > 0){
diffLog.append("\n");
diffLog.append("###########################");
diffLog.append("Only in SRC JSON");
diffLog.append("###########################");
diffLog.append("\n");
for(String key: diff1){
diffLog.append("KEY :: " + key + "\n");
diffLog.append("DATA :: " + srcJsonMap.get(key) + "\n");
diffLog.append("\n");
}
}
if(diff2.size() > 0){
diffLog.append("\n");
diffLog.append("###########################");
diffLog.append("Only in DEST JSON");
diffLog.append("###########################");
diffLog.append("\n");
for(String key: diff2){
diffLog.append("KEY :: " + key + "\n");
diffLog.append("DATA :: " + destJsonMap.get(key) + "\n");
diffLog.append("\n");
}
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println(diffLog.toString());
}
public static Map parseJson(String key, JSONObject jsonObject, Map map){
try{
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
String obj = iterator.next().toString();
String keyVal = (key.equals("")) ? obj : key + "." + obj;
if(jsonObject.get(obj) instanceof JSONArray){
JSONArray jsonArr = (JSONArray) jsonObject.get(obj);
for(int k=0; k < jsonArr.length; k++){
if(jsonArr.get(k) instanceof JSONObject){
parseJson(keyVal + "[" + k + "]", (JSONObject) jsonArr.get(k), map);
}
else{
map.put(keyVal, jsonArr.get(k));
}
}
}
else{
if(jsonObject.get(obj) instanceof JSONObject){
parseJson(keyVal, (JSONObject) jsonObject.get(obj), map);
}
else{
map.put(keyVal, jsonObject.get(obj));
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
return map;
}
}
Posted by
Vishnu Agrawal
at
3:07 PM
0
comments
Java: Store Json String into a Java Map
Following is the code to parse a json string and store the structure in Map
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJson2{
private static String jsonStr = "JSON String here";
public static void main(String[] args){
try{
JSONObject obj = new JSONObject(jsonStr);
parseJson(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void parseJson(JSONObject jsonObject){
Map map = new LinkedHashMap();
try{
parseJson("", jsonObject, map);
for(String key: map.keySet()){
System.out.println(key + "::" + map.get(key));
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static Map parseJson(String key, JSONObject jsonObject, Map map){
try{
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
String obj = iterator.next().toString();
String keyVal = (key.equals("")) ? obj : key + "." + obj;
if(jsonObject.get(obj) instanceof JSONArray){
JSONArray jsonArr = (JSONArray) jsonObject.get(obj);
for(int k=0; k < jsonArr.length; k++){
if(jsonArr.get(k) instanceof JSONObject){
parseJson(keyVal + "[" + k + "]", (JSONObject) jsonArr.get(k), map);
}
else{
map.put(keyVal, jsonArr.get(k));
}
}
}
else{
if(jsonObject.get(obj) instanceof JSONObject){
parseJson(keyVal, (JSONObject) jsonObject.get(obj), map);
}
else{
map.put(keyVal, jsonObject.get(obj));
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
return map;
}
}
Posted by
Vishnu Agrawal
at
2:45 PM
0
comments
Java: parse a JSON string
Following is the code to parse a json string
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJson1{
private static String jsonStr = "";
public static void main(String[] args){
try{
JSONObject obj = new JSONObject(jsonStr);
parseJson("", obj);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void parseJson(String key, JSONObject jsonObject){
try{
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
String obj = iterator.next().toString();
String keyVal = (key.equals("")) ? obj : key + "." + obj;
if(jsonObject.get(obj) instanceof JSONArray){
JSONArray jsonArr = (JSONArray) jsonObject.get(obj);
for(int k=0; k < jsonArr.length; k++){
if(jsonArr.get(k) instanceof JSONObject){
parseJson(keyVal + "[" + k + "]", (JSONObject) jsonArr.get(k));
}
else{
System.out.println(keyVal + " :: " + jsonArr.get(k));
}
}
}
else{
if(jsonObject.get(obj) instanceof JSONObject){
parseJson(keyVal, (JSONObject) jsonObject.get(obj));
}
else{
System.out.println(keyVal + " :: " + jsonObject.get(obj));
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
Posted by
Vishnu Agrawal
at
2:24 PM
0
comments
Tuesday, September 17, 2013
Wednesday, November 28, 2012
Shell script: format numbers
Shell script to format date in yyyy.mm.dd format
#!/bin/bash
year=2012
for (( c=1; c<=12; c++ ))
do
month=$(printf "%02d" $c)
for (( d=1; d<=15; d++ ))
do
day=$(printf "%02d" $d)
echo $year.$month.$day
done
done
Posted by
Vishnu Agrawal
at
10:57 PM
0
comments
Labels: shell scripting
Java : Send Email
Following is the code to send email using java. Download mail.jar and activation.jar to run the program.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailProcessor {
private String mailHost;
private String from;
private String to;
private String subject;
private String text;
public static void main(String[] args)
{
EmailProcessor emp = new EmailProcessor("mailhost", "from@test.com", "to1@test.com,to2@test.com", "Subject", "Email Text");
emp.send();
}
public EmailProcessor(String mailhost, String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
this.mailHost = mailhost;
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", mailHost);
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress[] toAddress = null;
try {
fromAddress = new InternetAddress(from);
String[] toEmails = to.split(",");
toAddress = new InternetAddress[toEmails.length];
for (int i = 0; i < toEmails.length; i++)
{
toAddress[i] = new InternetAddress(toEmails[i].trim());
}
} catch (AddressException e) {
Utility.logError(e.getMessage());
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipients(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
Utility.logError(e.getMessage());
e.printStackTrace();
}
}
}
Posted by
Vishnu Agrawal
at
10:47 PM
0
comments
Labels: java
Friday, June 8, 2012
Selenium: Testing auto complete fields
public static void inputTextInAutocompleteField(String testField, String testValue)
{
try {
selenium.type(testField, testValue);
selenium.typeKeys(testField," \b") ;
} catch (Exception e) {
e.printStackTrace();
}
}
Posted by
Vishnu Agrawal
at
6:29 PM
0
comments
Labels: selenium
Selenium: How to accept SSL certificates
However, we can resolve this issue by installing CyberVillains Certificate on Windows. We need to follow below steps to work Selenium with SSL.
1. Start selenium server with "-trustAllSSLCertificates" command
2. Use "*firefoxproxy" instead of "firefox" OR "*iexploreproxy" instead of "iexplore"
3. Install CyberVillains Certificate (selenium bundles a special certification authority (CA) certificate that is used to trust all the other SSL certificates.)
Installing CyberVillains Certificate
---------------------------------------
1. Extract selenium jar into a folder
2. Goto sslSupport diretory
3. Double click on cybervillainsCA.cer
Posted by
Vishnu Agrawal
at
5:12 PM
0
comments
Labels: selenium
Tuesday, June 5, 2012
Bash: read csv file
#!/bin/bash
FILENAME=test.csv
OLDSEP=$IFS
IFS=,
[ ! -f $FILENAME ] && { echo "File not found : $FILENAME"; exit 99; }
while read field1 field2 field3 field4
do
echo "$field1 : $field2 : $field3 : $field4"
done < $FILENAME
IFS=$OLDSEP
Posted by
Vishnu Agrawal
at
1:02 PM
3
comments
Labels: linux, shell scripting, solaris
Cannot remove directory: File exists
$chmod -R 777 logs/ $rm -rf logs/ $rm: cannot remove directory 'logs/': File existsChecked the logs folder content and found out that there was .nfs*** file in this, when I manually deleted this file, it was recreated immediately and the timestamp of the file was not current, it was same of which I just deleted.
$ls -lrta total 20K drwxrwxrwx 3 test vishnu 4.0K May 3 03:27 .. -rwxrwxr-x 1 test vishnu 11K May 3 03:27 .nfs29682 drwxrwxr-x 2 test vishnu 4.0K Jun 4 23:17 .To solve this issue, we need to find out which process is using this file and delete that process.
$/usr/sbin/fuser -u logs/.* logs/.: logs/..: logs/.nfs29682: 23142m(test)23142 is the process which is using this directory, we need to kill it.
kill -9 23142now delete the directory, it will be deleted successfully.
$rm -rf logs/ $
Posted by
Vishnu Agrawal
at
12:22 PM
0
comments
Thursday, April 19, 2012
Selenium: Check if Selenium Server is running
If you want to check whether selenium server is running or not, hit the url "http://host:port/selenium-server/driver/?cmd=testComplete", If response is returned that means, server is running on the given host:port. Here is the Java code for this:
import java.net.HttpURLConnection;
import java.net.URL;
public static boolean isSeleniumServerRunning(String host, int port)
{
try {
String baseUrl = "http://" + host + ":" + port;
System.out.println("Checking selenium server status [" + baseUrl + "]");
URL url = new URL(baseUrl + "/selenium-server/driver/?cmd=testComplete");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK)
return true;
} catch (Exception e) {
System.err.println("Could not check selenium server status: " + e.getMessage());
e.printStackTrace();
}
return false;
}
Posted by
Vishnu Agrawal
at
10:21 PM
0
comments
Java: Copy Directory structure
public static void copyFolder(String srcFile, String destFile) throws IOException
{
File src = new File(srcFile);
File dest = new File(destFile);
if(!src.exists())
{
System.out.println("Source folder do not exists [" + srcFile + "]");
return;
}
if(src.isDirectory())
{
//if directory not exists, create it
if(!dest.exists())
{
dest.mkdir();
}
//list all the directory contents
String files[] = src.list();
for (String file : files)
{
//construct the src and dest file structure
String sourceFile = src.getAbsolutePath() + File.separator + file;
String destinationFile = dest.getAbsolutePath() + File.separator + file;
//recursive copy
copyFolder(sourceFile, destinationFile); }
}
else
{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
Posted by
Vishnu Agrawal
at
10:15 PM
0
comments
Labels: java
Java: Comparing Arrays
public static boolean compareArrays(String[] actual, String[] expected)
{
if(actual == null || expected == null)
return false;
Arrays.sort(actual);
Arrays.sort(expected);
if(Arrays.equals(actual, expected))
return true;
else
return false;
}
Posted by
Vishnu Agrawal
at
10:09 PM
0
comments
Labels: java
Sunday, April 15, 2012
GNU Screen: Useful tips
1. Give access to other users on the screen:
- Let say screen "test" is running on host 15.25.125.148 with user "xyz"
- run command "Ctrl a :"
- type "multiuser on" to enable multiuser mode
- type "acladd <unix username>" (to whom you want to give access)
- type "aclchg <args>" to change permissions on the screen for that user
- Now the user will login on that host via command "ssh user@15.25.125.148"
- attach to screen with command "screen -x xyz/test"
2. Changing session name of the running screen
The default session name created by the screen command is constructed from the tty and host names, which isn't very intuitive. To change this session name, run this command on your screen session
Ctrl a :sessionname newSessionName3. Send a command to a window in a running screen session from the commandline
screen -x <screen session name> -p <window number or name> -X stuff '<command>\012'4. Create screen session with commands running
- First, create .screenrc_test with following contents where you specify your tabbed sessions and commands
startup_message off
vbell off
caption always "%{= bb}%{+b w}%n %h %=%t %c"
hardstatus alwayslastline "%-Lw%{= BW}%50>%n%f* %t%{-}%+Lw%<"
activity "Activity in %t(%n)"
deflogin on
shell -/bin/bash
screen -t TAB1
stuff "cd $HOME && ls -1rt | tail -1 | xargs tail -f \012"
screen -t TAB2
stuff "cd $HOME && top \012"
- Run screen -S test -c .screenrc_test 5. Starting screen and detach automatically
screen -S test -dm -c .screenrc_test
Posted by
Vishnu Agrawal
at
11:07 AM
0
comments
Labels: gnu screen, screen
Javascript: expand/collapse functionality in a web page
Here is the script to implement expand/collapse functionality in a web page.
Javascript:
function toggle(showHideDiv, switchImgTag)
{
var elem = document.getElementById(showHideDiv);
var imageElem = document.getElementById(switchImgTag);
if(elem.style.display == "block") {
elem.style.display = "none";
imageElem.innerHTML = '
';
}
else {
elem.style.display = "block";
imageElem.innerHTML = '
';
}
}
function Collapse(showHideDiv, switchImgTag)
{
var elem = document.getElementById(showHideDiv);
var imageElem = document.getElementById(switchImgTag);
elem.style.display = "none";
imageElem.innerHTML = '
';
}
function Expand(showHideDiv, switchImgTag)
{
var elem = document.getElementById(showHideDiv);
var imageElem = document.getElementById(switchImgTag);
elem.style.display = "block";
imageElem.innerHTML = '
';
}
function ExpandAll()
{
var elements = document.getElementsByTagName("a");
for (var i = 0; i < elements.length; i++)
{
var myname = elements[i].getAttribute("id");
if(myname != null)
{
if(myname.substr(0, 4) == "img-")
{
var linkid = myname.substr(4);
Expand("div-"+ linkid, "img-"+linkid);
}
}
}
document.getElementById('expand-all').style.display='none';
document.getElementById('collapse-all').style.display='block';
}
function CollapseAll()
{
var elements = document.getElementsByTagName("a");
for (var i = 0; i < elements.length; i++)
{
var myname = elements[i].getAttribute("id");
if(myname != null)
{
if(myname.substr(0, 4) == "img-")
{
var linkid = myname.substr(4);
Collapse("div-"+ linkid, "img-"+linkid);
}
}
}
document.getElementById('expand-all').style.display='block';
document.getElementById('collapse-all').style.display='none';
}
Web Page:
Expand Collapse Test
Test1
|
||||||||||||||||||||||||||||||
Test2
|
|||||||||||||||||||||||||||||||||||||
Stylesheet:
body, table {
font-family: Verdana, Arial, sans-serif;
font-size: 12;
}
table {
border-collapse: collapse;
border: 1px solid #ccc;
}
th, td {
padding-left: 0.3em;
padding-right: 0.3em;
}
a {
text-decoration: none;
}
.title {
font-style: italic;
}
.selected {
background-color: #ffffcc;
}
.status_done {
background-color: #eeffee;
}
.status_passed {
background-color: #00FF00;
}
.status_failed {
background-color: #FF0000;
}
.status_notrun {
background-color: #FFFF00;
}
.status_header {
background-color: #FFA500;
}
.status_duration {
background-color: #00FFFF;
}
.breakpoint {
background-color: #cccccc;
border: 1px solid black;
}
Posted by
Vishnu Agrawal
at
10:03 AM
0
comments
Labels: javascript, web
Tuesday, February 28, 2012
Selenium: simulating click on GWT buttons
In web applications, buttons which are rendered by GWT (google-web-toolkit) cannot be clicked. Selenium RC doesn't recognize them as HTML button. so following will not work for those type of buttons/element
selenium.click(elementLocator)After some googling, I found out that we can click on these elements by native key events with follwoing code.
public static void clickOnGWTPopElement(String elementLocator) {
try{
//normal click doesn't work on GWT popup elements so we need to perform native mouse operations
selenium.mouseOver(elementLocator);
selenium.mouseDown(elementLocator);
selenium.mouseUp(elementLocator);
}catch (Exception e) {
e.printStackTrace();
}
}
Posted by
Vishnu Agrawal
at
10:16 AM
0
comments
Sunday, January 8, 2012
Write data into Excel file using Apache POI
package com.qa.test;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class SpreadSheetWriter {
/** This method writes data to new excel file **/
public static void writeDataToExcelFile(List> data, String fileName)
{
try{
HSSFWorkbook myWorkBook = new HSSFWorkbook();
HSSFSheet mySheet = myWorkBook.createSheet();
HSSFRow myRow = null;
HSSFCell myCell = null;
//Create header row
createHeaderRow(mySheet);
int rowNum = 1;
Iterator> iter = data.iterator();
while(iter.hasNext())
{
myRow = mySheet.createRow(rowNum++);
int cellNum = 0;
List key = iter.next();
for(String values: key)
{
myCell = myRow.createCell(cellNum++);
myCell.setCellValue(values);
}
}
FileOutputStream out = new FileOutputStream(fileName);
myWorkBook.write(out);
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Posted by
Vishnu Agrawal
at
9:06 PM
0
comments
Labels: java
Read Excel file using apache POI library
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcel {
public static void main(String[] args){
try{
InputStream myxls = new FileInputStream("C:\\exceltest.xls");
HSSFWorkbook wb = new HSSFWorkbook(myxls);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
System.out.println("Total Rows :: " + sheet.getLastRowNum());
//Iterate over each row
while (rows.hasNext())
{
HSSFRow row = (HSSFRow) rows.next();
if(checkIfRowEmpty(row))
continue;
int minColIndex = row.getFirstCellNum();
int maxColIndex = row.getLastCellNum();
for(int colIndex = minColIndex; colIndex <= maxColIndex; colIndex++)
{
HSSFCell cell = row.getCell(colIndex);
// POI can't recognize empty cells of Excel, so we should create new cells with a blank value
if(cell == null)
{
cell = row.createCell(colIndex);
cell.setCellValue(" ");
}
String value = "";
switch(cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
value = Double.toString(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = Boolean.toString(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_FORMULA:
value = "";
break;
default:
value = cell.getStringCellValue();
break;
}
System.out.print(value + "|");
}
System.out.println();
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static boolean checkIfRowEmpty(HSSFRow row)
{
int minColumIndex = row.getFirstCellNum();
int maxColumnIndex = row.getLastCellNum();
boolean isRowEmpty = true;
for(int columIndex = minColumIndex; columIndex <= maxColumnIndex; columIndex++)
{
HSSFCell cell = row.getCell(columIndex);
if(cell == null || cell.toString().trim().isEmpty() || cell.toString().length() == 0){
}
else{
isRowEmpty = false;
return isRowEmpty;
}
}
return isRowEmpty;
}
}
Posted by
Vishnu Agrawal
at
6:33 PM
0
comments
Labels: java
Wednesday, December 14, 2011
Running multiple version of firefox
1. Close your all running instances of firefox
2. Download older versions of firefox from http://www.oldversion.com/Mozilla-Firefox.html and do a custom install, install them on a specific version directory. For example I installed them as below:
C:\Program Files\Mozilla Firefox_6.0.2
C:\Program Files\Mozilla Firefox_7.0.1
3. Create profiles for every version by following steps:
A. Goto Run command (or press WINDOWS+R)
B. C:\Program Files\Mozilla Firefox_6.0.2 -P
C. It will open a profile window, Create a profile name with 'Firefox6.0.2'
4. Repeat step 3 for all firefox versions, create unique profile for each version
5. To run a specific version of firefox use below command:
<path to firefox executable> -no-remote -P <profile name>
C:\Program Files\Mozilla Firefox_6.0.2\firefox.exe -no-remote -P Firefox6.0.2
C:\Program Files\Mozilla Firefox_7.0.1\firefox.exe -no-remote -P Firefox7.0.1
Posted by
Vishnu Agrawal
at
5:51 PM
0
comments
Labels: firefox










