Null pointer exception on cluster.connect when using Cassandra 2.2.7 - java

I am trying to display all users usernames from a Cassandra database using an AJAX script in the jsp page.This would display a list of the users usernames when a view all button is clicked. However the Server throws a Null pointer exception on Session session = cluster.connect("");
java.lang.NullPointerException
User.searchAll(User.java:87)
Search.doGet(Search.java:82)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Model
public class User {
Cluster cluster;
public User() {
}
public java.util.LinkedList<ProfileBean> searchAll(){
Session session = cluster.connect("instagrim");
LinkedList<ProfileBean> profileBeanList = new LinkedList();
String cqlQuery = "select * from userprofiles";
PreparedStatement ps = session.prepare(cqlQuery);
ResultSet rs;
BoundStatement bs = new BoundStatement(ps);
rs = session.execute(bs.bind());
if(rs.isExhausted()){
System.out.println("Profile not found");
}
else
{
for (Row row : rs){
ProfileBean profile = new ProfileBean();
profile.setLogin(row.getString("login"));
profileBeanList.add(profile);
}
}
session.close();
return profileBeanList;
}
Servlet
public class Search extends HttpServlet {
Cluster cluster = null;
public void init(ServletConfig config)
{
cluster = CassandraHosts.getCluster();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User us = new User();
String output ="";
LinkedList<ProfileBean> profileBeanList = new LinkedList();
profileBeanList = us.searchAll();
for (int i=0;i<profileBeanList.size();i++)
{
output="<p>"+profileBeanList.get(i).getLogin() +"</p>";
}
response.getWriter().write(output);
RequestDispatcher rd = request.getRequestDispatcher("search.jsp");
rd.forward(request,response);
}

cluster is null, therefore it does not have a connect method. The system lets you know about the situation with the error message.
The solution is to make sure that cluster is properly initialized before you try to connect.

Related

Hbase client reading different user for read and write

I am using hbase client 2.1.7 to connect to my server(same version 2.1.7).
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.1.7</version>
Now there is an user who have permission to read/write on the table in the server.
User = LTzm#yA$U
For this my code looks like this:
String hadoop_user_key = "HADOOP_USER_NAME";
String user = "LTzm#yA$U";
System.setProperty(hadoop_user_key, token);
Now when I am trying to read the key from the table i am getting following error:
error.log:! Causing:
org.apache.hadoop.hbase.security.AccessDeniedException:
org.apache.hadoop.hbase.security.AccessDeniedException: Insufficient
permissions for user 'LTzm' (table=table_name, action=READ)
Weird part is writes are working fine. To validate that whether right user is getting passed for write, i removed the user and try rerun the code and the write fails with the error:
error.log:! org.apache.hadoop.hbase.ipc.RemoteWithExtrasException:
org.apache.hadoop.hbase.security.AccessDeniedException: Insufficient
permissions (user=LTzm#yA$U,
scope=table_name, family=d:visitId,
params=[table=table_name,family=d:visitId],action=WRITE)
Again read was also failing with:
error.log:! org.apache.hadoop.hbase.ipc.RemoteWithExtrasException:
org.apache.hadoop.hbase.security.AccessDeniedException: Insufficient
permissions for user 'LTzm'
(table=table_name, action=READ)
Somehow Ltzm is getting passed with read call and LTzm#yA$U is getting passed for write.
Does anyone help me what is the issue here, Is # or special symbol not allowed in the user for hbase(then how is it working for write calls).
Edit 1:
Here is the function to create connection:
public static Connection createConnection() {
String hadoop_user_key = "HADOOP_USER_NAME";
String user = "LTzm#yA$U";
Map<String, String> configMap = new HashMap<>();
configMap.put("hbase.rootdir", "hdfs://session/apps/hbase/data"));
configMap.put("hbase.zookeeper.quorum", "ip1, ip2");
configMap.put("zookeeper.znode.parent", "/hbase");
configMap.put("hbase.rpc.timeout", "400");
configMap.put("hbase.rpc.shortoperation.timeout", "400");
configMap.put("hbase.client.meta.operation.timeout", "5000");
configMap.put("hbase.rpc.engine", "org.apache.hadoop.hbase.ipc.SecureRpcEngine");
configMap.put("hbase.client.retries.number", "3");
configMap.put("hbase.client.operation.timeout", "3000"));
configMap.put(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, "30"));
configMap.put("hbase.client.pause", "50"));
configMap.put("hbase.client.pause.cqtbe", "1000"));
configMap.put("hbase.client.max.total.tasks", "500"));
configMap.put("hbase.client.max.perserver.tasks", "50"));
configMap.put("hbase.client.max.perregion.tasks", "10"));
configMap.put("hbase.client.ipc.pool.type", "RoundRobinPool");
configMap.put("hbase.rpc.read.timeout", "200"));
configMap.put("hbase.rpc.write.timeout", "200"));
configMap.put("hbase.client.write.buffer", "20971520"));
System.setProperty(hadoop_user_key, token);
Configuration hConfig = HBaseConfiguration.create();
for (String key : configMap.keySet())
hConfig.set(key, configMap.get(key));
UserGroupInformation.setConfiguration(hConfig);
Connection hbaseConnection;
hbaseConnection = ConnectionFactory.createConnection(config);
return connection;
}
Here are the read and write calls:
protected Result read(String tableName, String rowKey) throws IOException {
Get get = new Get(Bytes.toBytes(rowKey));
get.addFamily(COLUMN_FAMILY_BYTES);
Result res;
Table hTable = null;
try {
hTable = getHbaseTable(tableName);
res = hTable.get(get);
} finally {
if (hTable != null) {
releaseHbaseTable(hTable);
}
}
return res;
}
protected void writeRow(String tableName, String rowKey, Map<String, byte[]> columnData) throws IOException {
Put cellPut = new Put(Bytes.toBytes(rowKey));
for (String qualifier : columnData.keySet()) {
cellPut.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes(qualifier), columnData.get(qualifier));
}
Table hTable = null;
try {
hTable = getHbaseTable(tableName);
if (hTable != null) {
hTable.put(cellPut);
}
} finally {
if (hTable != null) {
releaseHbaseTable(hTable);
}
}
}
private Table getTable(String tableName) {
try {
Table table = hbaseConnection.getTable(TableName.valueOf(tableName));
} catch (IOException e) {
LOGGER.error("Exception while adding table in factory.", e);
}
}

