table created using jquery is not accessible from servlet - java

Based on the help availed from stackoverflow I created the table with hiddenfields to pass the value to servlet, but in servlet I am unable to get the values of the input fields.
Here is my jQuery code to create table:
$("#linkInstr").click(function() {
var arr = new Array();
var cdid = $("#cboinstr option:selected");
var code = $("#cbocode option:selected");
$.get("trnDC?caseNo=21&insid="+cdid.text(), function(data) {
arr = data.split(",");
var contents = '<tr><td><input type="checkbox" id="chk_select'+counter+'" /></td><td><input type="hidden" id="txtCodeid'+counter+'" value="'+code.text()+'"/> ' + code.text()+ '</td><td><input type="hidden" id="txtInstrid'+counter+'" value="'+cdid.text()+'"/>' + cdid.text() + '</td><td>' + arr[0] + '</td><td>' + arr[1] + '</td><td>' + arr[2] + '</td></tr>';
alert(contents);
$("#tblDetails").append(contents);
counter++;
})
})
And here is my Servlet code:
int noOfRows = Integer.parseInt(request.getParameter("noOfRows"));
for (int i = 0; i < noOfRows; i++) {
int j = i + 1;
String codeid = request.getParameter("txtCodeid" + i);
throw new Exception(request.getParameter("txtCodeid" + i));
String instrId = request.getParameter("txtInstrid"+i);
st.executeUpdate("insert into trndcdtls values(" +ccode +"," +fyear_code +"," +Dcno +"," + j +",'" + codeid +"','" + instrId + "','"+status+"')");
}
The exception is throwed purposefully by myself to check any value is availble on request, but it shows nothing.

You need to give the input fields a name. This becomes the request parameter name.
Thus, instead of
<input id="foo">
<input id="bar">
you need
<input name="foo">
<input name="bar">
The ID is purely to identify the elements at the client side, not at the server side. You may add them, but they won't be sent to the server side. Only the name-value pairs of an input element will be sent as request parameters to the server side.
That said, please use PreparedStatement in your Java code to avoid SQL injection risks. Further on, it surprises me that you got the Java code compiled with the Exception in the middle of the flow. It would have given "unreachable code" error.

Related

Randomly changing the JSON Values for every "Post" Request Body using Java

This could be a duplicate question, but I couldn't find my solution anywhere. Hence, posting it.
I am trying to simply POST a request for a Student account Creation Scenario. I do have a JSON file which comprises all the "Keys:Values", required for Student account creation.
This is how the file student_Profile.json looks like:
{
"FirstName":"APi1-Stud-FN",
"MiddleInitial":"Q",
"LastName":"APi1-Stud-LN",
"UserAlternateEmail":"",
"SecretQuestionId":12,
"SecretQuestionAnswer":"Scot",
"UserName":"APi1-stud#xyz.com",
"VerifyUserName":"APi1-stud#xyz.com",
"Password":"A123456",
"VerifyPassword":"A123456",
"YKey":"123xyz",
"YId":6,
"Status":false,
"KeyCode":"",
"SsoUserName":"APi1-stud#xyz.com",
"SsoPassword":"",
"BirthYear":2001
}
So everything on Posting the request from "Rest Assured" point of view looks fine, it's just that I want to update a few values from the above JSON body using JAVA so that I can create a new Student profile every time I run my function and don't have to manually change the Body.
For Every POST Student Account Creation scenario, I need to update the value for
the following keys so that a new test student user account can be created:
First Name
Last Name and
Username // "VerifyUserName" and "SSO UserName" will remain same as user name
I modified the answer to get random values and pass them to json body. random value generation was taken from the accepted answer of this question.
public void testMethod() {
List<String> randomValueList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
randomValueList.add(salt.toString());
}
String jsonBody = "{\n" +
" \"FirstName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"UserAlternateEmail\":\"\",\n" +
" \"SecretQuestionId\":12,\n" +
" \"SecretQuestionAnswer\":\"Scot\",\n" +
" \"UserName\":\"" + randomValueList.remove(0) + " \",\n" +
" \"VerifyUserName\":\"APi1-stud#xyz.com\",\n" +
" \"Password\":\"A123456\",\n" +
" \"VerifyPassword\":\"A123456\",\n" +
" \"YKey\":\"123xyz\",\n" +
" \"YId\":6,\n" +
" \"Status\":false,\n" +
" \"KeyCode\":\"\",\n" +
" \"SsoUserName\":\"APi1-stud#xyz.com\",\n" +
" \"SsoPassword\":\"\",\n" +
" \"BirthYear\":2001\n" +
"}";
Response response = RestAssured
.given()
.body(jsonBody)
.when()
.post("api_url")
.then()
.extract()
.response();
// Do what you need to do with the response body
}
We can used pojo based approach to do certain things very easily . No matter how complex is the payload , serialization and dieselization is the best answer . I have created a framework template for api automation that can we used by putting required POJO's in path :
https://github.com/tanuj-vishnoi/pojo_api_automation
To create pojo, I also have ready to eat food for you :
https://github.com/tanuj-vishnoi/pojo_generator_using_jsonschema2pojo
for the above problem you can refer to the JsonPath lib https://github.com/json-path/JsonPath and use this code:
String mypayload = "{\n" +
" \"FirstName\":\"APi1-Stud-FN\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"APi1-Stud-LN\"}";
Map map = JsonPath.parse(mypayload).read("$",Map.class);
System.out.println(list);
once the payload converted into map you can change only required values as per the requirement
To generate random strings you can refer to lib org.apache.commons.lang3.RandomStringUtils;
public static String generateUniqueString(int lenghtOfString){
return
RandomStringUtils.randomAlphabetic(lenghtOfString).toLowerCase();
}
I recommend to store payload in a separate file and load it at runtime.

