Null Pointer exception on Indexed Container Vaadin - java

I am using the FilterTable addon of vaadin.
I am getting a NullPointerException on the following code, but unable to find the reason of this.
cont = new IndexedContainer()
cont.addContainerProperty("Patient", String.class, null);
cont.addContainerProperty("Date Of Service", String.class,null);
cont.addContainerProperty("Provider", String.class, null);
Session session = HibernateUtil.getSessionFactory().openSession();
Iterator<?> iterator = session.createQuery("FROM ConvertVisitToBillingV WHERE ready_for_billing = '0'").list().iterator();
while(iterator.hasNext()){
ConvertVisitToBillingV var = (ConvertVisitToBillingV) iterator.next();
Visits v = (Visits) session.load(Visits.class, var.getVisitId());
Appointments app = (Appointments)session.load(Appointments.class, v.getAppointmentId());
t_id= var.getVisitId();
cont.addItem(t_id);
Resources res = (Resources)session.load(Resources.class, v.getReferredBy());
cont.getContainerProperty(t_id, "Patient").setValue(var.getFirstName() + " " + var.getLastName());
cont.getContainerProperty(t_id, "Date Of Service").setValue(new SimpleDateFormat("MM/dd/yyyy").format(v.getVisitDt()));
cont.getContainerProperty(t_id, "Provider").setValue(res.getResourceFirstName()+" "+res.getResourceLastName());
}
When it executes the line "cont.getContainerProperty(t_id,property).setValue()
It occasionally throws NullPointerException. Not getting the reason behind it.
What can be the reason behind this , any help!
Thanks!

