servlet - client connection in a chat application to send messages - java

<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<meta charset="utf-8">
<title>Chat</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#button').click(function() {
$.get('/backEnd', function(data) {
$("#textarea").html(data);
});
});
});
</script>
</head>
<body>
<label for="textarea">
<blockquote>
<ul>
<ul>
<li><strong>Session Progress</strong></li>
</ul>
</ul>
</blockquote>
</label>
<p>
<textarea name="textarea" cols="88" rows="33" id="textarea"></textarea>
</p>
<button id="button">Update</button>
<p> </p>
<p>
<label for="textarea2">
<ul>
<ul>
<li><strong>Session Message input</strong></li>
</ul>
</ul>
</label>
<textarea name="textarea2" cols="44" rows="11" id="textarea2"></textarea>
</p>
<p>
<input type="button" name="button" id="button" value="Send">
</p>
</body>
</html>
the above is the jsp for the chat page, the user should type text into textarea2 and accordingly it should appear in textarea1 if it was sent successfully, but how can i do this in order for 2 clients to talk with each other

One way to do it
You should have a servlet which has an action where the messages from both sides are posted. This servlet should hold those messsages in some kind of data structure. Now both conversation sides should poll a different action in certain time interval to check if new messages have appeared in this collection and update those text areas accordingly.
This is one of many many ways to implement your requirements.

Related

Using a form to display model objects in Thymeleaf. Is there a better way to do this?