How to get selected value from json list on java

I've list from db and put in json list with checkbox and the value. I need the value for insert to table db. So, how to get value from the selected checkbox in java? Thanks a lot.
In JSP File
function refreshList() {
var collection = "";
collection = collection
+ " <table><thead><th class='LIST'><span><label>Selection</span></label></th><th class='LIST'><span><label>List</span></label></th></thead><tbody>";
var isnew = $("input:radio[name=isnew ]:checked").val();
var string = "";
$.getJSON('${pageContext.request.contextPath}/master.do?reqcode=refreshList', {
'isnew ' : isnew
}, function(result) {
$.each(result,function(key,value) {
string = string + "<tr><td> "
+ "<input id='id' type='checkbox' value=" + key + "/></td>" + "<td> " + value
+ "</td></tr>";
});
collection = collection + string + " </tbody></table> ";
$('#collectionid').html(collection);
});
}
<div id="collectionid"></div>
You need to have a name attribute on the checkbox.
<input name="chkBox" type="checkbox" value="xxx" />
You can get the checkbox value from servlet request object as shown below:
String[] values = request.getParameterValues("chkBox");

How to generate dynamic table in a java class from a list

I am working in a application where i have to make an html table in the java class and have to save that in database.I am creating that table in java but the how to generate dynamic row in that table .Using 3 lists.I am giving what i have done,
+"Interview LineUp"
+" <table border ='1'>"
+"<tr>"
+"<td>Interviewe</td>"
+"<td>Timing1</td>"
+"<td>Timing2</td> "
+"</tr> "
+"<tr>"
+"<td>name</td>"
+"<td>timing1</td> "
+"<td>timing2</td> "
+"</tr> "
+"</table>"
So this is the table i am using in the java class,and i have 3 lists which contains 3 set of information like name,timing1,timing2.Now i want that if there are 3 values in all the lists then 3 rows will be generating.
The lists are
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
List<String> listOfinterviewerName = Arrays.asList(intervierwName.split(","));
Like i am doing this
+"<tr>";
for(int k=0;k<listOfinterviewerName .size();k++){
+"<td>listOfinterviewerName .get(k)</td>"
+}
How to do that,in that java class ?? somebody please help .Thanks in advance
+"test" is not a valid Java statement. What are you adding the text to?
When building a String incrementally, you should always use a StringBuilder.
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
List<String> listOfinterviewerName = Arrays.asList(intervierwName.split(","));
StringBuilder buf = new StringBuilder();
buf.append("<html>" +
"<body>" +
"<table>" +
"<tr>" +
"<th>Interviewe</th>" +
"<th>Timing1</th>" +
"<th>Timing2</th>" +
"</tr>");
for (int i = 0; i < listOfinterviewerName.size(); i++) {
buf.append("<tr><td>")
.append(listOfinterviewerName.get(i))
.append("</td><td>")
.append(interviewTimingToFrom1.get(i))
.append("</td><td>")
.append(interviewTimingToFrom2.get(i))
.append("</td></tr>");
}
buf.append("</table>" +
"</body>" +
"</html>");
String html = buf.toString();
Of course, to guard against Cross-site scripting (XSS) attacks, you should escape the values.
I was not so clear about your question, but as per what I understood, the code below will work for you.
public static void main(String[] args) {
String s = ""+"Interview LineUp"
+" <table border ='1'>"
+"<tr>"
+"<td>Interviewe</td>"
+"<td>Timing1</td>"
+"<td>Timing2</td> "
+"</tr> "
;
String interviewTime1="11:30,12:30";
String interviewTime2="13:30,15:00";
String intervierwName="Adam,Smith";
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
List<String> listOfinterviewerName = Arrays.asList(intervierwName.split(","));
for(int i=0;i<interviewTimingToFrom1.size();i++)
{
s = s.concat( "<tr>"
+"<td>"+listOfinterviewerName.get(i)+"</td>"
+"<td>"+interviewTimingToFrom1.get(i)+"</td> "
+"<td>"+interviewTimingToFrom2.get(i)+"</td> "
+"</tr> ");
}
s=s.concat( "</table>");
System.out.println(s);
}