Without more details I would say either :
v.getVisitDt() is null for some `v``
session.load(Resources.class, v.getReferredBy()); returns null for some v and so res is null.
This will probably fix the problem:
cont.getContainerProperty(t_id, "Patient").setValue(var.getFirstName() + " " + var.getLastName());
if(v.getVisitDt()!=null){
cont.getContainerProperty(t_id, "Date Of Service").setValue(new SimpleDateFormat("MM/dd/yyyy").format(v.getVisitDt()));
} else {
cont.getContainerProperty(t_id, "Date Of Service").setValue("?");
}
if(res!=null){
cont.getContainerProperty(t_id, "Provider").setValue(res.getResourceFirstName()+" "+res.getResourceLastName());
else{
cont.getContainerProperty(t_id, "Provider").setValue("?");
}

Related

Transactions from ArangoDB java driver fails to change anything in the database

I am trying to send a transaction through the Java driver in my spring application.
The following is the simplified code.
#Test
public void rawTransactionTest(){
var appContext = new AnnotationConfigApplicationContext(DataLoaderApplication.class);
var arangoOperations = appContext.getBean(ArangoOperations.class);
String action = "function(){\n" +
" db = require(\"#arangodb\").db; \n" +
"db._query(\"LET doc = {title: \\\"Hello\\\"} "+
"UPSERT { _key: doc._key } INSERT doc._key == null ? UNSET(doc, \\\"_key\\\") : doc " +
"REPLACE doc IN Books OPTIONS { ignoreRevs: false } RETURN NEW\");\n" +
"return \"Success\"; \n" +
"}";
System.out.println(action);
var tOpts = new TransactionOptions();
tOpts.writeCollections("Books");
tOpts.waitForSync(true);
var result = arangoOperations.driver().db().transaction(action, String.class, tOpts);
System.out.println("Commit");
}
This returns the return value "Success" in the variable result. But the database remains unchanged. Doing the same thing in ArangoShell works perfectly fine. The ArangoShell code is as follows -
db._executeTransaction({
collections: {
write: ["Books"]
},
action: function(){
db = require("#arangodb").db;
db._query("LET doc = {title: \"Hello\"} UPSERT { _key: doc._key } "+
"INSERT doc._key == null ? UNSET(doc, \"_key\") : doc REPLACE doc"+
" IN Books OPTIONS { ignoreRevs: false } RETURN NEW");
return "Success";
}
});
This code works fine from the shell. Other non-transaction queries work fine from he same Spring-container.
What might be the problem?
The .db() only points to the _system database. Had to pass the database name to fix it.

cursor is crashing with CursorIndexOutOfBoundsException

My cursor is crashing my application with the android database error.
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I made another much less optimized slider that scans my database and I find the good value.
public Cursor getAllDataTableStaffDatabase(String table_name){
this.open();
Cursor result =this.mDb.rawQuery("SELECT * FROM " + table_name,null);
return result;// fonctionne très bien
}
public String findNameOfStaffBymail(String mail) {
String sql = " SELECT * FROM " + DatabaseStaffHandler.STAFF_TABLE_NAME + " WHERE " + DatabaseStaffHandler.STAFF_MAIL + " = ? ";
Cursor result = super.mDb.rawQuery(sql, new String[]{mail});
Cursor data = super.getAllDataTableStaffDatabase(DatabaseStaffHandler.STAFF_TABLE_NAME);
String test = result.getString(1); //error
while (data.moveToNext()) {
if (data.getString(3).equals(mail)) {
viewAll();
return data.getString(1);
}
}
}
I would like to retrieve the value name that corresponds to the email address.
This usually happens when you do not have the data in your Cursor and you are still trying to access the data. It is similar to the ArrayIndexOutOfBoundsException. I found nothing wrong with your query so far. However, I think you might consider adding null checking in your code which will prevent your application from crashing. Especially in the while loop, you need to put a null check in the condition.
And you need to use the moveToFirst function wherever necessary.
public Cursor getAllDataTableStaffDatabase(String table_name) {
this.open();
Cursor result = this.mDb.rawQuery("SELECT * FROM " + table_name,null);
return result;
}
public String findNameOfStaffBymail(String mail) {
String sql = " SELECT * FROM " + DatabaseStaffHandler.STAFF_TABLE_NAME + " WHERE " + DatabaseStaffHandler.STAFF_MAIL + " = ? ";
Cursor result = super.mDb.rawQuery(sql, new String[]{mail});
Cursor data = super.getAllDataTableStaffDatabase(DatabaseStaffHandler.STAFF_TABLE_NAME);
// Add a null checking here.
if (result != null) {
result.moveToFirst();
String test = result.getString(1);
}
if(data != null) data.moveToFirst();
while (data != null) {
if (data.getString(3).equals(mail)) {
viewAll();
return data.getString(1);
}
data.moveToNext();
}
}
Hope that solves your problem.
Thank you for your reply. I found my problem thanks to you. I wonder if the cursor does not boot at the end. But it is good practice to check if received is not null. Thank you and have a nice day

Getting a null-point exception in Neo4j data retrieval

I have the following code.
GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
GraphDatabaseService db= dbFactory.newEmbeddedDatabase("C:/Users/shadid/Documents/Neo4j/DB");
ExecutionEngine execEngine = new ExecutionEngine(db, null);
ExecutionResult execResult = execEngine.execute("MATCH (mat:TheMatrix) RETURN mat");
String results = execResult.dumpToString();
System.out.println(results);
I am getting a null point exception. I have tried running the command in the neo4j command line. So the data do exist. I am not quite sure where is the error. Quite a noob in neo4j so could someone please help me out
Here's the error I am getting by the way
Exception in thread "main" java.lang.NullPointerException
at org.neo4j.cypher.internal.CypherCompiler.(CypherCompiler.scala:69)
at org.neo4j.cypher.ExecutionEngine.createCompiler(ExecutionEngine.scala:237)
at org.neo4j.cypher.ExecutionEngine.(ExecutionEngine.scala:64)
at App.Main.main(Main.java:53)
Just found a more intuitive way of doing the same thing and it works yay!!!
try ( Transaction ignored = db.beginTx();
Result result = db.execute( "MATCH (n:TheIronGiant) RETURN n.`title: `" ) )
{
String rows ="";
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
System.out.println(rows);
}
You are using the ExecutionEngine constructor that takes a LogProvider as the second parameter, but passing a null value for it. If you called the single-parameter constructor instead, which does not take a LogProvider, you may not get the exception.
Also, ExecutionEngine class is now deprecated, and you should use GraphDatabaseService.execute() instead.

How to remove deadlocks in orientdb

I am getting too many deadlocks on OrientDb while I am using Java API to query the vertices. After the deadlock happens, the entire database becomes unresponsive and I have to kill the daemon and start again. As example, the error that I get from deadlocks is :
com.orientechnologies.common.concur.OTimeoutException: Can not lock record for 2000 ms. seems record is deadlocked by other record
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.acquireReadLock(OAbstractPaginatedStorage.java:1300)
at com.orientechnologies.orient.core.tx.OTransactionAbstract.lockRecord(OTransactionAbstract.java:120)
at com.orientechnologies.orient.core.id.ORecordId.lock(ORecordId.java:282)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.lockRecord(OAbstractPaginatedStorage.java:1776)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.readRecord(OAbstractPaginatedStorage.java:1416)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.readRecord(OAbstractPaginatedStorage.java:694)
at com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.executeReadRecord(ODatabaseDocumentTx.java:1569)
at com.orientechnologies.orient.core.tx.OTransactionNoTx.loadRecord(OTransactionNoTx.java:80)
at com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.load(ODatabaseDocumentTx.java:1434)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.readRecord(ONetworkProtocolBinary.java:1456)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:346)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:216)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:65)
Following is the block that I use to query edges and create associations between vertices
public User generateFriend(String mobile, String userRID) {
StringBuilder errorMsg = new StringBuilder();
Iterable<OrientVertex> vertexes;
//Retrieve friends of the user
List<User> friendsList = new ArrayList<User>();
vertexes = db.queryVertices("select expand( unionAll(inE('E_Friend').out,outE('E_Friend').in) ) from " + userRID,errorMsg);
if (!errorMsg.toString().equals("")) {
throw new DbException("Db exception occured, " + errorMsg);
}
for (OrientVertex v : vertexes){
friendsList.add(vertexToUser(v));
}
//Create edges if between the user and other users with mobile number in the list and if the edge is not yet created
User u = findUserByMobileNo(friendsList,mobile);
if ( u == null){
u = findByMobileNo(mobile);
if (u != null) {
//create edge
db.executeQuery("select createEdge('E_Friend','" + userRID + "','" + u.getRid() + "') from " + userRID, new HashMap<String, Object>(), errorMsg);
if (!errorMsg.toString().equals("")) {
throw new DbException("Db exception occured, " + errorMsg);
}
}
}
return u;
}
public Iterable<OrientVertex> queryVertices(String query, StringBuilder errMsg){
logger.error("before getGraph, " + errMsg.toString());
graph = getGraph(errMsg);
if (!errMsg.toString().equals("")){
return null;
}
logger.error("after getGraph, " + errMsg.toString());
Iterable<OrientVertex> vertices = null;
try {
OSQLSynchQuery<OrientVertex> qr = new OSQLSynchQuery<OrientVertex>(query);
vertices = graph.command(qr).execute();
logger.error("after graph command execute, " + errMsg.toString());
}
catch (Exception ex){
errMsg.append(ex.getMessage());
logger.error("graph command exception, " + errMsg.toString());
}
logger.error("before return vertices, " + errMsg.toString());
return vertices;
}
public List<ODocument> executeQuery(String sql, HashMap<String,Object> params,StringBuilder errMsg) {
List<ODocument> result = new ArrayList<ODocument>();
try {
db = getDatabase(errMsg);
if (!errMsg.toString().equals("")){
return null;
}
OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql);
if (params.isEmpty()) {
result = db.command(query).execute();
} else {
result = db.command(query).execute(params);
}
} catch (Exception e) {
errMsg.append(e.getMessage());
//TODO: Add threaded error log saving mechanism
}
return result;
}
Due to index missing on table deadlock come, so check your all table which are involved in this operation and find out that indexes are present or not on column.
Refer link in which I have a same problem of deadlock.

calling a java class in a servlet

in my servlet i called an instance of a class.java( a class that construct an html table) in order to create this table in my jsp.
the servlet is like the following:
String report=request.getParameter("selrep");
String datev=request.getParameter("datepicker");
String op=request.getParameter("operator");
String batch =request.getParameter("selbatch");
System.out.println("report kind was:"+report);
System.out.println("date was:"+datev);
System.out.println("operator:"+op);
System.out.println("batch:"+batch);
if(report.equalsIgnoreCase("Report Denied"))
{
DeniedReportDisplay rd = new DeniedReportDisplay();
rd.ConstruireReport();
}
else if(report.equalsIgnoreCase("Report Locked"))
{
LockedReportDisplay rl = new LockedReportDisplay();
rl.ConstruireReport();
}
request.getRequestDispatcher("EspaceValidation.jsp").forward(request, response);
in my jsp i can not display this table even empty or full.
note: exemple a class that construct denied Report has this structure:
/*constructeur*/
public DeniedReportDisplay() {}
/*Methodes*/
#SuppressWarnings("unchecked")
public StringBuffer ConstruireReport()
{
StringBuffer retour=new StringBuffer();
int i = 0;
retour.append("<table border = 1 width=900 id=sheet align=left>");
retour.append("<tr bgcolor=#0099FF>" );
retour.append("<label> Denied Report</label>");
retour.append("</tr>");
retour.append("<tr>");
String[] nomCols ={"Nom","Prenom","trackingDate","activity","projectcode","WAName","taskCode","timeSpent","PercentTaskComplete","Comment"};
//String HQL_QUERY = null;
for(i=0;i< nomCols.length;i++)
{
retour.append(("<td bgcolor=#0066CC>")+ nomCols[i] + "</td>");
}
retour.append("</tr>");
retour.append("<tr>");
try {
s= HibernateUtil.currentSession();
tx=s.beginTransaction();
Query query = s.createQuery("select opcemployees.Nom,opcemployees.Prenom,dailytimesheet.TrackingDate,dailytimesheet.Activity," +
"dailytimesheet.ProjectCode,dailytimesheet.WAName,dailytimesheet.TaskCode," +
"dailytimesheet.TimeSpent,dailytimesheet.PercentTaskComplete from Opcemployees opcemployees,Dailytimesheet dailytimesheet " +
"where opcemployees.Matricule=dailytimesheet.Matricule and dailytimesheet.Etat=3 " +
"group by opcemployees.Nom,opcemployees.Prenom" );
for(Iterator it=query.iterate();it.hasNext();)
{
if(it.hasNext()){
Object[] row = (Object[]) it.next();
retour.append("<td>" +row [0]+ "</td>");//Nom
retour.append("<td>" + row [1] + "</td>");//Prenom
retour.append("<td>" + row [2] + "</td>");//trackingdate
retour.append("<td>" + row [3]+ "</td>");//activity
retour.append("<td>" + row [4] +"</td>");//projectcode
retour.append("<td>" + row [5]+ "</td>");//waname
retour.append("<td>" + row [6] + "</td>");//taskcode
retour.append("<td>" + row [7] + "</td>");//timespent
retour.append("<td>" + row [8] + "</td>");//perecnttaskcomplete
retour.append("<td><input type=text /></td>");//case de commentaire
}
retour.append("</tr>");
}
//terminer la table.
retour.append ("</table>");
tx.commit();
} catch (HibernateException e)
{
retour.append ("</table><H1>ERREUR:</H1>" +e.getMessage());
e.printStackTrace();
}
return retour;
}
thanks for help.
1) The instances of DeniedReportDisplay and LockedReportDisplay are created locally, no way to refer them once outside the if..else block.
2) The method invoked ( rd.ConstruireReport() ) returns a StringBuffer and you should store it somewhere. Try to use Response.getWriter() and put all the response string into this writer.
3) Suggest you to find some good tutorial books about how to design Servlets/JSP, the solution you tried to build is quite wried.
The problem is that you are not doing anything with the return value from ConstruireReport(), so it just get's lost. You should set it as a request attribute so your JSP can find the string.
EDIT: Suggestion to use getWriter() on the servlet removed - misunderstood scenario.

Categories