Java Bean not working as expected - java

OK, I have a JSP running the following script section.
<% irCollection mgrq = new irCollection();
mgrq.setMgrid("Chris Novish");
mgrq.populateCollection();
int pagenum;
if (request.getParameter("p") != null) {
String pagedatum=request.getParameter("p");
pagenum = Integer.parseInt(pagedatum);
} else { pagenum = 0; }
for (int i=0;i<10;i++) {
int rownum = pagenum * 10 + i;
InquireRecord currec = mgrq.getCurRecords(rownum);
out.println(currec.getID()); %>
irCollection has an ArrayList property that stores a several InquireRecord objects. It gets this data from a database using the mgrid as (set in line 2 there) as the matching term.
But I'm getting an IndexOutOfBounds exception on what appears here as line 11.
I've done some tests, and I'm pretty sure that it's because populateCollection() isn't getting things done. I have a getSize method that gives me a size of 0.
I made a test class in Eclipse to make sure all my methods were working:
package com.serco.inquire;
public class test {
public static void main (String[] args) {
String mgr = "Chris Novish";
irCollection bob = new irCollection();
bob.setMgrid(mgr);
bob.populateCollection();
InquireRecord fred = bob.getCurRecords(1);
System.out.println(fred.getID());
}
}
That test class produces exactly what I'd expect.
Other than the names of some of the local variables, I can't see what I'm doign different in the JSP.
So... tell me, what noobish mistake did I make?
for the sake of being thorough, here's the populateCollection() method:
public void populateCollection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "inquire.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute ("SELECT * FROM inquiries WHERE manager = '" + mgrid + "'");
ResultSet rs = s.getResultSet();
int cur;
if (rs != null) {
while (rs.next()) {
cur = rs.getRow();
cur -- ;
int curID = rs.getInt("ID");
this.newIR.setID(curID);
String cursub = rs.getString("submitter");
this.newIR.setSubmitter(cursub);
this.iRecords.add(cur, this.newIR);
}
this.size = iRecords.size();
this.pages = this.size / 10;
int remain = this.size % 10;
if (remain > 0) { this.pages++; }
} else { System.out.println("no records."); }
}
catch (Throwable e) {
System.out.println(e);
}
}

Your IndexOutOfBounds exception is probably being caused by the value of rownum being passed to mgrq.getCurRecords().
Your test code proves nothing because there you're calling getCurRecords() with a constant which is probably always valid for your system and will never cause the exception.
My suggestion is to step through the code in your JSP with a debugger, or even simply to print out the value of your variables (especially pagedatum, pagenum and rownum) in your JSP code.