How to extract data from certain facebook pages for a specified date range(from and to)?

I am stuck up in this date range query. I need to extract data from particular facebook pages for a specified date range.I am able to do this individually, by using since and until fields. But how to use these two fields together.
Here is my code:
public static String getFacebookPostes(Facebook facebook, String searchPost)
throws FacebookException {
String searchResult = "Item : " + searchPost + "\n";
StringBuffer searchMessage = new StringBuffer();
ResponseList<Post> results = facebook.searchPosts(searchPost, new Reading().since("2014-04-02"));
String userId="";
for (Post post : results) {
System.out.println(post.getMessage());
searchMessage.append(post.getMessage() + "\n");
for (int j = 0; j < post.getComments().size(); j++) {
searchMessage.append(post.getComments().get(j).getFrom()
.getName()
+ ", ");
searchMessage.append(post.getComments().get(j).getMessage()
+ ", ");
searchMessage.append(post.getComments().get(j).getCreatedTime()
+ ", ");
searchMessage.append(post.getComments().get(j).getLikeCount()
+ "\n");
userId=post.getComments().get(j).getFrom().getId();
User user = facebook.getUser(userId);
//System.out.println("ROCK");
System.out.println(user);
}
}
Any guidance is appreciated. Thanks in advance.
PS : I am using facebook4j-core-2.0.2.jar and eclipse kepler.
According to http://facebook4j.org/en/code-examples.html you can use all date formats descirbed in http://www.php.net/manual/en/datetime.formats.date.php
From my understanding the code would then look like this:
ResponseList<Post> results = facebook.searchPosts(searchPost, new Reading().since("2014/04/02").until("2014/04/08"));

After extracting data from html using a for loop, how do I insert one by one into a database?

I have extracted multiple data from an HTML using Jsoup and now I am trying to insert one by one into a derby db using JDBC on netbeans.
Here is my code:
public String nameOf() {
String nameStr = null;
String nameResults = "";
for(int j=100;j<=110;j++) {
refNum = j;
//System.out.println("Reference Number: " + refNum);
try {
//crawl and parse HTML from definition and causes page
Document docDandC = Jsoup.connect("http://www.abcd.edu/encylopedia/article/000" + refNum + ".htm").get();
// scrape name data
Elements name = docDandC.select("title");
nameStr = name.get(0).text();
//System.out.println(nameStr);
nameResults += nameStr + " ";
} catch (Exception e) {
//System.out.println("Reference number " + refNum + " does not exist.");
}
}
return nameResults;
So this method takes the names of diseases from 10 different HTMLs. What I am trying to do is to insert one name at a time to a derby db that I have created using JDBC. I have everything set up and all I have left to do is to insert each name in the corresponding name field of a table named DISEASE (which has fields: id, name, etc).
nameResults += nameStr + " ";
This part worries me as well since some diseases can have multiple words. Maybe I should use a list of some sort?
Please help! Thanks in advance.
Something like:
public List<String> nameOf() {
...
List<String> nameResults = new ArrayList<String>();
...
nameResults.add(nameStr);
...
return nameResults;

Categories