Sending JavaScript code to a Web Surveillance Server (CCTV) in Android - javascript

Im trying to send the pan tilt zoom commands to a web surveillance server provided by the device (DVR). I am able to access everything in the web server and i used fire bug in firefox to locate the specific JavaScript command that the buttons are sending to the server. I want to send that specific line of code from my android app. Should I use JSON or SOAP? Im not familiar with these two but i think it is the way to do it, i just don't know what to do specifically with these concepts.
this is the sample JavaScript i got from the web surveillance using firebug:
This is the content of the anchor tag:
<a class="y4" onmouseout="ajaxFunction('stop','directionleft')"
onmouseup="ajaxFunction('stop','directionleft')"
onmousedown="ajaxFunction('start','directionleft')" href="javascript:;"></a>
This is the script of the "ajaxFunction":
function ajaxFunction(req, param)
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³ÖAJAX£¡");
return false;
}
}
}
if(g_viewStatu[g_clicked].vbPlaying)
{
if(req=="start")
{
xmlHttp.open("POST","dvrcmd",true);
xmlHttp.send("command=ptz_req&req="+req+"&param="+param+"&channel="+g_viewStatu[g_clicked].nchannel+"&stream="+g_channelStatu[g_viewStatu[g_clicked].nchannel].streamStyle);
ptzstate = 1;
}
else if(req=="stop" && ptzstate == 1)
{
xmlHttp.open("POST","dvrcmd",true);
xmlHttp.send("command=ptz_req&req="+req+"&param="+param+"&channel="+g_viewStatu[g_clicked].nchannel+"&stream="+g_channelStatu[g_viewStatu[g_clicked].nchannel].streamStyle);
ptzstate = 0;
}
}
}

Answered my own question.. >.<
public void executePTZ(String cmd, String direction){
String posturl = "http://192.168.1.120";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
try {
httppost.setEntity(new StringEntity("command=ptz_req&req="+cmd+"&param="+direction+"&channel=1&stream=1"));
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

How to display additional info on mouseover with ajax and javascript

I have an e-commerce simulation web app for buying movies and I want a popup small window to appear when a user mouses over the movie's id and display info and give them the option to add that movie to their cart (like how Facebook displays users info when you mouseover one of your friend's names). I have a java servlet that receives the movie's id and gets the proper info from my database and sends it back to the JSP, but form there I don't know how to properly use AJAX or jquery to display the window with the proper info.
SERVLET CODE
int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
StringBuilder query = new StringBuilder("select * from movies where movies.id =");
query.append(movie_id);
// Perform the query
MySQLHandler sql_handler = new MySQLHandler( );
sql_handler.execute_query( query.toString() );
ResultSet result = sql_handler.get_result();
try {
Movie movie = createMovie(result);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(movie.getTitle());
request.setAttribute("movie", movie);
}
catch(SQLException e) {
e.printStackTrace();
}
}
JAVASCRIPT CODE
function ajaxFunction(movie_id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);
}
$.ajax({
url: 'route/to/videoinfo' + specificVideoId,
type: "POST",
contentType: "application/json ;charset=UTF-8",
}).done(function(result){
(if you rendered out the html already just do)
var containerDiv = document.getElementById("#idOfDivToFill")
containerDiv.innerHTML = result
}).fail(function(err){
console.log(err)
})
Someone let me know if this is terrible.

chrome 401 unauthorized javascript login

I'm currently developing a chrome extension, I need to access some http-auth protected resources (webdav). The HTTP auth is using (in the best case) a digest authentication.
The issue is : if the login/password is wrong, I can't just get a 401 status (unauthorized), Chrome pops up the regular authentication dialog. Which I don't want cause it's confusing for user and I can't save the credentials from here.
EDIT: Another use-case I faced is : I want to check if a resource is password-protected without trying to provide credentials to actualy access it.
Any ideas on how to catch the 401 without poping the Chrome's auth box ?
I try using this function:
function autoLogin(domain, user, password) {
var httpAuth;
if (window.XMLHttpRequest) {
httpAuth = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
httpAuth = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
else {
alert("Seu browser não suporta autenticação xml. Favor autenticar no popup!");
}
var userName = domain + "\\" + user;
httpAuth.open("GET", "/_layouts/settings.aspx", false, userName, password);
httpAuth.onreadystatechange = function () {
if (httpAuth.status == 401) {
alert("wrong");
eraseCookie('AutoLoginCookieUserControl_User');
eraseCookie('AutoLoginCookieUserControl_Password');
}
else {
if ($(".pnlLogin").is(':visible')) {
$(".pnlLogin").hide();
$(".pnlUsuario").css("display", "block");
$(".avatar").css("display", "block");
var name = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });
$(".loginNomeUsuario").html("Seja Bem Vindo(a) <br />" + name);
}
}
}
try {
httpAuth.send();
}
catch (err) {
console.log(err);
}
}

AJAX call to struts action not working

