Saturday, April 5, 2014

Connecting to Wordpress Database and manipulating post content using PHP

The sample code below covers the following:
1. Connecting to database using PHP.
2. File uploading and reading in PHP.
3. Parsing and splitting operations on Strings in PHP.
Sample Code


<?php
function replaceTitleWithHyperlink($content, $hospGuid, $title)
{
$parts = explode(" ", $content);
$arrlength = count($parts);

$inFound = False;
$asFound = False;
$hospitalName = "";

$indexOfFirstIn = 0;
$indexOfRequiredAs = 0;

for($i=0;$i<$arrlength;$i++)
{
if(strcmp($parts[$i],"in") == 0)
{
$inFound = True;
$indexOfFirstIn = $i;
}
else if($inFound == True and strcmp($parts[$i],"as") == 0)
{
$asFound = True;
$indexOfRequiredAs = $i;
}
else if($asFound == False and $inFound == True)
{
$hospitalName = $hospitalName . " " . $parts[$i];
}
else if($asFound == True and $inFound == True)
{
break;
}
}

$indexOfMatch=1;
$numberOfMatches = 0;

for($i=1;$i<count($hospGuid);$i++)
{
if(strcasecmp(trim($title[$i]), trim($hospitalName)) == 0)
{
$indexOfMatch = $i;
$numberOfMatches++;
}
}
echo "<br>numberOfMatches: " . $numberOfMatches . "<br>";

$finalDocPost = "";

if($numberOfMatches > 1)
{
return $finalDocPost;
}

$parts[$indexOfRequiredAs - 1] = "<a href=\"" . $hospGuid[$indexOfMatch] . "\">" . $hospitalName . "</a>";

for($i=0;$i<$arrlength;$i++)
{
if($i>$indexOfFirstIn and $i<$indexOfRequiredAs-1)
{
}
else
{
$finalDocPost .= " " . $parts[$i];
}
}

echo "<br> Final Doctor Post: " . $finalDocPost . "<br>";
return $finalDocPost;
}

//Fetch values from the form.
$db_url = $_POST["db_url"];
$db_user = $_POST["db_user"];
$db_password = $_POST["db_password"];
$db_name = $_POST["db_name"];
$file_name = $_POST["file"];
$csv_indices = $_POST["indices"];
$update_pref = $_POST["update_pref"];

// Create connection
$con=mysqli_connect($db_url,$db_user,$db_password,$db_name);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error() . "<br>";
}
else
{
echo "Successfully connected to the database<br>";
}

//Array of unique-ids.
$indices = array("dummy");

if(strlen($csv_indices) > 0)
{
$parts = explode(",", $csv_indices);
for($i=0; $i< count($parts); $i++)
{
array_push($indices, trim($parts[$i]));
}
array_push($indices, "");
}

