mechanize and redirecting (ruby) - ruby

I thought that mechanize follows redirection by default ... by my script ends at the redirection page. How can I handle this?
require 'rubygems'
require 'mechanize'
agent = WWW::Mechanize.new
page = agent.get("http://www.vbulletin.org/forum/index.php")
login_form = page.form_with(:action => 'login.php?do=login')
login_form['vb_login_username'] = 'user name'
login_form['vb_login_password'] = ''
login_form['vb_login_md5password_utf'] = 'md5 hash from the password'
login_form['vb_login_md5password'] = 'md5 hash from the password'
page = agent.submit login_form
#Display welcome message if logged in
puts page.parser.xpath("/html/body/div/table/tr/td[2]/div/div").xpath('text()').to_s.strip
output = File.open("login.html", "w") {|f| f.write(page.parser.to_html) }
redirection page html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head>
<body>
<noscript>
<meta http-equiv="Refresh" content="2; URL=http://www.vbulletin.org/forum/index.php">
</noscript>
<script type="text/javascript">
<!--
function exec_refresh()
{
window.status = "Redirecting..." + myvar;
myvar = myvar + " .";
var timerID = setTimeout("exec_refresh();", 100);
if (timeout > 0)
{
timeout -= 1;
}
else
{
clearTimeout(timerID);
window.status = "";
window.location = "http://www.vbulletin.org/forum/index.php";
}
}
var myvar = "";
var timeout = 20;
exec_refresh();
//-->
</script><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="generator" content="vBulletin 3.6.12">
<meta name="keywords" content="vbulletin,forum,bbs,discussion,jelsoft,bulletin board,hacks,modifications,addons,articles,programming,site review">
<meta name="description" content="This is a discussion forum powered by vBulletin. To find out about vBulletin, go to http://www.vbulletin.com/ .">
<!-- CSS Stylesheet --><link rel="stylesheet" type="text/css" href="clientscript/vbulletin_css/style-befeb917-00023.css" id="vbulletin_css">
<link rel="stylesheet" type="text/css" href="clientscript/blue.css" id="blue">
<!-- / CSS Stylesheet --><script type="text/javascript">
<!--
var SESSIONURL = "";
var SECURITYTOKEN = "c1e3de2fd54e2938c4ab1e80ae448aa6bbea25b2";
var IMGDIR_MISC = "images/misc";
var vb_disable_ajax = parseInt("0", 10);
// -->
</script><script type="text/javascript" src="clientscript/vbulletin_global.js?v=3612"></script><link rel="alternate" type="application/rss+xml" title="vBulletin.org Forum RSS Feed" href="external.php?type=RSS2">
<!-- VB.ORG --><!-- The line above sets the script var and must be left in --><script type="text/javascript">
<!--
script = "login";
userid = "0";
forumid = "";
threadid = "";
authorid = "";
// -->
</script><script type="text/javascript" src="clientscript/vborg_miscactions.js?v=3612"></script><!-- /VB.ORG --><title>vBulletin.org Forum</title>
<div id="container" style="border-width:0;width:950px">
<br><br><br><br><form action="http://www.vbulletin.org/forum/index.php" method="post" name="postvarform">
<table class="tborder" cellpadding="4" cellspacing="1" border="0" align="center">
<tr>
<td class="tcat">Redirecting...</td>
</tr>
<tr>
<td class="panelsurround" align="center">
<div class="panel">
<blockquote>
<p> </p>
<p><strong>Thank you for logging in, my username.</strong></p>
<p class="smallfont">Click here if your browser does not automatically redirect you.</p>
<div> </div>
</blockquote>
</div>
</td>
</tr>
</table>
</form>
<br><br><br><br>
</div>
</body>
</html>

There is an option in mechanize for that. Mechanize does not follow meta refreshes by default, we can set that option though.
agent.follow_meta_refresh = true

Are you sure it's HTTP 30x Redirect response? Not normal "200 OK" response with page containing <meta http-equiv="refresh" content="100;url=...">. Mechanize follows first type of redirection, second is just normal response with link, which you should follow.
I can't check, because you didn't posted username/password in code.
Edit:
After your update, this should be enough to follow redirection after login:
page.link_with(:text => "Click here if your browser does not automatically redirect you.").click