Is your JSP Snippet correct? It looks like you started the braces for the
for (int i=0;i<10;i++) {
but I dont see a end braces for that at all. Can you check if that is the case and if so, fix the code appropriately?

Related

how to update multiple records with jdbc with oracle and spring boot

I am trying to update several records from spring jdbc but this is not working what am i doing wrong?
does not respond when I make a request, but the data in the array is arriving, try without array and the same thing happens.
I am sending an array of objects to be able to update but I get to the method cstmt.executeQuery(); it does not execute and it waits and does not go any further.
#PostMapping(path = "/updateEstadoPlanesServicios", produces = MediaType.APPLICATION_JSON)
public String updateEstadoPlanesServicios(#RequestBody String lista) {
ServiciosPlanesUpdateDTO[] fromJson = gson.fromJson(lista, ServiciosPlanesUpdateDTO[].class);
return gson.toJson(consultaPlanesComisionPortal.estadoPlanesServicios(fromJson));
}
#Transactional(rollbackFor = { Exception.class })
public replyDTO estadoPlanesServicios(ServiciosPlanesUpdateDTO[] list) {
System.out.println("data: "+list.toString());
replyDTO re = new replyDTO();
int count = 0;
try {
StringBuilder update = new StringBuilder();
update.append("UPDATE Detalleproductoservicio ");
update.append(" SET loginregistro = ?, estado = 'D', fechasys = sysdate ");
update.append(" WHERE codigo_Servicio = ? and codigo_planproductoservicio = ? and NIT = ?");
try (Connection conexion = obtenerConexion.obtenerConexion(0);
PreparedStatement cstmt = conexion.prepareStatement(update.toString())) {
conexion.setAutoCommit(false);
for(ServiciosPlanesUpdateDTO elements: list) {
//System.out.println(elements.toString());
System.out.println("1 element:"+elements.getLoginRegistro());
System.out.println("2 element:"+elements.getCodigoServicio());
System.out.println("3 element:"+elements.getCodigoPlanProductoServicio());
System.out.println("4 element:"+elements.getNit());
cstmt.setString(1, elements.getLoginRegistro().trim());
cstmt.setInt(2,Integer.parseInt( elements.getCodigoServicio().trim()));
cstmt.setString(3, elements.getCodigoPlanProductoServicio().trim());
cstmt.setString(4, elements.getNit().trim());
count = cstmt.executeUpdate();
//cstmt.execute();
//count++;
//cstmt.addBatch();
//cstmt.executeBatch();
//
}
conexion.commit();
if(count > 0) {
re.setMessage("Status ok,"
+"count: "+count);
re.setExitoso(true);
}else {
re.setExitoso(false);
re.setMessage("failed");
}
}
} catch (Exception e ) {
re.setExitoso(false);
re.setMessage(e.getMessage());
}
return re;
}
this is working I found the problem apparently the database conflicts when I have Oracle SQL Developer open and I make the request by postman this is a little weird but I closed Oracle Developer and it worked.

Dynamic Variable Initialization Error in Java

I have this piece of code which is giving an error saying
variable priorityCheck is not initialized
The output that I require is that the query executes with the given value of priorityCheck in a loop. Here is the code:
String query;
String StrComp;
int PerFound;
Statement stmt = null;
ResultSet rs = null;
String priorityCheck;
// running the queries
for (int i = 0; i < names.size(); i++) {
StrComp = types.get(i).toString();
PerFound = StrComp.indexOf("%");
if (StrComp.indexOf("P1") != -1) {
priorityCheck =
"a.SubscriptionType=0 and a.applyticketpriorityfilterflag = 1 and a.P1 & a.P2 = 1";
} else if (StrComp.indexOf("P2") != -1) {
priorityCheck =
"a.SubscriptionType=0 and a.applyticketpriorityfilterflag = 1 and a.P3 & a.P4 = 1";
} else if (StrComp.indexOf("WO") != -1) {
priorityCheck = "a.SubscriptionType=2";
}
if (PerFound == -1) {
query =
"SELECT DATEDIFF(minute,a.LastStatusDate,GETUTCDATE()) FROM SASubscriptionPIIView a,SAWorkflowToolPIIView b WHERE (a.toolid=b.id and a.active=1 and a.SubscriptionCategory=0 and "
+ priorityCheck
+ " and b.toolname like "
+ types.get(i)
+ ")";
writeLog(query);
} else {
query =
"SELECT DATEDIFF(minute,a.LastStatusDate,GETUTCDATE()) FROM SASubscriptionPIIView a,SAWorkflowToolPIIView b WHERE (a.toolid=b.id and a.active=1 and a.SubscriptionCategory=0 and "
+ priorityCheck
+ " and b.toolname like "
+ types.get(i)
+ ")";
writeLog(query);
}
}
This error basically means: you are using (reading!) a variable in your code, but there are paths in your code that do not initialize your variable.
Simplified:
String foo;
if (whatever) {
foo = "from if";
}
bar = foo;
That is what your code is doing: it contains a way to reach a "read" for priorityCheck without a previous "write" to that variable. One simple fix:
String foo = "not initialized";
In other words: think what the variable should contain as "default". Or make sure that there are no paths without assigning a value.
Beyond that: your real problem is that you are writing overly complicated code. If you really intend to write "database code" at this point; consider reading a bit about "clean coding practices"; for example the Single Layer of Abstraction principle. Your problem is that you are writing code that is so complex that you can't see any more what the code is doing.
Please initialize variable priorityCheck with some default value - "", for example.
The problem is that in code
if (StrComp.indexOf("P1")!=-1)
{
priorityCheck="a.SubscriptionType=0 and a.applyticketpriorityfilterflag = 1 and a.P1 & a.P2 = 1";
}
else if (StrComp.indexOf("P2")!=-1)
{
priorityCheck="a.SubscriptionType=0 and a.applyticketpriorityfilterflag = 1 and a.P3 & a.P4 = 1";
}
else if (StrComp.indexOf("WO")!=-1)
{
priorityCheck="a.SubscriptionType=2";
}
variable priorityCheck can be not initialized - else statement is missing.

Database insertion synchronization

I have a java code that generates a request number based on the data received from database, and then updates the database for newly generated
synchronized (this.getClass()) {
counter++;
System.out.println(counter);
System.out.println("start " + System.identityHashCode(this));
certRequest
.setRequestNbr(generateRequestNumber(certInsuranceRequestAddRq
.getAccountInfo().getAccountNumberId()));
System.out.println("outside funcvtion"+certRequest.getRequestNbr());
reqId = Utils.getUniqueId();
certRequest.setRequestId(reqId);
System.out.println(reqId);
ItemIdInfo itemIdInfo = new ItemIdInfo();
itemIdInfo.setInsurerId(certRequest.getRequestId());
certRequest.setItemIdInfo(itemIdInfo);
dao.insert(certRequest);
addAccountRel();
counter++;
System.out.println(counter);
System.out.println("end");
}
the output for System.out.println() statements is `
1
start 27907101
com.csc.exceed.certificate.domain.CertRequest#a042cb
inside function request number66
outside funcvtion66
AF88172D-C8B0-4DCD-9AC6-12296EF8728D
2
end
3
start 21695531
com.csc.exceed.certificate.domain.CertRequest#f98690
inside function request number66
outside funcvtion66
F3200106-6033-4AEC-8DC3-B23FCD3CA380
4
end
In my case I get a call from two threads for this code.
If you observe both the threads run independently. However the data for request number is same in both the cases.
is it possible that before the database updation for first thread completes the second thread starts execution.
`
the code for generateRequestNumber() is as follows:
public String generateRequestNumber(String accNumber) throws Exception {
String requestNumber = null;
if (accNumber != null) {
String SQL_QUERY = "select CERTREQUEST.requestNbr from CertRequest as CERTREQUEST, "
+ "CertActObjRel as certActObjRel where certActObjRel.certificateObjkeyId=CERTREQUEST.requestId "
+ " and certActObjRel.certObjTypeCd=:certObjTypeCd "
+ " and certActObjRel.certAccountId=:accNumber ";
String[] parameterNames = { "certObjTypeCd", "accNumber" };
Object[] parameterVaues = new Object[] {
Constants.REQUEST_RELATION_CODE, accNumber };
List<?> resultSet = dao.executeNamedQuery(SQL_QUERY,
parameterNames, parameterVaues);
// List<?> resultSet = dao.retrieveTableData(SQL_QUERY);
if (resultSet != null && resultSet.size() > 0) {
requestNumber = (String) resultSet.get(0);
}
int maxRequestNumber = -1;
if (requestNumber != null && requestNumber.length() > 0) {
maxRequestNumber = maxValue(resultSet.toArray());
requestNumber = Integer.toString(maxRequestNumber + 1);
} else {
requestNumber = Integer.toString(1);
}
System.out.println("inside function request number"+requestNumber);
return requestNumber;
}
return null;
}
Databases allow multiple simultaneous connections, so unless you write your code properly you can mess up the data.
Since you only seem to require a unique growing integer, you can easily generate one safely inside the database with for example a sequence (if supported by the database). Databases not supporting sequences usually provide some other way (such as auto increment columns in MySQL).

compare two arrayList and stock the result in a thirth arrayList

i want compare 2 arrayList when i stock in them the result of a class java of telnet
this class it's to telnet about a router and gives all of interfaces of this routers then stock them in the arrayList
so i stock the interfaces for the router1 in myData1 and the second in myData2
and i will compare if the interface of the first aray it's the same in the second just add one of them in the array of result myData
but it gives me anthing the code
public class Test {
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
String sql = "SELECT * FROM router;";
Telnet_Interface telnet = new Telnet_Interface();
Telnet_Interface telnet1 = new Telnet_Interface();
Telnet_Interface telnet2 = new Telnet_Interface();
PreparedStatement prest = conn.prepareStatement(sql);
ResultSet res=prest.executeQuery();
while(res.next()){
telnet1.Config(res.getString(1), "user", "passwd", res.getString(1));
telnet2.Config(res.getString(2), "user", "passwd", res.getString(2));
}
ArrayList myData=new ArrayList();
ArrayList myData1=telnet1.getMyData();
ArrayList myData2=telnet2.getMyData();
boolean bool=false;
for(int i=0;i<myData1.size();i++)
{
for(int j=0;j<myData2.size();j++)
{
if (myData2.get(j).equals(myData1.get(i)))
{
bool=true;
//System.out.print("sdfsd");
}
if(!bool)
{
myData.add(myData2.get(j));
//System.out.print("sdsd");
}
}
}
for(int x=0;x<myData.size();x++)
{
System.out.print(myData.get(x));
}
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
what's the problem ??
thank you
You can just use ArrayList.retainAll method like this
list1.retainAll(list2)
after this method list1 will containt only the data which are available in list2.
(Not an answer) Separate all. Use logging and handle the exceptions.
If it is not a kind of dictionary attack, first do the SQL retrieving users with passwords.
Close result set, statement and connection.
Check the results.
Then get the telnet data.
Check the results.
Then do the comparison.
I hope you can see the deleted answer of #StinePike; he basically proposes list1.retainAll(list2) to remove all element in list1 that occur in list2.
I think you want to do the following. Outcommented is non-looping alternative.
// Add all myData2 and myData1 elements but not twice to myData.
// (1) Add myData2
myData.addAll(myData2);
// (2) Add myData1 when not in myData2
//myData1.removeAll(myData1);
//myData.addAll(myData1);
for (int i = 0; i < myData1.size(); i++)
{
boolean found = false;
for (int j = 0; j < myData2.size(); j++)
{
if (myData2.get(j).equals(myData1.get(i)))
{
found = true;
break;
}
}
if (!found)
{
myData.add(myData1.get(i));
}
}

I am getting error 500 and null pointer exception

I am making project on online examination in java.
I am facing a problem.
On starting base I have 15 questions in my database and I am fetching those sequentially.
The problem is that if I attempt all the answers I get the results otherwise I get error 500 and NullPointerException. The questions are multiple choice. Every question has four options. If I don't attempt all the questions then I get the above error.
<%#page import="java.sql.*"%>
<%
String st[] = new String[20];
String ans[] = new String[20];
int k=0;
//int length = Integer.parseInt(request.getAttribute("length").toString());
for (int i = 0; i < 15; i++)
{
int j = i + 1;
st[i] = request.getParameter("radio" + j);
System.out.println(st[i]);
}
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "root", "root");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("Select ANS from ANSWERS order by ID");
//String ans = "";
int t;
while (rs.next()) {
ans[k] = rs.getString("ans");
k++;
System.out.println(ans[k]);
}
int count = 0;
//String answers[] = ans.split(" ");
for (int i = 0; i < 15; i++) {
if (st[i].equals(ans[i])) {
count++;
}
}
out.println("Your " + count + " answers are correct");
%>
At the start of your code you're initializing your st[] with request.getParameter("radio" + j); This might come as null. As per the javadoc for getParameter():
Returns the value of a request parameter as a String, or null if the
parameter does not exist.
So when you try to execute this following piece of code:
for (int i = 0; i < 15; i++) {
if (st[i].equals(ans[i])) {
count++;
}
}
There is a chance that st[i] is in fact null. This might possibly be a reason for the NullPointerException in your code
You should be enclosing your logic in try catch and in finally handle the SQL exception for connection, rs (in separate try catch blocks)
Also, try lloking at the stack trace, as to which line gives the null pointer exception
I would say that your answers are simply not submitted back with your request. If the radio group for a question does not have a selected value, that radio group is not going to be part of the POST request that you are processing after the form submission.
That is why you get the Null pointer exception in the first place.
I cannot runt your example above, but i assume that the error is happening in the comparison line at the end of your example:
if (st[i].equals(ans[i])) {
Update
For a quick fix, just switch the evaluated values: st[i].equals(ans[i]) to ans[i].equals(st[i]). That way you can always do a equals against null and get the correct count.

Categories

Resources