Archive

Archive for November, 2011

Algorithrm Links

November 28, 2011 Comments off
Categories: Algorithms

Binary Search in a sorted rotated array

November 28, 2011 Comments off

public class RotatedBinarySearch
{
private long[] input ={ 8, 9, 10, 1, 2, 3, 4, 5, 6, 7 };
private long searchElement = 8;

public RotatedBinarySearch()
{
System.out.println("Element found at index ::" + rotatedSearch(input, 0, input.length - 1,searchElement));
}

public int rotatedSearch(long[] values, int start, int end, long x)
{
int middle = (start + end) / 2;
long startVal = values[start];
long midval = values[middle];
long endVal =  values[end];


if (startVal == x)
{
return start;
}
else if (endVal == x)
{
return end;
}
else if (end - start == 1)
{
return -1;
}

if (startVal <= midval)
{
if (x <= midval && x >= startVal)
{
return rotatedSearch(values, start, middle, x);
}
else
{
return rotatedSearch(values, middle, end, x);
}
}
else if (midval <= endVal)
{
if (x >= midval && x <= endVal)
{
return rotatedSearch(values, middle, end, x);
}
else
{
return rotatedSearch(values, start, middle, x);
}
}
else
{
return -1;
}
}

public static void main(String[] args)
{
new RotatedBinarySearch();
}
}

Categories: Algorithms

Binary Search Implementation with out Recursion

November 28, 2011 Comments off

public class BinarySearch
{
private long [] input = {1,2,3,4,5,6,7,8,9,10};
private long searchElement = 10;

public BinarySearch()
{
printSearchIndex(input);
}

public void printSearchIndex(long [] input)
{
long currElement = 0;
int index = 0;
int startIndex = 0;
int endIndex = input.length;

while(startIndex < endIndex)
{
index = (startIndex + endIndex)/2;
currElement = input[index];

if(currElement > searchElement)
{
endIndex = index - 1;
}else if(currElement < searchElement)
{
startIndex = index + 1;
}else
{
System.out.println("Element found at "+index);
return;
}
}
}

public static void main(String[] args)
{
new BinarySearch();
}

}

Categories: Algorithms

Implementing Binary Search using Recursion

November 28, 2011 Comments off

public class BinarySearch
{
private long [] input = {1,2,3,4,5,6,7,8,9,10};
private long searchElement = 10;

public BinarySearch()
{
System.out.println("Element found at index ::"+getSearchIndex(input,0,input.length -1));
}

public long getSearchIndex(long [] input , int beginIndex , int endIndex)
{
int index = (beginIndex + endIndex) / 2;

if(input[index] == searchElement)
{
return index;

}else if(input[index] < searchElement)
{
return getSearchIndex(input,index+1 , endIndex);

}else
{
return getSearchIndex(input,beginIndex ,index - 1);
}
}

public static void main(String[] args)
{
new BinarySearch();
}
}

Categories: Algorithms

Java Program for calculating X^n in o(log n ) time complexity

November 21, 2011 Comments off

public class TestMain
{
private static long hits1;
private static long hits2;

public static void main(String[] args)
{
TestMain main = new TestMain();

System.out.println("Normal Result ::"+main.power(2,31));
System.out.println("Hits ::"+hits1);

System.out.println("Optimised Result ::"+main.normalPow(2,31));
System.out.println("Hits ::"+hits2);

}

public long normalPow(long x , long n)
{
long result = 1;

while(n > 0)
{
result = result * x;

n--;

//for calculating hits
hits2++;
}

return result;

}

public long power(long x , long n)
{
//for calculating hits
hits1 ++;
if(n == 0)
{
return 1;
}

long temp = power(x,n/2);
if( n%2 == 0)
{
return (temp * temp );
}else
{
return (temp * temp * x);
}
}
}

Categories: Algorithms

FileUpload HTML Page

November 17, 2011 Comments off
<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File download and upload sample</title>
css" href="css/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/<span class=">// <![CDATA[
javascript</span>" src="js/jquery-1.3.2.min.js">
// ]]></script>
<script type="text/<span class=">// <![CDATA[
javascript</span>" src="js/jquery-ui-1.7.2.custom.min.js">
// ]]></script>
<script type="text/<span class=">// <![CDATA[
javascript</span>" src="js/jquery.form.js">
// ]]></script>
<script type="text/javascript">
$(document).ready(function()
{
$(function()
{
$("#tabs").tabs();
});

$( "#status" ).hide();
$( "#fileListResult" ).hide();

// attach handler to form's submit event
$('#uploadKeyForm').submit(function() {
// submit the form
$(this).ajaxSubmit(function(e) {

$( "#message" ).html(e);
$( "#status" ).show();
$('#uploadKeyForm').clearForm();
});
return false;
});

// attach handler to form's submit event
$('#fileListForm').submit(function() {
// submit the form
$(this).ajaxSubmit(function(e) {

$( "#fileListResult" ).html(e);
$( "#fileListResult" ).show();
$( "#fileListForm" ).clearForm();

});
return false;
});
});
function showDialog( text )
{
$("#dialog").attr({ innerHTML: text });
$("#dialog").dialog(
{
bgiframe: true,
modal: false,
});
$("#dialog").dialog( 'open' );
}
</script>
</head>
<body>
<div>
<div>20px; padding: 0 .7em;"></div>
<p align="center"> Health Control Panel</p>
</div>
</div>