been trying to get comfortable with Spring Boot/Thymeleaf/frontend development in general. I'm currently using a table on the frontend to display a list of objects from the backend, as well as a form to allow users to view properties of each item in the list.
I feel like the way I'm doing this is really weird and feel that there could be a better way. Would appreciate any tips/feedback, thank you.
HTML/Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Gambler Card List</title>
<link th:href="#{/css/styles.css}" rel="stylesheet" />
</head>
<body>
<h1>Gambler Card List</h1>
<div class="cardlist-wrapper">
<div class="cardlist-names">
<form action="/gambler/cardlist" method="get">
<table class="cardlist-table">
<tr th:each="card : ${cardList.getCardList()}">
<td>
<input th:class="card-btn"
th:attr="id=${{card.getId()} == {currentCard.getId()} ? 'selected' : ''}"
type="submit" th:value="${card.getName()}" name="cardName">
</td>
</tr>
</table>
</form>
</div>
<div class="cardlist-description">
<h4 th:text="${currentCard.getDescriptionTitle()}"></h4>
<p th:text="${currentCard.getDescription()}"></p>
</div>
</div>
</body>
</html>
Controller
#RequestMapping(value = "gambler/cardlist")
public String baseCardList(Model model,
#RequestParam(value="cardName", required=false) String cardName) {
model.addAttribute("currentCard", cardList.getCardByName(cardName));
model.addAttribute("cardList", cardList);
return "gambler/cardlist";
}
Output (need 10 rep to post image, so here's a link)
One potential improvement/simplification is to remove the form and replace the inputs with anchors. The anchors would look something like this (not tested!):
<a th:href="#{/gambler/cardlist(cardName=${card.name})}">
<button th:text="${card.name}"
th:classappend="${card.id == currentCard.id ? 'selectedButton' : 'deselectedButton'}">Card Name</button>
</a>
You can style selectedButton and deselectedButton as you wish.

Is there a way in Selenium to overcome Safari browser's same origin policy in click on a button within iFrame?

I'm trying to click on a Submit button within an iFrame. Trying to switch with iFrame id gives "Blocked a frame with origin from accessing a cross-origin frame" error.
<iframe id="challengeFrame" name="challengeFrame" width="250" height="400">
<html>
<body>
<form id="capture" class="challenge-form" action="capture" method="POST">
<div class="column">
<ul class="options">
<li>
....
</li>
<li>
...
</li>
</ul>
</div>
<div class="column">
<input type="submit" class="button" value="Submit">
</div>
</form>
</body>
</html>
</iframe>
In the above iFrame I need to click on the submit button. Please suggest any method with example to achieve this in Selenium Java/JS framework.
Be sure to include in your chrome options this argument:
options.add_argument("--disable-web-security")
This should disable the CORS check.

How to convert this for velocity template?

I have html content. I want to convert it to velocity template. Please provide the steps to be taken to convert it to template.
I need to insert the html in database also.
Following is the html :
<div class="divNumberFilter">
<div class="divLabel" style="width: 70px;">Number:</div>
<div class="divInputField">
<input id="$tags.searchStandard" type="text" style="width: 100px;">
<script src='<s:url value=""></s:url>' type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
addOnload(grouping());
addOnload(initilizeStandardAutoComplete());
</script>
</div>
<div class="clear"></div>
</div>
<!-- Standard Description filter -->
<div class="divDescriptionFilter">
<div class="divLabel" style="width: 70px;">Description:</div>
<div class="divInputField">
<input id="$tags.standardFilter" type="text" style="width: 318px;">
<script src='<s:url value=""></s:url>' type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
addOnload(grouping());
addOnload(initilizeStandardDescAutoComplete());
</script>
</div>
<div class="clear"></div>
</div>
<div id="standard_list" class="selection_property_div" style="padding-bottom: 5px;">
</div>
Please help..
Okay first of all, to convert this into a Velocity template, you must have an idea what you EXACTLY want to do. That's step 1.
Then start writing the code in a velocity template file. Figure out what part would be dynamic, i.e., would be rendered by the Velocity Template Engine., which I guess you already know.
<input id="$tags.standardFilter" type="text" style="width: 318px;">
Inserting it into database.
You would need a table structure like this.
create table if not exists Templates (
template_file_name varchar(50), --The column to store the name of templates.
html mediumblob, --The column which actually has the velocity templates.
lastmod timestamp --The column which contains the last modification information.
);
Then use the DataSourceResourceLoader and configure it (please read Velocity Docs for reference).
Make a VelocityEngine out of the configurations of the DataSourceResourceLoader.
have FUN.
--Cheers, Jay.

The loop is not working correctly

I have written this loop below. It executes perfectly fine in the first iteration; however, in the second iteration, it returns the following error:
Unable to locate element:
{"method":"xpath","selector":"html/body/header[2]/div[2]/nav/ul/li[2]/a"}`
Command duration or timeout: `120.06` seconds
The loop code is mentioned below:
Workbook w2;
w2 = Workbook.getWorkbook(new File("C:\\Users\\pcs\\Desktop\\flightdata.xls")); //flight data destintion location will be same as source from flight data.
Sheet s2 = w2.getSheet(0);
for (k = 1; k < s2.getRows(); k++)
{
//redeem flow
d1.findElementByXPath("html/body/header[2]/div[2]/nav/ul/li[2]/a").click();
d1.findElementByXPath("html/body/header[2]/div[2]/nav/ul/li[2]/ul/li[3]/a").click();
d1.findElement(By.xpath("html/body/section/div[1]/form/div/div[2]/div[1]/div/div[1]/input")).sendKeys(s2.getCell(0, k).getContents());
//pause for list to be populated
try
{
Thread.sleep(1000L);
}
catch (Exception e)
{
}
//Get all items in autocomplete list
List<WebElement> items1 = d1.findElements(By.xpath("html/body/ul/li[3]/a"));
//Look for item
for( i= 0; i <items1.size();i++)
{
if(items1.get(i).getText().contains(s2.getCell(0, k).getContents()))
{
items1.get(i).click();
break;
}
}
//calendar handling
d1.findElementById("checkin").click();
d1.findElementByXPath("html/body/div[2]/div[2]/div/a/span").click();
d1.findElementByXPath("html/body/div[2]/div[2]/table/tbody/tr[3]/td[3]/a").click();
//Select Number of Rooms
d1.findElementById("roomscount").sendKeys("1");
//Select Room type
d1.findElementById("roomtype").sendKeys("Single");
//Occupant's Nationality
d1.findElementById("nationality").sendKeys("India");
//Click search button
d1.findElementByXPath("html/body/section/div[1]/form/div/div[2]/div[4]/input").click();
//after 2 min wait
d1.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
POST SEARCH HTML PAGE
<!DOCTYPE html>
<html>
<head>
<body class="" ondrop="return false;" ondragstart="return false;" onunload="" onpageshow="if (event.persisted) noBack();" onload="noBack();">
<header>
<div class="logo">
<div class="right">
<ul class="login">
<nav class="links">
<ul>
<li>
<li>
Redeem sMiles
<ul>
<li class="pointer sprite"> </li>
<li class="flight">
<li class="hotel">
<a href="hotel.html?action=hotels">
<span class="sprite"> </span>
Hotels
</a>
</li>
<li class="smiles">
</ul>
</li>
</ul>
</nav>
<div class="clear"></div>
</div>
<div class="clear"></div>
</header>
<div class="clear"></div>
<script src="/fm/travel/js/hotel.js" type="text/javascript">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link type="text/css" rel="stylesheet" href="/fm/styles/demo_table_jui.css">
<link rel="stylesheet" href="/fm/travel/styles/ui-lightness/jquery-ui-1.10.4.css">
<link rel="stylesheet" href="/fm/travel/styles/ui-lightness/autocomplete.css">
<script src="/fm/travel/js/jquery-1.10.2.js" type="text/javascript">
<script src="/fm/travel/js/jquery-ui-1.10.4.js" type="text/javascript">
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
<script type="text/javascript">
<script type="text/javascript">
<script type="text/javascript">
<div id="loader" style="display: none;">
<div id="modifySearchBlock" style="display: block;">
<div class="clear"></div>
<footer>
<script src="/fm/travel/js/jquery.js">
<script src="/fm/js/bootstrap.min.js">
<script src="/fm/js/jquery.meanmenu.js">
<script>
<script src="/fm/js/jquery.simpleGal.js">
<script>
<script src="/fm/js/owl.carousel.js">
<script>
<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>
<ul id="ui-id-1" class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all " tabindex="0" style="display: none;"></ul>
</body>
</html>
The above code belongs to the page where I return once search is completed.
Again I need to go to the below link to do the search:
<li class="flight">
<li class="hotel">
<a href="hotel.html?action=hotels">
<span class="sprite"> </span>
Hotels
</a>
</li>
<li class="smiles">
</ul>
</li>
The above code belongs to the link which I need to click. please provide same suggestions.
First you should have a look to other selector than xpath which is unreadble and can be dangerous, here you will a lot a way to find elements. For example cssSelector is a very reliable way to find element.
Another advantage is that your code become more readable.
If I understand, the first iteration no problem, then the seconde one, this is the click on the dropdown at the top of your page that cause the crash.
A possible solution is that your page is not come back to its original state at the end of your loop. You could refresh the page at the end of the loop:
driver.navigate().refresh();
Or check in which state you are at the end of the loop.
Hope that helps.
Well, the problem which my code was facing is that when search gets finished, I was trying trying to click the web elements with the same old xpaths. Actually, on close analysis I found that the xpaths of the same webelements on the results page got altered slightly due to which my script was not able to recognize the elements on new location.
Hence, i just changed the xpaths and problem got resolved.

How to add ajax action to jsp page?

I have to add ajax action to date field. When user choose appropriate date, it should show at table all free apartment.
How to implement this at jsp page. I'm newly at JavaEE.
Here is content of page:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# page errorPage="error/errHandler.jsp" %>
<jsp:include page="/WEB-INF/jspf/header.jspf" />
<html>
<head>
<title>Reservation an apartment</title>
<h1 align="left">Reservation an apartment</h1>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/bookRoom">
<div class="reservation-group" align="left">
<label class="places-label">Couch places at room</label>
<span class="selections">
<select id="r_select">
<option>select</option>
<option>1 person</option>
<option>2 persons</option>
<option>3 persons</option>
<option>4 persons</option>
</select>
</span>
</div>
<br/><br/>
<div class="reservation-group" align="left">
<label>Star rating</label>
<select>
<option>select</option>
<option>2 stars</option>
<option>3 stars</option>
<option>4 stars</option>
<option>5 stars</option>
</select>
</div>
<br/><br/>
<div align="left">
<label>Check-in date</label>
<input type="date" placeholder="yy/mm/dd"/>
</div>
<br/><br/>
<div align="left">
<label>Check-out date</label>
<input type="date"/>
</div>
<br/><br/>
<div class="register-group" align="left">
<div class="selections">
<input type="reset" value="Reset" class="btn" />
<input type="submit" value="Register" class="btn" />
</div>
</div>
</form>
</body>
</html>
How does this ajax technologist works on jsp in general? Do we need to use javascript or jquery? If yes, how exactly will be right.
Looking of the page:
I want to understand this implementation. Any suggestions are appreciate.
Use onchange event as ,
<input type="date" placeholder="yy/mm/dd" onchange="sendAjax()" id="checkInDate" />
You jquery will be ,
<script type= "text/javascript">
$( document ).ready(function() {
});
function sendAjax() {
var checkInDate= $("#checkInDate").val();
//var checkOutDate= $("#checkOutDate").val();
$.ajax({
type: "POST",
url: "You URL path"
data: "checkInDate" + checkInDate,
dataType: "html",
success: function(response) {
//alert("Success : "+response);
if(response != null && response !="" && response !="null"){
//do you stuff here
}
},
error: function(e) {
alert('Error: ' + e.message);
},
});
}
</script>
This has nothing to do with the type of server-side view rendering technology you are using (in your case JSP), it's a question of having some JavaScript code react on a change in the date select box and then trigger a call to a server function that returns the available apartments given the entered date.
JQuery is JavaScript, it's a commonly used JavaScript framework. And yes, you could very well use it for this task. Just add an id to your date select box (for example "checkindate"):
<input id="checkindate" type="date" placeholder="yy/mm/dd"/>
and then use JQuery to attach code to the change event which calls your server with the selected date:
$(document).ready(function() {
$("#checkindate").change(function(event) {
var selectedDate = event.target.value;
$.get("/your/server/function?selectedDate=" + selectedDate, function(data) {
// populate list with data
}, "json");
});
});
Your server function will have to read the query parameter "selectedDate" and with that construct a list of available apartments in (for example) JSON format and return that to the client.
Use onChange event and and send the ajax call on onChange event.
You can use onClick,onblur() event too
<script>
function onDateChange(){
//Alert OnChange is Called
alert("Date Changed");
//Send ajax call
}
</script>

Categories