getResource() nullPointerException - java

I am trying to get the contents of a local JSON file in Java. Instead I am getting the following stacktrace:
java.lang.NullPointerException
fi.avaliaho.ottoautomaatitv2.Webservice.doGet(Webservice.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:352)
org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:171)
I already made sure that the file coordinates.json is located in the same directory as the Webservice.java file. I am aware of this question, but the answers do not solve my problem. Here is my servlet:
import java.net.URL;
import java.io.*;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Webservice extends HttpServlet {
URL path = null;
Reader file = null;
BufferedReader input = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
path = Webservice.class.getResource("coordinates.json");
file = new FileReader(path.getFile());
}
}

Try to use getSystemResource() method
path = ClassLoader.getSystemResource("coordinates.json")
or how it was mentioned by #LaksithaRanasingha in comments add / in the begining:
path = Webservice.class.getResource("/coordinates.json");
Also this might be useful Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

Related

The type com.mongodb.WriteConcern cannot be resolved. It is indirectly referenced from required .class files. How do I fix this error?

I have included mongodb-driver-3.0.2.jar and bson-4.1.0.jar in my application build path in Eclipse. After writing a simple code of inserting some documents in mongoDB database and executing it, I get this error:
The type com.mongodb.WriteConcern cannot be resolved. It is indirectly referenced from required .class files
This is my code:
package abhishek; //<--- The error shows in this line
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
#WebServlet("/Mongo_details")
public class Mongo_details extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String email="";
String age="";
Cookie[] cookie=request.getCookies();
for(Cookie c: cookie) {
if(c.getName().equals("name"))
name=c.getValue();
else if(c.getName().equals("email"))
email=c.getValue();
else
age=c.getValue();
}
// creates database
MongoClient ml=new MongoClient("localhost",27017);
DB db=ml.getDB("Storage");
// creates table
DBCollection c=db.getCollection("Details");
// insert documents
BasicDBObject doc=new BasicDBObject();
doc.put("Name", name);
doc.put("Email", email);
doc.put("Age", age);
c.insert(doc);
}
}
Please help me fix this.
EDIT: Ok I found a fix, I removed the mongodb-driver-3.0.2.jar from my build path and added mongo-java-driver-2.10.1. But now its showing a new error in console:
Caused by: java.lang.ClassNotFoundException: com.mongodb.DBObject
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1365)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1188)
... 40 more
But I have that class in my com.mongodb package
How do I fix this?

How to Call a class within same package and same directory in java?

Basically I have:
package duck.reg.pack;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
DBConnect DB = new DBConnect();
}
}
Class to call At Test.java:
package duck.reg.pack;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DBConnect {
private Connection con;
private Statement st;
public DBConnect(){
System.out.println("Hi there!");
return;
}
}
Both File Directory Location:
C:\classes\duck\reg\pack\Test.java + DBConnect.java
The problem is that when I compile the program with command:
C:\classes\duck\reg\pack>javac -cp "C:\Users\Unknown\JavaEEWorkspace\lib\*" Test.java
This error is thrown:
Test.java:16: error: cannot find symbol
DBConnect connect = new DBConnect();
I googled a little and I found I could remove the .java Extension from Test while compiling it and I did so But Then I got this error:
error: Class names, 'Test', are only accepted if annotation processing is explicitly requested
1 error
All replies are much appreciated :)
You need to run the compiler from the top package (which is at the root of the tree on the filesystem). So cd to
cd C:\classes
And run
javac -cp "C:\Users\Unknown\JavaEEWorkspace\lib\*" duck\reg\pack\*.java
We need to use the -cp (or -classpath) option to specify the base directory of the package com.yyy, in order to locate DBConnect.
javac -cp "d:\lib\*" d:\myJavaProject\pkg\*.java
write at the top
import duck.reg.pack.DBConnect;
in the class that you want to import it.
Why don't you use IntelliJ it will do it for you ?

How get current country name in java?

I want to get current country name in java . I use this code.
private HttpServletRequest request;
Locale currentCountry = request.getLocale();
System.out.println(currentCountry.getDisplayCountry());
But it through an NullPointerException like Caused by: java.lang.NullPointerException. at 2nd line. Please Help me anyone.
The snippet of code is not enough to tell why you got the Null Pointer. I assume you are use servlet on server side.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HttpServletBean;
public class MyServlet extends HttpServletBean {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Locale userlocale = request.getLocale();
out.println("Your Country : " + userlocale.getCountry());
out.println();
out.println("");
}
}

display an image from a blob field using servlet

i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)

Easy way to write servlet that returns table data in xml format

Easy way to write servlet that returns table data in xml format - ?
Data comes from a database table.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TableServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/xml");
PrintWriter writer = response.getWriter();
writer.println("<?xml version=\"1.0\"?>");
writer.println("<table>");
writer.println("<style>");
writer.println("<finish>polished</finish>");
writer.println("<material>oak</material>");
writer.println("</style>");
writer.println("<legs>4</legs>");
writer.println("</table>");
writer.flush();
}
}
You may found jersey useful it works for XML, also supports JSON . Here is a good tutorial (Look section 4) .

Categories

Resources