ERROR java.lang.NoClassDefFoundError: com/mongodb/MongoClient

so i got a very strange error message. Im currently working on a java web project with maven and testing the project with Eclipse and Tomcat. So I imported all the neccessary dependencys (mongo java driver, mongodb driver, mongodb driver core, bson and javax.servlet api), or so i thought. But still i'm getting this error over and over again.
If I run the code as part of a main method it works just fine...so im in the dark what could have caused this problem.
this is my MongoDB connector,
public class Connector {
final String HOST = "localhost";
final int PORT = 27017;
final String DBNAME = "mitfahrapp";
public static Connector instance;
public MongoClient connection;
public MongoDatabase database;
public Connector(){
this.connection = new MongoClient(this.HOST, this.PORT);
this.database = connection.getDatabase(DBNAME);
}
public MongoClient getClient() {
return connection;
}
public static Connector createInstance() throws UnknownHostException {
if (Connector.instance == null) {
Connector.instance = new Connector();
}
return Connector.instance;
}
public MongoCollection<Document> getCollection(String name) {
return this.database.getCollection(name);
}
public void CloseMongo() {
connection.close();
}
}
and this is part of my LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connector c = Connector.createInstance();
MongoCollection<Document> collection = c.getCollection("users");
String username = request.getParameter("username");
String password = request.getParameter("password");
Bson filterUsername = Filters.eq("username", username);
Bson filterPwd = Filters.eq("password", password);
Bson bsonFilter = Filters.and(filterUsername, filterPwd);
FindIterable<Document> doc = collection.find(bsonFilter);
if (doc != null) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
Thanks for any answers in advance!
This means that the classes are not included in the jar, if you are using maven you should use the maven shade plugin to include those.