Related

Spring + Thymeleaf + Dropzone

I might sound strange with this question but I'm very new into those three technologies - Spring, Thymeleaf and Dropzone.
I am currently trying to get a html page resulting from a response from my Spring Controller + Thymeleaf with a request from a Dropzone file upload.
So my Controller receive the file from dropzone, reads it, apply some parsing and return the result as a html page, like a report.
It works as expected if I use a simple form like the one available in Spring tutorial site.
But when I put Dropzone I simply can't get the result from this html page.
I'll leave here my upload html (I've been trying to get the result and print into a div, without success):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>My upload form with Dropzone</title>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<script>
Dropzone.options.myDropZone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 1,
paramName: "file",
// The setting up of the dropzone
init: function() {
var myDropzone = this;
var submitButton = document.getElementById("btnStartUpload");
submitButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
this.on("sendingmultiple", function(file, xhr, form) {
form.append("file", file);
});
this.on("success", function(file, response) {
console.log(response);
$(".result").html(response);
});
}
}
</script>
</head>
<body>
<div id="dropzone">
<form id="myDropZone" class="dropzone" th:action="#{/upload}" method="POST" enctype="multipart/form-data">
<div class="previews"></div>
<button id="btnStartUpload">Submit file!</button>
</form>
</div>
<div id="result" class="result"></div>
</body>
My Controller:
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile (#RequestParam("file") MultipartFile file, ModelMap model)
{
try
{
// parse file and insert a collection into attribute, to be used in the 'result' page.
model.addAttribute("fields", /*collection*/);
return "result";
}
catch (IOException e)
{
e.printStackTrace();
return "failed";
}
}
And then my result html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>My result page</title>
</head>
<body>
<table>
<tr>
<td>F1</td>
<td>F2</td>
<td>F3</td>
</tr>
<th:block th:each="field : ${fields}">
<tr>
<td th:text="${field.name}"></td>
<td th:text="${field.value}"></td>
<td th:text="${field.description}"></td>
</tr>
</th:block>
</table>
</body>
</html>

Search page in spring mvc doesn't work

I Have created simple mvc CRUD. All works fine except search page.
Im getting errorr as follows:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
Controller page is:
#RequestMapping(value="/search")
public ModelAndView search(){
return new ModelAndView("search","command", new Emp());
}
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public ModelAndView search1(#ModelAttribute("name") Emp emp){
String name = null;
name = dao.searchname(name);
return new ModelAndView("searchemp","name",name);
}
Search.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>z
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
label {
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
.box{background-color: #e1e8f0;}
body{background:#f0eceb;}
</style>
</head>
<body>
<div style=" left: 30%; top: 25%; position: absolute;">
<div class="col-sm-12 col-sm-offset-3 box " >
<center> <h1>Add New Employee</h1> </center>
<form method="post" action="jsp/searchemp/" >
<div class="form-group"> <div class="col-xs-7">
<label ><h5>Name :</h5></label>
<input name="name" class="form-control" placeholder="Enter Name of the employee" />
<button type="submit" value="Save" class="btn btn-primary btn-lg">Search</button>
</div></div>
</form>
</div>
</div>
</body>
</head>
Searchemp.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Employees List</h1>
<table class="table table-hover" border="1" width="70%" cellpadding="2">
<thead>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody><tr>
<td>${String.id}</td>
<td>${String.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr> </tbody>
</table>
<br/>
Add New Employee
jdbctemplate query:
public String searchname(String name) {
String query = "select * from Emp99 where name=?";
Object[] inputs = new Object[] {name};
String empName = template.queryForObject(query, inputs, String.class);
return empName;
}
Dont know what goes wrong.
help me.
in order for jsp to consume an bean , your controller method should return data,in your jsp you are trying to utilize
{String.id} and {emp.id} which is never passed from the controller method search1.so you need to add your beans to a model and
return the page like this.
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public String search1(#ModelAttribute("name") Emp emp,Model model){
model.addAttribute("emp",emp); //passing the model name and the bean ,
//model.addAttribute("name",anotherBean); //you can add many attributes as you wish.
return "searchemp";
}
now inside the searchemp.jsp you can utilize the emp bean like this.
{emp.id}
remove the {String.id} part. inside the searchemp.jsp which will not work.

Classic ASP Auto complete

I'm using classic ASP to create an auto-complete page. I have two different pages, autocomplete.asp and source.asp. My code as below:
autocomplete.asp
<%# language="VBScript" %>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<!-- SCRIPT FOR AUTOCOMPETE SEARCH BOX //-->
<script type="text/javascript" language="javascript">
$(function () {
$("#productname").autocomplete({
source: "source.asp",
minLength: 2
});
});
</script>
</head>
<body>
<p> </p>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="productname">
</div>
<p> </p>
</body>
</html>
sourse.asp
<%# language="VBScript" %>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2 /jquery.js" ></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" ></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css"/>
<!-- SCRIPT FOR AUTOCOMPETE SEARCH BOX //-->
</head>
<%
Dim keywords, keywords_cmd, output, firstItem
Set keywords_cmd = Server.CreateObject ("ADODB.Command")
keywords_cmd.ActiveConnection = "DRIVER={SQL Server};SERVER=wsgpdba4.sgp.is.keysight.com;UID=kportal;PWD=q1w2e3r4;DATABASE=A_Sys"
keywords_cmd.CommandText = "SELECT ProductId FROM Product where ProductId like '%" & Request.QueryString("term") & "%'"
keywords_cmd.Prepared = true
Set keywords = keywords_cmd.Execute
output = "["
While (NOT keywords.EOF)
output = output & "{""ProductId"":""" & keywords.Fields.item("ProductId") & """},"
keywords.MoveNext()
Wend
keywords.Close()
Set keywords = Nothing
output=Left(output,Len(output)-1)
output = output & "]"
response.write output
%>
<body>
</body>
</html>
The source.asp return me like this:
[{"ProductId":"111 "}]
Please help
I had to work on a legacy program recently. I had to get autosuggest to work with SQL and ASP. This is what I came up with.
<%# Language=VBScript %>
<!-- #include File="CarrierAutocomplete.inc"-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link href="jquery-ui-1.12.1.custom/jquery-ui.css">
<script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script>
$(function() {
var strCarriers = [<%=getListOfCarriers()%>];
$( "#carrier_name" ).autocomplete({
source: strCarriers
});
});
</script>
</head>
<body>
<table>
<tr>
<td align="right"><p><b>CARRIER:</b></td>
<label for="carrier_name"></label></td>
<td><input id="carrier_name" name="carrier_name"></td>
</tr>
</table>
</body>
</html>
'CarrierAutoComplete.inc
<!--#include file="ConnStrings.inc"--> 'you won't need this
<%
Function getListOfCarriers()
Set conn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
Dim sql
Dim allCarriers
Dim strCarriers
Dim n
'conn.Open ConnString 'PRODUCTION
conn.Open ConnString 'DEVELOPMENT
sql = "SELECT [carrier] FROM [dbo].[VerifiedCarriers] order by carrier"
Set RS = Conn.Execute(sql)
if not rs.eof and err.number=0 then
allCarriers = rs.getrows
End If
colStart = LBound(allCarriers, 1)
colEnd = UBound(allCarriers, 1)
rowStart = LBound(allCarriers, 2)
rowEnd = UBound(allCarriers, 2)
For row=rowStart to rowEnd
For col=colStart to colEnd
strCarriers = strCarriers + """" & "" & allCarriers(col,row) & """," & chr(13)
Next
Next
strCarriers = Left(strCarriers,Len(strCarriers) - 2) 'REMOVE THE LAST COMMA
response.write strCarriers
End Function
%>
I'm not 100% clear on the issue here, but the jquery ui control needs to have data in an expected form of value and label:
[{"value":"111", "label":"sample product"}]
Or you can just supply an array of strings if you're not concerned about the values:
["product one", "product two"]
You're also not selecting the product name from your db, just the Id, as I assume your autocomplete needs to show a list of product names?

I'm trying to change button text by calling action method using ajax.actionlink. That method is returning a string as button ID in new page

LAYOUT:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/bootstrap")
#Scripts.Render("~/bundles/modernizr")
<link rel="Stylesheet" href="../../Content/bootstrap.min.css" />
<link rel="Stylesheet" href="../../Content/bootstrap-theme.min.css" />
</head>
#*<body style="background-image: url(../../Content/Images/old-paper.jpg)">*#
<body style="background-color: #EEE">
#*---- WEB PAGE ---- *#
<div class="wrap-middle">
#*---- TITLE OF THE WEBSITE ----*#
<div class="container-fluid" style="width: 100%; background-image: url('/Content/Images/Header.bmp')">
<div>
<h1>
ONLINE VOTING SYSTEM</h1>
</div>
</div>
#*---- BODY SECTION ----*#
<div class="jumbotron">
<div class="container">
#RenderBody()
</div>
</div>
<div class="navbar navbar-inverse navbar-fixed-bottom" style="box-shadow: 0 0 20px black;">
<div class="container-fluid" style="color: Yellow">
Copyright <sup><span class="glyphicon glyphicon-copyright-mark"></span></sup>2014.
</div>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
VIEW:
#model IEnumerable<Online_Voting_System_site.DAL.tbl_candidate>
#{
ViewBag.Title = "CandidateApproval";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Ajax.ActionLink("Approve",
"ApproveCandidate",
new { _CandidateID = item.CandidateID },
new AjaxOptions { UpdateTargetId = item.CandidateID.ToString() },
new { #id = item.CandidateID.ToString(), #class = "btn btn-sm btn-success" })
ACTION METHOD:
public string ApproveVoter(string ID)
{
/* Logic is hidden.I use that ID parameter in here */
return "Approved";
}
I'm trying to change button text by calling action method using
ajax.actionlink. That action method is returning a string as button ID
but it displayed in new page.
Edit: The string should the text of the button. But the text is getting displayed in a new page.

Jquery/Ajax working in Safari but not Firefox

This is a test page. There is a button that on click should load an entire external page extern2.php into the content div. Extern2.php works in both Safari and Firefox, however index.php only works in Safari.
The main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax Test</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript">
function foo() {
$('#content').load('extern2.php', function() {
alert('Load was performed.');
});
}
</script>
<meta name="robots" content="index, follow, noarchive" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input type="submit" name="formSubmit" value="Submit" />
</form>
<?php
if(isset($_POST['formSubmit']))
{
?>
<script type="text/javascript">
$(document).ready(function() {
$('#content').load('extern2.php');
});
</script>
<?
}
?>
<div id="content">Initial content in test.html</div>
</body>
</html>
The external page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<meta name="robots" content="index, follow, noarchive" />
<link rel="stylesheet" href="style.css" type="text/css" />
<!-- This includes the ImageFlow CSS and JavaScript -->
<link rel="stylesheet" href="imageflow.packed.css" type="text/css" />
<script type="text/javascript" src="imageflow.packed.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<?php
// Connecting to database
$con = mysql_connect('CONNECT INFO HERE');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("CONNECT INFO HERE", $con);
$userID=2;
$getPage="SELECT * FROM pages,thumbnails WHERE thumbnails.thumbnailID=pages.thumbnailID AND pages.userID=".$userID." AND pages.projectID='8' LIMIT 3";
$pageResult = mysql_query($getPage) or die(" ". mysql_error());
?>
<!-- This is all the XHTML ImageFlow needs -->
<div id="myImageFlow" class="imageflow">
<? while($line = mysql_fetch_array($pageResult)) {
$thumb = $line['fileName'];
$title = $line['title'];
$link = $line['url'];
echo "<img src='../../thumbnails/small/".$thumb."' longdesc='".$link."' alt='".$title."' />";
}
?>
</div>
<?
mysql_close($con);
?>
</body>
</html>
What does the error console (CTRL-SHIFT-J) say? Also does Firebug help at all?

Resources