else
{
echo $_FILES["file"]["name"] . "<br>";
$allowedExtensions = array("txt");
$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

if(in_array($extension, $allowedExtensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "Error: " . $_FILES["file"]["error"] . "</p><br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$file = fopen($_FILES["file"]["tmp_name"], "r") or exit("<br>Unable to open file!");
echo "<br>";
while(!feof($file))
{
$line = fgets($file);
echo $line. "<br>";
array_push($indices, trim($line));
}
fclose($file);
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>File type not supported</p><br>";
}
}

$arrlength = count($indices);
$hospGuid = "";

for($i=1;$i<$arrlength-1;$i++)
{
echo "<br>";
echo "The value in indices is: " . $indices[$i] . " is the value";
}
echo "<br>";
echo "<br>";

for($i=1;$i<$arrlength-1;$i++)
{
$docSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_content from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Doctors'))";

$hospSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_title from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Hospitals'))";

echo "<strong>Hospitals query: " . $hospSelect . "</strong>";

$hospSet = mysqli_query($con,$hospSelect);

echo "<table border='1'>
<tr>
<th>Hospital Post ID</th>
<th>GUID</th>
</tr>";

$hospTitle = array("");
$hospGuid = array("");
$numOfHospitals = 1;

while($row = mysqli_fetch_array($hospSet))
{
array_push($hospGuid, $row['guid']);
array_push($hospTitle, $row['post_title']);
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $hospGuid[$numOfHospitals] . "</td>";
echo "</tr>";
$numOfHospitals++;
}
echo "</table>";
echo "<br>";

echo "<strong>Doctors query: " . $docSelect . "</strong>";
$docSet = mysqli_query($con,$docSelect);

$numOfDoctors = 0;

echo "<table border='1'>
<tr>
<th>Doctor Post ID</th>
<th>GUID</th>
<th>Content</th>
</tr>";

while($row = mysqli_fetch_array($docSet) and $numOfDoctors < 1)
{
$post_content = $row['post_content'];
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['guid'] . "</td>";
echo "<td>" . $post_content . "</td>";
echo "</tr>";
$numOfDoctors++;

$finalDocPost = replaceTitleWithHyperlink($post_content, $hospGuid, $hospTitle);

if(strlen($finalDocPost) > 0)
{
$docUpdate = "update wp_posts set post_content = '" . $finalDocPost . "' where ID = " . $row['ID'];

echo "<br><br> The update statement is: " . $docUpdate;

if($update_pref == "Yes")
{
mysqli_query($con,$docUpdate);
}
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>There was ambiguity found while matching hospitals.</p><br>";
}
}
echo "<br><br>Number of doctors found: " . $numOfDoctors . "<br>";

echo "</table>";
echo "<br>";
echo "<br>";
}
mysqli_close($con);
?>

Using TableLayout and dynamically populating views in Android

Useful links are follow: http://forum.codecall.net/topic/70354-tablelayout-programatically/

Sample Code:

public void drawScreen(ArrayList<Product> products) {
tl.removeAllViews();
sv.removeAllViews();

TableRow.LayoutParams params = new TableRow.LayoutParams();
params.gravity = Gravity.CENTER_VERTICAL;

for(int i=0;i<products.size();i++) {
TableRow tr = new TableRow(this);
//View v = (RelativeLayout)findViewById(R.layout.product_row);
TextView tv = new TextView(this);
ImageView iv = new ImageView(this);
CheckBox cb = new CheckBox(this);
cb.setOnClickListener(this);
checkboxes.add(cb);
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
cb.setLayoutParams(params);
//cb.setOnCheckedChangeListener(this);
tv.setText(products.get(i).getAsin());
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setWidth(200);
tr.addView(iv);
tr.addView(tv);
tr.addView(cb);
tr.setGravity(Gravity.CENTER);
tr.setBackground(getResources().getDrawable(R.drawable.rectangle));
tl.addView(tr);
}
TableRow tr = new TableRow(this);
tr.setGravity(Gravity.CENTER);
compareButton = new Button(this);
compareButton.setText("Compare");
compareButton.setOnClickListener(this);
tr.addView(compareButton);
tl.addView(tr);
sv.addView(tl);
setContentView(sv);
}

Communicating non-primitive data objects between Android Activities

Non-primitive types such as ArrayLists can be communicated between Activities in Android using Parcelable interface.
Sample Example:
Class Definition:


package com.example.comparisonapp;

import android.os.Parcel;
import android.os.Parcelable;

public class Product implements Parcelable{
private String asin;
private String imageUrl;
private String description;
private String title;
private Double rating = 0.0;

public String getAsin() {
return asin;
}
public void setAsin(String asin) {
this.asin = asin;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}

public Product() {;}

public Product(Parcel in) {
this.asin = in.readString();
this.imageUrl = in.readString();
this.description = in.readString();
this.title = in.readString();
this.rating = in.readDouble();
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
arg0.writeString(asin);
arg0.writeString(imageUrl);
arg0.writeString(description);
arg0.writeString(title);
arg0.writeDouble(rating);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Product createFromParcel(Parcel in) {
return new Product(in);
}
public Product[] newArray(int size) {
return new Product[size];
}
};
}


Caution:
1. The order of reading data from the Parcel in Parcel argument constructor must be the same as order of writing the data in the Parcel in the writeToParcel method.

Initializing the objects of the class and sending as intent.

products = new ArrayList<Product>();
for(int i=0;i<3;i++) {
Product product = new Product();
product.setAsin("asin " + i);
product.setTitle("Title " + i);
product.setDescription("description " + i);
product.setRating(4.5);
product.setImageUrl("imageUrl");
products.add(product);
}
intent.putExtra("products", products);
startActivity(intent);


Reading the data from the intent

Intent intent = getIntent();
ArrayList<Product> products = intent.getExtras().getParcelableArrayList("products");
for(int i=0;i<products.size();i++) {
Toast.makeText(getApplicationContext(), "Got: " + String.valueOf(products.get(i).getAsin()), Toast.LENGTH_SHORT).show();
}

Thursday, March 27, 2014

Interview Questions and their approach

1. Find if there is a loop in a single linked-list and if yes, remove it.
Approach-1: Take a slow and fast pointer and see if they ever meet.
Time Complexity: O(n)
Space Complexity: O(1)

Approach-2: Go on storing all the addresses and if a stored address is met.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-3: Reverse the linked-list. And then again reverse the linked-list.
Time Complexity: O(n)
Space Complexity: O(1)

2. Given an array of integers, find the pair of integers that add up to a given number.
Approach-1: Store the integers in a hash-table and see if the difference is present in the hash-table.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-2: Find all the possible pairs in the array.
Time Complexity: O(n-square)
Space Complexity: O(1)

Approach-3:
a) Sort all the numbers (Time: nlogn Space: O(1)).
b) At each element, search for the difference using binary search in the same array (Time: nlogn Space: O(1))
Total time-complexity: O(nlogn)