Session with Value Null Java/Neo4J

Hello i´m having problems in Java Null Pointer Exception in Session
This is my code:
public Configs(String uri, String username, String password)
{
Driver driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password) );
}
.....
public Boolean existMachine(){
machine mach = new machine();
try (Session session = driver.session())
{
}
}
And i call the Function in main(String[] args):
Configs connections = new Configs("bolt://localhost:7474", "neo4j", "");
if(connections.existMachine().booleanValue() == false)
{
...
}
else{
..
}
I´m getting error in:
try (Session session = driver.session())
You don't set drivers as an instance field of your class.
You have to make it available in existMachine

Start embeded Neo4j from servlet

I have created companies nodes from mysql database using this code
public class EnterCompaniesToNeo4j {
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
ConnectionStrings c=new ConnectionStrings();
String CONN_STRING=c.getConnString();
String USERNAME=c.getUsername();
String PASSWORD=c.getPassword();
Connection conn=null;
PreparedStatement stmt=null;
int counter=0;
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1");
Transaction tx = graphDB.beginTx();
Node n = null;
try
{
stmt=conn.prepareStatement("select * from companies where node_id IS NULL", ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// stmt.setString(1, "100641318");
rs=stmt.executeQuery();
while(rs.next())
{
// deo gde se kreira nod
counter=counter+1;
n = graphDB.createNode();
n.setProperty( "taxnumber", rs.getString("tax_number"));
n.setProperty( "name", rs.getString("name"));
n.setProperty( "email", rs.getString("email"));
long br;
br=n.getId();
rs.updateLong("node_id",br);
rs.updateRow();
//System.out.println(n.getProperty("taxnumber"));
//System.out.println(n.getId()+"");
System.out.println(rs.getString("name"));
}
tx.success();
}
catch ( Exception e )
{
tx.failure();
}
finally
{
tx.finish();
stmt.close();
rs.close();
conn.close();
}
//ExecutionEngine engine = new ExecutionEngine( graphDB );
//ExecutionResult result = engine.execute( "start n=node(2) return n, n.taxnumber,n.name" );//vracanje noda 1
//ExecutionResult result = engine.execute( "START n = node(*) DELETE n" ); //brisanje svih nodova
//System.out.println(result.toString());
System.out.println(""+counter);
graphDB.shutdown();
}
}
Now I want to enable users to insert relationships after they are logged in , I do it from servlet like this
public class InputDebtDataToNeo4j extends HttpServlet {
GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1");
Transaction tx = graphDB.beginTx();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList<InputData> l111 = new ArrayList<InputData>();
ArrayList<InputData> l222 = new ArrayList<InputData>();
HttpSession session=request.getSession(true);
l111= (ArrayList<InputData>) session.getAttribute("hasdata");
l222=(ArrayList<InputData>) session.getAttribute("hasnotdata");
//put ka Neo4j bazi
long mynodenumber;
mynodenumber = Long.parseLong(session.getAttribute("node_id").toString());
try {
for (InputData element : l111)
{
ExecutionEngine engine = new ExecutionEngine( graphDB );
ExecutionResult result = engine.execute( "START a=node("+mynodenumber+"), b=node("+element.getNodeidnumber()+") CREATE a-[r:OWE{amount:"+element.getDebtamount()+"}]->b RETURN r" );//vracanje noda 1
out.println("Relacija "+result.toString()+"</br>");
out.println("Taks broj "+element.getTaxnumberdata()+"</br>");
out.println("Node Broj "+element.getNodeidnumber()+"</br>");
out.println("Iznos duga "+String.valueOf(element.getDebtamount())+"</br>");
out.println("Moj node broj "+mynodenumber+"</br>");
}
//response.sendRedirect("DebtSolutions.jsp");
tx.success();
}
catch(Exception e )
{
tx.failure();
out.println(e.toString());
}
finally {
tx.finish();
graphDB.shutdown();
out.close();
}
}
And for a result I get this error message
type Exception report
message Error instantiating servlet class servlets.InputDebtDataToNeo4j
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class servlets.InputDebtDataToNeo4j
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
root cause
java.lang.IllegalStateException: Database locked.
org.neo4j.kernel.InternalAbstractGraphDatabase.create(InternalAbstractGraphDatabase.java:289)
org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:227)
org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:79)
org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:70)
org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:205)
org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:56)
servlets.InputDebtDataToNeo4j.<init>(InputDebtDataToNeo4j.java:30)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:525)
java.lang.Class.newInstance0(Class.java:372)
java.lang.Class.newInstance(Class.java:325)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
What should I do in my servlet to make it work ...
You would want to have the graph database as a singleton.
So either you declare your GraphDatabaseService static in your servlet (remember there is a new servlet instance created per request (or at least as many as there are threads/pooled).
Or you have it injected, or you store it in the Application-Context. Or use a ServletContextListener that creates the graph database on startup and shuts it down correctly at shutdown.

Unable to set the value for running the java file

I'm working in Google gcm application,and here I'm authenticating the app user by correct Id & password.Authentication is working properly.
My I'm running this page by Run as -> Run on Server(Homeservlet.java),even for the correct employee and password,it's not showing the written jsp code(which is written in the if condition) and going to the else-part.
In the eclipse console : I can see the employee name and it's password.But my question is how to set the values sothat when I will run this page it'll show that jsp page inside.
I'm using set parameter to set the value,but whenever I'm running this page in Tomcat server,it's showing IllegalArgumentException.I found it's quiet relevant because when I'm running the value's are not set.
Actually I want ,for the correct employee and corresponding password,...it'll show that jsp page; otherwise(i mean in else-part,it'll not)
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
private static final int HTTP_STATUS = 200;
// private static final String HTTP = "OK";
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException {
PreparedStatement stmt = null;
String employee=req.getParameter("employeeid"); //getting the value from app User
String password=req.getParameter("password"); //corresponding password
req.setAttribute(employee, employee);
req.setAttribute(password, password);
try {
String url="jdbc:mysql://localhost/apps";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url,"root","root");
stmt = con.prepareStatement("select * from regid where emp_id=? and password=?");
stmt.setString(1, employee);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
System.out.println("2> Employee Id : "+employee+" && Password : "+password);
System.out.println("3> This employee "+employee+" exsists in the database and will be there");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html>"); //1> want to run this portion from here
out.print("<head>");
out.print("<title>Policy Page</title>");
out.print("<link rel='icon' href='../images/favicon.png'/>");
out.print("</head>");
out.print("<body>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null)
{
out.print("Status : "+status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty())
{
out.print("<h2>No devices registered!</h2>");
}
else
{
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='text' name='policy'>");
resp.setStatus(HttpServletResponse.SC_OK);
out.print("<input type='submit' value='Apply Policy'>");
out.print("</form>");
// getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
out.print("</body></html>"); //2> to here
resp.setStatus(HttpServletResponse.SC_OK);
}
else { //else-part
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
System.out.println(HttpServletResponse.SC_BAD_REQUEST);
System.out.println("4> This employee "+employee+" does not exsist in the database");
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
} catch(Exception x) {}
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
When the app user giving the id-password,the output in the console is:
2> Employee Id : P1 && Password : ppp
3> This employee P1 exsists in the database and will be there
but I'm running the page(run as->run on server-tomcat-6),it is showing this(instead of showing the jsp page)
HTTP Status 500
java.lang.IllegalArgumentException: Cannot call setAttribute with a null name
at org.apache.catalina.connector.Request.setAttribute(Request.java:1431)
at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:50
any idea....... where I'm going wrong.
2 things observed.
1)
Use
req.setParameter("employee", employee);
req.setParameter("password", password);
instead
req.setAttribute(employee, employee);
req.setAttribute(password, password);
2)
The next page you are showing is not a JSP. It is plain html created in servlet.
The set content type is html.
If you want to display employee in html,
you can write code like this,
out.print("<body>");
out.print("Welcome to this site Mr."+ employee);
If you still want to use the employee as a variable on that html, you have to embed Javascript in this page.

Categories