Hi i have a requirement in which i have to check something from struts action class and then send the result back to the browser using ajax call called in a JS fx'.The issue is im not able to hit the action class and console is throwing the following error:
org.apache.struts.action.RequestProcessor processActionCreate No action instance for path /ChangePwdAjax could be created
java.lang.ClassNotFoundException:test.ChangePwdAjaxAction.java
The class is compiled and the package context is valid test.ChangePwdAjaxAction.java
Any ideas what and where im doing it wrong?
Here is what i have written so far.
JS code
function checkError()
{
var valuePassword="test";
var url = "/test/ChangePwdAjax.do?newPass="+valuePassword;
var xmlHTTP = getXMLHTTPRequest();
xmlHTTP.onreadystatechange = function() {
handleResponse(xmlHTTP); }
xmlHTTP.open("GET",url,true);
xmlHTTP.send();
}
function handleResponse(xmlHTTP){
alert("handleResponse");
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
alert("handleResponse");
var xmlDoc = xmlHTTP.responseXML;
alert(xmlDoc.documentElement.getElementsByTagName("pwdFlag")[0].text);
}
}
function getXMLHTTPRequest(){
alert("getXMLHTTPRequest");
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("XMLHttpRequest is not supported!");
}
}
Action class code
public class ChangePwdAjaxAction extends Action {
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
final HttpServletRequest request,final HttpServletResponse response)
{
System.out.println("----IN--AJAX ACTION----------");
final HttpSession session= request.getSession(false);
if(session==null || session.getAttribute("user_id")==null){
return mapping.findForward("sessionexpired");
}
final String user_id=(String)session.getAttribute("user_id");
try{
final BusinessDelegate busdel=new BusinessDelegate(user_id,session.getId());
String newpwd = (String)request.getParameter("newPass");
boolean b=busdel.checkOldPWd(user_id, newpwd);
//checking return values from bus delegate
response.setContentType("text/xml");
PrintWriter printwriter = response.getWriter();
printwriter.println("<?xml version=\"1.0\"?>");
printwriter.println("<Root>");
if(b)
{
System.err.println("----New password Failed--Y--------");
printwriter.println("<pwdFlag>"+"Y"+"</pwdFlag>");
}
else
{
System.out.println("----New password OK---N-------");
printwriter.println("<pwdFlag>"+"N"+"</pwdFlag>");
}
printwriter.println("</Root>");
}catch(Exception e){
logger.logCommon("Login Action : Login Process in Action : ", "EXCEPTION");
logger.logError(e);
}
return null;
}
}
Struts-config entry
<action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>
OOps this had to be
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction"/>
rather than
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>

How get the data using MVC- Servlets, JPS and JavaScripts

I have JSP page that has links (When people click on the link it is supposed to go to a servlet and then Bean class and DB Connection class to pull the data)..and when a user clicks on the like I tried to display the page using AJAX...however i am currently not getting any data/page pulled. Can someone please explain on how to achive this?
here is the link i have in my HTML page..but when i click on it is not showing up anything.
VT
Thanks for your help
Sorry here is my code
public class VacationTrackerDAO {
public static List<VactionTrackerBean> list() throws SQLException{
List<VactionTrackerBean> appr= new ArrayList<VactionTrackerBean>();
try{
DBConnection conObj=new DBConnection();
Connection dbCon= conObj.getCon();
Statement stmt=conObj.getStmt();
String queryCPList="select * from Capacity_Plan";
String queryApprList="Select First_Last_Name from Vacation_Approvers";
PreparedStatement preStmtCPList=dbCon.prepareStatement(queryCPList);//get metadat
PreparedStatement preStmtApprList=dbCon.prepareStatement(queryApprList);//get names
ResultSet rsCPList=preStmtCPList.executeQuery();
ResultSet rsApprList=preStmtCPList.executeQuery();
ResultSetMetaData metaCPList=rsCPList.getMetaData();
VactionTrackerBean vtBean=new VactionTrackerBean();
while(rsApprList.next()){
vtBean.setApprover((rsApprList.getString("First_Last_Name")));
appr.add(vtBean);
}
}catch(Exception e){
System.out.println("In the Vacation TrackerDAO.java class:"+e);
}
return appr;
}
}
Here is my Servlets which gets the request.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
List<VactionTrackerBean> vacBean=VacationTrackerDAO.list();
request.setAttribute("vacTracker", vacBean);
request.getRequestDispatcher("WEB-INF/VacationTracker.jsp").forward(request,response);
}catch (SQLException e){
System.out.println("Error in VacationTracker.java due to VactionTrackerDA.java:"+e);
request.getRequestDispatcher("WEB-INF/Error.jsp").forward(request,response);
}
Here is the code that i have in the JSP page.
<li> <a href="Main.jsp" > home </a> </li>
<li>Vacation Tracker </li>
</ul>
Here is the code for my Javascript
function getHTTPObject(){
var xhr=false;
if(window.XMLHttpRequest){
xhr= new XMLHttpRequest();
} else if(window.ActiveXObject){
try{
xhr= new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
xhr=false;
}
}
}
return xhr;
}
function grabfile(file){
var request=getHTTPObject();
if(request){
request.onreadystatechange=function(){ displayResponse(request);};
}
request.open("POST",file,true);
request.send(null);
}
function displayResponse(request){
if(request.readyState==4){
if(request.status==200){
document.getElementById ("middle_sub").innerHTML=request.responseText;
}
}
}

onclick insert in to ms sql database

I have asp.net application with JavaScript and I want to save in to ms sql DB additional information(TimeStamp) when a button is clicked.
onclick= "functionName();"
the function "functionName()" has another task and I want another function that store the timestamp as well
Write JS as below:
function functionName() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var now = new Date(); // You can also any kind of data using query string
xmlhttp.open("GET", "saveTimespan.aspx?datetime=" + now, true);
xmlhttp.send();
}
Write below code to code behind of saveTimespan.aspx' page as below(remove all markup other thanPage` directory of this page):
protected void Page_Load(object sender, EventArgs e)
{
UpdateTimeStamp();
}
public void UpdateTimeStamp()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE TargetTable SET DateTimColumnName = #DateTimColumnName";
cmd.Parameters.AddWithValue("#DateTimColumnName", MyDateTime);
cmd.CommandType = CommandType.Text;
try
{
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
Response.Write("Data Updated Successfully!");
}
}
catch (Exception ex)
{
//Handle exception
}
}
Try using jQuery ajax, would be easier like
function functionName() {
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
}
Ref: http://api.jquery.com/jQuery.ajax/

Categories

Resources