3. Given a single linked-list, find out if it is a palindrome or not.
Approach-1: Push half the nodes in a stack and traverse the rest of the linked-list, while popping the elements from the stack. At any point, if there is a mismatch, then it is not a palindrome.
Time Complexity: O(n)
Space Complexity: O(n)

Approach-2: Reach the mid element of the linked-list. And reverse the rest of the linked-list. Then traverse both the linked lists in parallel. At any point, if there is a mismatch, then it is not a palindrome.
Time Complexity: O(n)
Space Complexity: O(1)

4. Given a string S and a number n, rotate the string the given number of times.
Example input: S: abcdef, n: 2
Example output: efabcd

Approach-1: Start a loop at twice the given number from the end of the string. Swap the next n characters with the nth character from current position. Repeat this till the starting point reaches the beginning of the string.
Time Complexity: O(n)
Space Complexity: O(1)

Approach-2: Reverse the entire string. Then reverse the characters between 0 to n. And then reverse the characters between n+1 to length of string.
Time Complexity: O(n)
Space Complexity: O(1)  
  

Saturday, February 15, 2014

Uploading data from a file to WordPress blog using Selenium and Java-2

Doctors

package com.nueve.review.hreview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.w3c.dom.Element;

public class PostWriter {
private static WebDriver driver;
private static String baseUrl;
private static boolean acceptNextAlert = true;
private static StringBuffer verificationErrors = new StringBuffer();
private static LinkedHashMap<String,String> columnsMap = new LinkedHashMap<String,String>();
private static Boolean upload = true;//Variable that controls the uploading part of code.
private static String[] membershipArray = {"Membership1", "Membership2", "Membership3", "Membership4"};
private static String[] experienceArray = {"Experience 1", "Experience 2", "Experience 3", "Experience 4"};

public static void main(String[] args) {
//Template creation.
columnsMap.put("Unique ID", "");
columnsMap.put("First Name", "Dr. <first name>");
columnsMap.put("Middle Name", " <middle name>");
columnsMap.put("Last Name", " <last name>");
columnsMap.put("Main area of Expertise", " works as a <main area of expertise>");
columnsMap.put("Name of Hospital 1", " in <name of hospital>");
columnsMap.put("H1 Employment Type", " as <H1 Employement type>.");
columnsMap.put("H1 Fee (Rs.)", "\nConsultation Fee: Rs. <fee>");
columnsMap.put("Other areas of expertise", "\nIs also specialized in <other areas of expertise>\n");
columnsMap.put("Graduation Degree", "\nGraduation: <graduation degree>");
columnsMap.put("Graduation College", " <graduation college>");
columnsMap.put("Post Graduation Degree", "\nPost graduation: <post graduation degree>");
columnsMap.put("Post Graduation Area", "-<Post Graduation Area>");
columnsMap.put("Post Graduation College", " <Post Graduation College>");
columnsMap.put("Specialization Degree", "\nSpecialization: <Specialization degree>");
columnsMap.put("Specialization Area", " <specialization college>");
columnsMap.put("Specialization College", "-<Specialization Area>");
columnsMap.put("Super Specialization Degree", "\nSuper Specialization: <Super Specialization degree>");
columnsMap.put("Super Specialization Area", "-<super specialization area>");
columnsMap.put("Super Specialization College", " <Super Specialization College>");
String priorExperienceString = "\n\n<strong>Prior Experience:</strong>\n";
columnsMap.put("Total Experience","<total experience>\n");
for(int i = 0; i < experienceArray.length; i++) {
String key = experienceArray[i];
String value = "<" + experienceArray[i] + ">\n";
columnsMap.put(key, value);
}
String awardsString = "\n\n<strong>Awards and Membership:</strong>\n";
columnsMap.put("Awards and Recognitions", "<Awards and Recognitions>");
for(int i = 0; i < membershipArray.length; i++) {
String key = membershipArray[i];
String value = "<" + membershipArray[i] + ">\n";
columnsMap.put(key, value);
}
String otherHospitalsString = "\n\n<strong>Other Hospitals where doctor is available:</strong>\n";
columnsMap.put("Name of Hospital 2", " <Name of Hospital 2>");
columnsMap.put("H2 Employment Type", " as <H2 Employment Type>");
columnsMap.put("H2 Fee (Rs.)", "\nConsultation fee: Rs. <h2 fee>.\n");
columnsMap.put("Name of Hospital 3", " <Name of Hospital 3>");
columnsMap.put("H3 Employment Type", " as <H3 Employment Type>");
columnsMap.put("H3 Fee (Rs.)", "\nConsultation fee: Rs. <h3 fee>.\n");

String[] column = new String[10];
String csvFileName = "/Users/dsourabh/Downloads/Sample Data 26Jan14.csv";
//String csvFileName = "/Users/dsourabh/Documents/SampleDoctor.csv";
try {
BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName));
StringTokenizer stringTokenizer = null;
String curLine = csvReader.readLine();
int fieldCount = 0;
String[] csvFields = null;
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}
if(upload) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://nueve.co.in/doctors/");
//Logging in and opening the Admin page.
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("username");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("password");
driver.findElement(By.id("wp-submit")).click();
}
int cnt = 1;
while((curLine = csvReader.readLine()) != null)
{
System.out.println("Doctor: "+cnt);
cnt++;
StringBuilder titleString = new StringBuilder();
StringBuilder sb = new StringBuilder();
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
LinkedHashMap<String, String> valuesMap = new LinkedHashMap<String, String>();
//System.out.println("fieldCount = "+fieldCount);
if(fieldCount > 0)
{
int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
//System.out.println(curValue);
valuesMap.put(csvFields[i], curValue);
}
catch(Exception exp)
{
//System.out.println(csvFields[i]);
exp.printStackTrace();
}
i++;
}
if(valuesMap.get("First Name") != null && !valuesMap.get("First Name").equals("blank")) {
titleString.append("Dr. ");
titleString.append(valuesMap.get("First Name"));
}
if(valuesMap.get("Middle Name") != null && !valuesMap.get("Middle Name").equals("blank")) {
titleString.append(" ");
if(valuesMap.get("First Name").equals("blank")) {
titleString.append("Dr. ");
}
titleString.append(valuesMap.get("Middle Name"));
}
if(valuesMap.get("Last Name") != null && !valuesMap.get("Last Name").equals("blank")) {
titleString.append(" ");
if(valuesMap.get("First Name").equals("blank") && valuesMap.get("Middle Name").equals("blank")) {
titleString.append("Dr. ");
}
titleString.append(valuesMap.get("Last Name"));
}