<br />
<div id="tabs">
<ul>
<li><a href="#tabs-1">Upload File</a></li>
<li><a href="#tabs-2">Download File</a></li>
</ul>
<div id="tabs-1" title="Upload File">1px solid black; text-align: left;"></div>
&nbsp;

<form id="uploadKeyForm" action="/<span class=" method="post" enctype="multipart/form-data">Commonsfileuploadservlet" target="submitFrame"></form>
<table width="100%">
<tr>
<td>
<div id="status">
<div>20px; padding: 0 .7em;"></div>
<p id="message" align="center">Health Control Panel</p>
</div>
</div>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>Start IP-Address*</td>
<td><input id="sIp" name="sIp" type="text"></td>
</tr>
<tr>
<td>End IP-Address</td>
<td><input id="eIp" name="eIp" type="text"></td>
</tr>
<tr>
<td>User Name*</td>
<td><input id="un" name="un" type="text"></td>
</tr>
<tr>
<td>Password*</td>
<td><input id="pwd" name="pwd" type="password"></td>
</tr>
<tr>
<td>Destination Dir*</td>
<td><input id="dd" name="dd" type="text"></td>
</tr>
<tr>
<td>File*</td>
<td><input id="ks" name="ks" type="file"></td>
</tr>
<tr>
<td><input type="submit" id="uploadKey" value="Upload File"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<iframe id="submitFrame" name="submitFrame" style="display: none; visibility: hidden">
<div id="tabs-2" title="Download File">1px solid black; text-align: left;"></div>
&nbsp;

<form id="fileListForm" action="/<span class=" method="post">listFiles" target="submitListFrame"></form>
<table width="100%">
<tr>
<td>
<table>
<tr>
<td>Server IP*</td>
<td><input id="tsIP" name="tsIP" type="text"></td>
</tr>
<tr>
<td>User Name*</td>
<td><input id="tUN" name="tUN" type="text"></td>
</tr>
<tr>
<td>Password*</td>
<td><input id="tpwd" name="tpwd" type="password"></td>
</tr>
<tr>
<td>Destination Dir</td>
<td><input id="dd" name="dd" type="text"></td>
</tr>
<tr>
<td><input type="submit" id="listFiles" value="List Files"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div id="fileListResult"></div>
</div>
</div>
</body>
</html>
Categories: General

FileUploadServlet

November 17, 2011 Comments off

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rapidhealth.dao.RapidHealthDAO;
import com.rapidhealth.pojo.DiscoveryConfig;
import com.rapidhealth.scp.SCPDispatcher;
import com.rapidhealth.utils.ApplicationContextHolder;

public class FileUploadServlet extends HttpServlet
{
private final Logger log = LoggerFactory.getLogger(FileUploadServlet.class);

private static final String TMP_DIR_PATH = "/tmp";
private static final String DESTINATION_DIR_PATH = "/repository";

private File tmpDir;
private File destinationDir;
private String realPath;

public void init(ServletConfig config) throws ServletException
{
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory())
{
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory())
{
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String fileName = null;

PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);

ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try
{
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
DiscoveryConfig config = new DiscoveryConfig();
while (itr.hasNext())
{
FileItem fi = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if ( fi.isFormField() )
{
System.out.println("File Name = " + fi.getFieldName() + ", Value = " + fi.getString());
if(fi.getFieldName().equals("sIp"))
{
config.setStartIp(fi.getString());
}else if(fi.getFieldName().equals("eIp"))
{
config.setEndIp(fi.getString());
}else if(fi.getFieldName().equals("un"))
{
config.setUserName(fi.getString());
}else if(fi.getFieldName().equals("pwd"))
{
config.setPwd(fi.getString());
}else if(fi.getFieldName().equals("dd"))
{
config.setDestFileDirLoc(fi.getString());
}
}
else
{
fileName = fi.getName();

config.setFileName(fileName);
config.setFileLoc(realPath+File.separatorChar+fileName);
config.setCreatedDateTime(System.currentTimeMillis());

File file = new File(destinationDir, fi.getName());
fi.write(file);
}
}
log.info("File {} uploaded successfully at location {}",fileName,destinationDir);

RapidHealthDAO healthDAO = (RapidHealthDAO)ApplicationContextHolder.getAppContext().getBean("rapidDAO");
healthDAO.saveorupdate(config);

log.debug("Configuration Saved to DB Successfully");

SCPDispatcher dispatcher = (SCPDispatcher)ApplicationContextHolder.getAppContext().getBean("scpPool");
dispatcher.startupload(config);
log.debug("File {} started uploading",config.getFileName());

out.print("File upload started successfully");
}
catch (Exception ex)
{
log("Error encountered while parsing the request", ex);

out.print("Failed to save data");
}
out.close();
}
}
Categories: General