Set<String> keySet = valuesMap.keySet();
Iterator<String> keySetIterator = keySet.iterator();

while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
try {
if(!valuesMap.get(key).equals("blank")) {
String templateValue = columnsMap.get(key);
String actualValue = templateValue.replaceAll("<(.*)>", valuesMap.get(key));
sb.append(actualValue);
}
if(key.equals("Super Specialization College")) {
Boolean toAppend = false;
for(int j = 0; j < experienceArray.length; j++) {
if(!valuesMap.get(experienceArray[j]).equals("blank")) {
toAppend = true;
}
}
if(!valuesMap.get("Total Experience").equals("blank")) {
toAppend = true;
}
if(toAppend) {
sb.append(priorExperienceString);
}
}
else if(key.equals(experienceArray[experienceArray.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < membershipArray.length; j++) {
if(!valuesMap.get(membershipArray[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(awardsString);
}
}
else if(key.equals(membershipArray[membershipArray.length - 1])) {
if(valuesMap.get("Name of Hospital 2") != null && !valuesMap.get("Name of Hospital 2").equals("blank")) {
sb.append(otherHospitalsString);
}
}
} catch (NullPointerException e){
System.out.println(key);
e.printStackTrace();
}
}
System.out.println(sb);
}
if(upload) {
baseUrl = "http://nueve.co.in/doctors/wp-admin/post-new.php";
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);

//baseUrl = "http://nueve.co.in/doctors/wp-admin/";
//Adding a new post with the required parameters.
//driver.get(baseUrl + "/doctors/wp-admin/");
driver.findElement(By.id("title-prompt-text")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys(titleString);
//driver.findElement(By.id("content_ifr")).clear();

driver.findElement(By.id("content-html")).click();
driver.findElement(By.id("content")).clear();
driver.findElement(By.id("content")).sendKeys(sb);

/*
driver.findElement(By.id("acf-field-speciality")).clear();
driver.findElement(By.id("acf-field-speciality")).sendKeys("Speciality");
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
driver.findElement(By.id("acf-since")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
driver.findElement(By.id("acf-field-phone")).click();
driver.findElement(By.id("acf-field-phone")).clear();
driver.findElement(By.id("acf-field-phone")).sendKeys("99999999999");
driver.findElement(By.id("acf-field-address")).clear();
driver.findElement(By.id("acf-field-address")).sendKeys("Address");
*/
if (valuesMap.get("Main area of Expertise") != null && !valuesMap.get("Main area of Expertise").equals("blank")) {
driver.findElement(By.id("new-tag-post_tag")).clear();
driver.findElement(By.id("new-tag-post_tag")).sendKeys(valuesMap.get("Main area of Expertise"));
driver.findElement(By.cssSelector("input.button.tagadd")).click();
}

driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.linkText("Main")).click();
new Select(driver.findElement(By.id("ta_post_review_rating"))).selectByVisibleText("4");
driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.name("ta_post_repeatable[0][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][title]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][desc]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[1][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][title]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][desc]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[2][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][title]")).sendKeys("Waiting Time");
driver.findElement(By.name("ta_post_repeatable[2][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][desc]")).sendKeys("Waiting Time");
driver.findElement(By.name("ta_post_repeatable[2][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[3][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][title]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][desc]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][rating]")).sendKeys("0");

driver.findElement(By.id("in-category-105")).click();

synchronized (driver) {
try {
driver.wait(4000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

if(valuesMap.get("Unique ID") != null && !valuesMap.get("Unique ID").equals("blank")) {
driver.findElement(By.id("acf-field-index")).click();
driver.findElement(By.id("acf-field-index")).clear();
driver.findElement(By.id("acf-field-index")).sendKeys(valuesMap.get("Unique ID"));
}
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
if(valuesMap.get("First Name") != null && !valuesMap.get("First Name").equals("blank")) {
driver.findElement(By.id("acf-field-first_name")).click();
driver.findElement(By.id("acf-field-first_name")).clear();
driver.findElement(By.id("acf-field-first_name")).sendKeys(valuesMap.get("First Name"));
}
//driver.findElement(By.id("acf-since")).clear();
//driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
if(valuesMap.get("Middle Name") != null && !valuesMap.get("Middle Name").equals("blank")) {
driver.findElement(By.id("acf-field-middle_name")).click();
driver.findElement(By.id("acf-field-middle_name")).clear();
driver.findElement(By.id("acf-field-middle_name")).sendKeys(valuesMap.get("Middle Name"));
}
if(valuesMap.get("Last Name") != null && !valuesMap.get("Last Name").equals("blank")) {
driver.findElement(By.id("acf-field-last_name")).click();
driver.findElement(By.id("acf-field-last_name")).clear();
driver.findElement(By.id("acf-field-last_name")).sendKeys(valuesMap.get("Last Name"));
}

synchronized (driver) {
try {
driver.wait(6000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
driver.findElement(By.id("publish")).click();
}
sb = null;
titleString = null;
}
if(upload) {
driver.close();
}
csvReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchElementException nse) {
nse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Uploading data from a file to Wordpress blog using Selenium and Java-1

Hospitals

package com.nueve.review.hreview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class HospitalPostWriter {
private static WebDriver driver;
private static String baseUrl;
private static boolean acceptNextAlert = true;
private static StringBuffer verificationErrors = new StringBuffer();
private static LinkedHashMap<String,String> columnsMap = new LinkedHashMap<String,String>();
private static Boolean upload = true;//Variable that controls the uploading part of code.
private static String[] contactNumbers = {"Alternate Contact Number 1","Alternate Contact Number 2"};
private static String[] membershipArray = {"Awards & Recognition", "Membership2", "Membership3"};
private static String[] emailIds = {"Email Id", "Alternate Email Id"};
private static String[] extensionNumbers = {"Extension Number 1", "Extension Number 2"};

private static String opps_map = "[oppso-map";
private static String map_id = " map_id=\"123\"";
private static String map_type = " map_type=\"ROADMAP\"";
private static String bubble = " bubble=\"\"";
private static String height = " height=\"350px\"";
private static String width = " width=\"400px\"";
private static String zoom = " zoom=\"14\"";
private static String lat = " lat=\"\"";
private static String lon = " lon=\"\"]";

//[oppso-map map_id="123" map_type="ROADMAP" bubble="" height="350px" width="400px" zoom="14" lat="12.95223" lon="77.52879"]

public static void main(String[] args) {
//Template creation.
columnsMap.put("Unique ID", "");
columnsMap.put("Hospital Name", "");
columnsMap.put("Full Address", " is located at ");
columnsMap.put("City", " ");
columnsMap.put("State", ", ");
columnsMap.put("Pincode", ", ");
columnsMap.put("Nearest Landmark", "\nNearest Landmark: ");
columnsMap.put("Locality", " in ");
columnsMap.put("Primary Contact Number", "\nFor booking appointments, please call ");

String alternateContactsString = "\n\nAlternative Contact Numbers\n";
for(int i = 0; i < contactNumbers.length; i++) {
String key = contactNumbers[i];
String value = "<" + contactNumbers[i] + ">\n";
columnsMap.put(key, value);
}

String emailString = "\nEmail ID: \n";
for(int i = 0; i < emailIds.length; i++) {
String key = emailIds[i];
String value = "<" + emailIds[i] + ">\n";
columnsMap.put(key, value);
}

String extensionString = "\n\nExtension Numbers: ";
for(int i = 0; i < extensionNumbers.length; i++) {
String key = extensionNumbers[i];
String value = "<" + extensionNumbers[i] + ">\n";
columnsMap.put(key, value);
}
columnsMap.put("Fax Number", "\nFax Number: ");
columnsMap.put("Hospital Website", "\nWebsite: ");

String aboutHospitalString = "\n\nAbout the hospital\n";

columnsMap.put("Hospital Description", "\n\n");
columnsMap.put("Hospital Speciality", "\n");

String awardsString = "\n\nAwards and Membership:\n";
for(int i = 0; i < membershipArray.length; i++) {
String key = membershipArray[i];
String value = "<" + membershipArray[i] + ">\n";
columnsMap.put(key, value);
}
columnsMap.put("Latitude", "\nLatitude: ");
columnsMap.put("Longitude", "\nLongitude: ");

String csvFileName = "/Users/dsourabh/Downloads/HospitalTrial.csv";
//String csvFileName = "/Users/dsourabh/Documents/SampleDoctor.csv";
try {
BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName));
StringTokenizer stringTokenizer = null;
String curLine = csvReader.readLine();
int fieldCount = 0;
String[] csvFields = null;
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}
if(upload) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://nueve.co.in/doctors/");
//Logging in and opening the Admin page.
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("username");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("passsword");
driver.findElement(By.id("wp-submit")).click();
}
int cnt = 1;
while((curLine = csvReader.readLine()) != null)
{
System.out.println("Hospital: "+cnt);
cnt++;
StringBuilder mapString = new StringBuilder();
StringBuilder titleString = new StringBuilder();
StringBuilder sb = new StringBuilder();
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
LinkedHashMap<String, String> valuesMap = new LinkedHashMap<String, String>();
//System.out.println("fieldCount = "+fieldCount);
if(fieldCount > 0)
{
int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
//System.out.println(curValue);
valuesMap.put(csvFields[i], curValue);
}
catch(Exception exp)
{
//System.out.println(csvFields[i]);
exp.printStackTrace();
}
i++;
}
if(valuesMap.get("Hospital Name") != null && !valuesMap.get("Hospital Name").equals("blank")) {
titleString.append(valuesMap.get("Hospital Name"));
}

Set keySet = valuesMap.keySet();
Iterator keySetIterator = keySet.iterator();
//[oppso-map map_id="123" map_type="ROADMAP" bubble="" height="350px" width="400px" zoom="14" lat="12.95223" lon="77.52879"]
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
try {
if(!valuesMap.get(key).equals("blank")) {
String templateValue = columnsMap.get(key);
String actualValue = templateValue.replaceAll("<(.*)>", valuesMap.get(key));
if(key.equals("Latitude")) {
sb.append("\n\n");
String actualLat = lat.replaceAll("<(.*)>", valuesMap.get("Latitude"));
String actualLon = lon.replaceAll("<(.*)>", valuesMap.get("Longitude"));
sb.append(opps_map + map_id + map_type + bubble + height + width + zoom + actualLat + actualLon);
break;
}
sb.append(actualValue);
}
if(key.equals("Primary Contact Number")) {
Boolean toAppend = false;
for(int j = 0; j < contactNumbers.length; j++) {
if(!valuesMap.get(contactNumbers[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(alternateContactsString);
}
}
else if(key.equals(contactNumbers[contactNumbers.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < emailIds.length; j++) {
if(!valuesMap.get(emailIds[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(emailString);
}
}
else if(key.equals(emailIds[emailIds.length - 1])) {
Boolean toAppend = false;
for(int j = 0; j < extensionNumbers.length; j++) {
if(!valuesMap.get(extensionNumbers[j]).equals("blank")) {
toAppend = true;
}
}
if(toAppend) {
sb.append(extensionString);
}
}
else if(key.equals("Hospital Website")) {
Boolean toAppend = false;
if((valuesMap.get("Hospital Description") != null && !valuesMap.get("Hospital Description").equals("blank"))
|| (valuesMap.get("Hospital Speciality") != null && !valuesMap.get("Hospital Speciality").equals("blank"))) {
toAppend = true;
}
if(toAppend) {
sb.append(aboutHospitalString);
}
}
else if(key.equals("Hospital Speciality")) {
Boolean toAppend = false;
if((valuesMap.get("Awards & Recognition") != null && !valuesMap.get("Awards & Recognition").equals("blank"))) {
toAppend = true;
}
if(toAppend) {
sb.append(awardsString);
}
}
} catch (NullPointerException e){
System.out.println(key);
e.printStackTrace();
}
}
System.out.println(sb);
}
if(upload) {
baseUrl = "http://nueve.co.in/doctors/wp-admin/post-new.php";
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);

//baseUrl = "http://nueve.co.in/doctors/wp-admin/";
//Adding a new post with the required parameters.
//driver.get(baseUrl + "/doctors/wp-admin/");
driver.findElement(By.id("title-prompt-text")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys(titleString);
//driver.findElement(By.id("content_ifr")).clear();

driver.findElement(By.id("content-html")).click();
driver.findElement(By.id("content")).clear();
driver.findElement(By.id("content")).sendKeys(sb);

/*
driver.findElement(By.id("acf-field-speciality")).clear();
driver.findElement(By.id("acf-field-speciality")).sendKeys("Speciality");
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
driver.findElement(By.id("acf-since")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-since")).sendKeys("24 Jan");
//driver.findElement(By.id("dp1390624043131")).click();
driver.findElement(By.id("acf-field-phone")).click();
driver.findElement(By.id("acf-field-phone")).clear();
driver.findElement(By.id("acf-field-phone")).sendKeys("99999999999");
driver.findElement(By.id("acf-field-address")).clear();
driver.findElement(By.id("acf-field-address")).sendKeys("Address");
*/
if (valuesMap.get("Hospital Speciality") != null && !valuesMap.get("Hospital Speciality").equals("blank")) {
driver.findElement(By.id("new-tag-post_tag")).clear();
driver.findElement(By.id("new-tag-post_tag")).sendKeys(valuesMap.get("Hospital Speciality"));
driver.findElement(By.cssSelector("input.button.tagadd")).click();
}

driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.linkText("Main")).click();
new Select(driver.findElement(By.id("ta_post_review_rating"))).selectByVisibleText("4");
driver.findElement(By.linkText("Criteria")).click();
driver.findElement(By.name("ta_post_repeatable[0][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][title]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][desc]")).sendKeys("Quality of treatment");
driver.findElement(By.name("ta_post_repeatable[0][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[0][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[1][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][title]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][desc]")).sendKeys("Cost of treatment");
driver.findElement(By.name("ta_post_repeatable[1][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[1][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[2][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][title]")).sendKeys("Quality of facilities and equipments");
driver.findElement(By.name("ta_post_repeatable[2][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][desc]")).sendKeys("Quality of facilities and equipments");
driver.findElement(By.name("ta_post_repeatable[2][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[2][rating]")).sendKeys("0");
driver.findElement(By.linkText("+ Add")).click();
driver.findElement(By.name("ta_post_repeatable[3][title]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][title]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][desc]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][desc]")).sendKeys("Overall patient satisfaction");
driver.findElement(By.name("ta_post_repeatable[3][rating]")).clear();
driver.findElement(By.name("ta_post_repeatable[3][rating]")).sendKeys("0");

driver.findElement(By.id("in-category-106")).click();
synchronized (driver) {
try {
driver.wait(4000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

if(valuesMap.get("Unique ID") != null && !valuesMap.get("Unique ID").equals("blank")) {
driver.findElement(By.id("acf-field-index")).click();
driver.findElement(By.id("acf-field-index")).clear();
driver.findElement(By.id("acf-field-index")).sendKeys(valuesMap.get("Unique ID"));
}
//driver.findElement(By.id("dp1390624043131")).click();
//driver.findElement(By.linkText("10")).click();
if(valuesMap.get("Hospital Name") != null && !valuesMap.get("Hospital Name").equals("blank")) {
driver.findElement(By.id("acf-field-full_name")).click();
//driver.findElement(By.id("acf-since")).clear();
driver.findElement(By.id("acf-field-full_name")).clear();
driver.findElement(By.id("acf-field-full_name")).sendKeys(valuesMap.get("Hospital Name"));
}
//driver.findElement(By.id("dp1390624043131")).click();
if(valuesMap.get("Full Address") != null && !valuesMap.get("Full Address").equals("blank")) {
driver.findElement(By.id("acf-field-full_address")).click();
driver.findElement(By.id("acf-field-full_address")).clear();
driver.findElement(By.id("acf-field-full_address")).sendKeys(valuesMap.get("Full Address"));
}
//driver.findElement(By.id("acf-field-address")).clear();
//driver.findElement(By.id("acf-field-address")).sendKeys("Address");

synchronized (driver) {
try {
driver.wait(6000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
driver.findElement(By.id("publish")).click();
}
sb = null;
titleString = null;
}
if(upload) {
driver.close();
}
csvReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchElementException nse) {
nse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}