This question already has answers here:
How to use java.net.URLConnection to fire and handle HTTP requests
(12 answers)
Making http calls from swing application to a servlet, session not saved
(1 answer)
Closed 1 year ago.
Server-side I have an HttpSession object. Each time the client starts the connection to the Servlet, the session changes.
Here I have a simplified version of my Servlet code:
//import ...
#WebServlet(name = "ServletController", urlPatterns = {"/ServletController"})
public class ServletController extends HttpServlet {
public void init(ServletConfig conf) {
//...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
try {
String action = request.getParameter("action");
switch (action) {
case "login":
s.setAttribute("account", "John");
out.println("Logged in successfully. Session: " + s);
out.flush();
break;
case "account":
String account = (String) s.getAttribute("account");
out.println(account + ". Session: " + s);
out.flush();
break;
default:
break;
}
} catch (Exception x) {
System.out.println(x);
}
}
}
And here the simplified Android one:
//import ...
public class Operation {
public static Executor e = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
Button login_btn = findViewById(R.id.login);
Button account_btn = findViewById(R.id.account);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String login = Operation.operation("?action=login");
});
}
});
account_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String account = Operation.operation("?action=account");
});
}
});
System.out.println(login);
System.out.println(account);
}
public static String operation(String urlParameters) {
HttpURLConnection conn = null;
try {
System.out.println(urlParameters);
URL url = new URL("http://10.0.2.2:8080/progettoTweb/ServletController" + urlParameters);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000);
conn.setConnectTimeout(1500);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
return readIt(conn.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
//building the output as a String
private static String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
}
}
As the System.out.println in the Android app show, I obtain a different session for each Operation.operation call I make.
In the original code I use SharedPreferences in order to save my data, but it does not solve the problem since I do not know how to use the session, gained from the interaction with the server-side, to obtain the required values.
Indeed, in the Servlet code I use s.getAttribute() but, since it creates a new HttpSession object each time, It cannot give back the requested values.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a problem. Please take a look at these codes. When I click to login button first time it throws null pointer exception even I am typing correct username and password. But second time everything goes fine. How can I solve this issue?
I have attached OracleDBConnection and Login servlet. Null pointer exception happens in OracleDBConnection file.
Thanks for reading.
OracleDBConnection.java
public class OracleDBConnection {
private static volatile OracleDataSource instance = null;
private static final DBPropertyController DB_PROPERTY = new DBPropertyController();
private static final String URL = DB_PROPERTY.getProperty("url");
private static final String USERNAME = DB_PROPERTY.getProperty("username");
private static final String PASSWORD = DB_PROPERTY.getProperty("password");
private static final String PORT = DB_PROPERTY.getProperty("port");
private OracleDBConnection(){
}
private static void initialize() {
try {
instance = new OracleDataSource();
instance.setURL(URL);
instance.setUser(USERNAME);
instance.setPassword(PASSWORD);
instance.setPortNumber(Integer.parseInt(PORT));
} catch (SQLException ex) {
Logger.getLogger(OracleDBConnection.class.getName()).log(Level.ERROR, ex);
}
}
public static OracleDataSource getInstance() {
OracleDataSource ods = OracleDBConnection.instance;
if(ods == null) {
synchronized(OracleDataSource.class){
ods = OracleDBConnection.instance;
if(ods == null) {
initialize();
}
}
}
return ods;
}
}
Login.java
#WebServlet(name = "Login", urlPatterns = {"/login"})
public class Login extends HttpServlet {
private final LogController logger = new LogController();
private final JWTController jwt_controller = new JWTController();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
LoginController login_controller = new LoginController();
HttpSession session = request.getSession(true);
String username = request.getParameter("username");
String password = request.getParameter("password");
int role = 0;
try {
role = Integer.parseInt(request.getParameter("userrole"));
} catch(NumberFormatException ex) {
Logger.getLogger(Login.class.getName()).log(Level.ERROR, null, ex);
role=0;
}
if(username!=null && password!=null && !username.equals("") && !password.equals("") && isRoleValid(role)){
if(login_controller.validateLogin(username, password, role)) {
// get manager object
Manager manager = login_controller.getManager(username, password, role);
long currentEpochTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
// set manager object to session
session.setAttribute("manager", manager);
//generate token
String token = jwt_controller.generateToken(username, MD5.generate(password), role);
// set token to cookie
Cookie cookie = new Cookie("token", token);
// add cookie to response
response.addCookie(cookie);
// check password expire date
if(manager.getPaswd_edate() > currentEpochTime) {
// signed in
response.getWriter().write("Signed in");
} else {
// expired
response.getWriter().write("Expired");
}
// add log
logger.addLog(username, "Signed in.", request.getRemoteHost(), request.getHeader("user-agent"));
} else {
response.getWriter().write("Error");
}
} else {
response.getWriter().write("Error");
}
}
private boolean isRoleValid(int role) {
return role==0 || role==1 || role==2 || role==3;
}
}
You haven't mentioned where is your NPE, but I guess it is because your OracleDBConnection.getInstance() returns null object first time it is called.
Change your lines
synchronized(OracleDataSource.class){
ods = OracleDBConnection.instance;
if(ods == null) {
initialize();
}
}
to
synchronized(OracleDataSource.class){
if(ods == null) {
initialize();
}
ods = OracleDBConnection.instance;
}
When I'm calling doPost directly, it shows me profile page in correct way. But then after login I open new tab in Chrome copy url "http://localhost:8080/17_servlets_jsp/profile" there and it shows me blank page
#WebServlet("/profile")
public class Profile extends HttpServlet {
**private String login;**
private HttpSession httpSession;
private User user;
private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
**if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
} else {
login = (String) httpSession.getAttribute("uLogin");
doPost(req, resp);
}**
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
**login = req.getParameter("login");
user = new ImplUserDAO().findByLogin(login);**
httpSession = req.getSession();
resp.setContentType("text/html");
try (PrintWriter out = resp.getWriter()) {
out.println("<title>Profile page</title>");
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", true);
httpSession.setAttribute("uLogin",req.getParameter("login"));
httpSession.setAttribute("uPass",req.getParameter("pass"));
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}
By calling doPost() you also execute this line:
user = new ImplUserDAO().findByLogin(req.getParameter("login"));
Which will throw an Exception or return null or whatever because your GET request didn't include that parameter. If you want to reuse doPost() you'd need to fetch login from either session or request:
String login = req.getParameter("login");
if(null == login) {
login = (String)httpSession.getAttribute("uLogin");
}
Or similar.
On Attributes and Parameters
In your commented out code, you tried to solve this issue by calling setAttribute("login"... on your request. While this is legal, you can not retrieve that value by calling getParameter(). Instead you'd have to call 'getAttribute()` again - which doesn't make much difference to retrieving directly from the session:
//Retrieve Parameter (been send into the servlet from outside)
String login = req.getParameter("login");
if(null == login) {
//Retrieve Attribute you put into the request in doGet()
login = (String)req.getAttribute("login");
}
Another Edit
You have the same issue with req.getParameter("pass").
You should seriously consider splitting login-process (checking username/password from request) from other functionality (display profile page) or reverse your logic: Do login, set user into session in doPost() and if successful call goGet()?
Full Example Code
Consider these changes to somewhat fix your logic:
#WebServlet("/profile")
public class Profile extends HttpServlet {
// Don't use member variables on Servlets - they get reused for all users!
// private String login;
// private HttpSession httpSession;
// private User user;
// private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
}
else {
User user = httpSession.getAttribute("userLoggedIn");
Role role = httpSession.getAttribute("userRole");
out.println("<title>Profile page</title>");
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if("true".equals(httpSession.getAttribute("isAdmin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
User user = new ImplUserDAO().findByLogin(login);
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
Role role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", user);
httpSession.setAttribute("userRole", role);
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
}
// Now refer to display part.
goGet(req, resp);
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}
I've implemented a asynchronous Servlet, which needs to parse the body of request and store the parsed result in cache. Should I implement the parseBody() function in Servlet or implement a new class, which will do the parsing? What is the best practice?
Here is my current code snippet:
public class DocFeedServlet extends FeedServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(DocFeedServlet.class);
private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final AsyncContext asyncContext = req.startAsync();
asyncContext.start(new Runnable() {
#Override
public void run() {
String bodyStr = getBody(req);
if (bodyStr.isEmpty()) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
asyncContext.complete();
return;
}
int ignoreTime = Integer.parseInt(req.getParameter(Constant.PARAM_IGNORE_TIME));
List<MockDocCacheKeyVal> mockDocCacheKeyVals = new ArrayList<>();
List<String> docUpdateFields = new ArrayList<>();
List<List<String>> docKeepFields = new ArrayList<List<String>>();
List<String> uuidsToRemove = new ArrayList<>();
int parseRet = parseBody(bodyStr, mockDocCacheKeyVals, docUpdateFields, docKeepFields, uuidsToRemove, ignoreTime);
if (parseRet != 0) {
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
asyncContext.complete();
}
});
}
protected int parseBody(String body, List<MockDocCacheKeyVal> mockDocCacheKeyVals, List<String> docUpdateFields, List<List<String>> docKeepFields, List<String> uuidsToRemove, int ignoreTime) {
try {
ObjectReader reader = OBJECTMAPPER.reader(new TypeReference<List<Document>>() { });
List<Document> documents = reader.readValue(body);
for (Document doc : documents) {
if (doc.getAction() != null && doc.getAction().equalsIgnoreCase(Constant.DOC_FEED_ACTION_DELETE)) {
if (doc.getUuid() != null) {
uuidsToRemove.add(doc.getUuid());
}
continue;
}
if (doc.getA() != null) {
} else if (doc.getB() != null) {
} else {
DocumentUtils.pruneWeightSet(doc.getC(), cPruneSize);
DocumentUtils.pruneWeightSet(doc.getD(), dPruneSize);
DocumentUtils.pruneWeightSet(doc.getE(), ePruneSize);
}
}
return documents.size();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return 0;
}
}
Thanks.
Asynchronous Request Body read is accomplished with the HttpServletRequest.getInputStream().setReadListener(ReadListener) concepts introduced in Servlet 3.1
You will only read based on events from your ReadListener, and you will only read enough to not block. (so no reading multi-megabyte buffers!).
This API is what you are looking for, however there be land mines here, so be sure you fully understand the API before you finish it.
I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}
I need to retrieve images from my database. For this I used jquery and servlet to retrieve all images stored in a table. But when i run the code it produces HTTP Status 500 - class oracle.jdbc.driver.OracleBlobInputStream declares multiple JSON fields named maxPosition I'm a newbie in Jquery I don't know how to use JSON for images.
My Servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname;// = request.getParameter("countryCode");
uname="shyam";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
ArrayList<ImageFileInfo> imageInfo = getInfo(uname);
ImageFileInfo info = new ImageFileInfo();
JsonElement imageObj = gson.toJsonTree(imageInfo);
boolean nonNullElemExist= false;
for (ImageFileInfo s: imageInfo) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
if(nonNullElemExist==true){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("imageInfo", imageObj);
out.println(myObj.toString());
out.close();
}
private ArrayList<ImageFileInfo> getInfo(String uname) {
ArrayList<ImageFileInfo> imageFileList = new ArrayList<ImageFileInfo>();
Connection conn = null;
PreparedStatement stmt = null;
try {
conn=prepareConnection();
StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("image");
String sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
ImageFileInfo info = new ImageFileInfo();
info.setName(rs.getString("imagename").trim());
info.setDisc(rs.getString("imagedisc").trim());
info.setImageid(rs.getInt("imageid"));
info.setalbumid(rs.getInt("albumid"));
byte imageData[] = rs.getBytes("imagethumb");
String encoded = DatatypeConverter.printBase64Binary(imageData);
info.setThumb(encoded);
byte image1Data[] = rs.getBytes("imagethumb");
String encoded1 = DatatypeConverter.printBase64Binary(image1Data);
info.setFull(encoded1);
}
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
catch(Exception e){ System.out.println( "Error --> " + displayErrorForWeb(e));;}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
conn = null;
}
}
return imageFileList;
}
And The ImageFileInfo.java file is:
package skypark;
import java.io.InputStream;
public class ImageFileInfo
{
String name = null;
String disc = null;
int imageid=0;
int albumid=0;
InputStream thumbarray;
InputStream fullarray;
public void setName(String name)
{
this.name = name;
}
public String getName() {
return name;
}
public void setDisc(String disc)
{
this.disc = disc;
}
public void setImageid(int Imageid)
{
this.imageid = Imageid;
}
public void setalbumid(int albumid)
{
this.albumid = albumid;
}
public void setThumb(InputStream inputStream)
{
this.thumbarray = inputStream;
}
public void setFull(InputStream binaryStream) {
this.fullarray = binaryStream;
}
}
And Stack trace is:
java.lang.IllegalArgumentException: class oracle.jdbc.driver.OracleBlobInputStream declares multiple JSON fields named maxPosition
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:122)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
com.google.gson.Gson.getAdapter(Gson.java:353)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:55)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.Gson.toJson(Gson.java:586)
com.google.gson.Gson.toJsonTree(Gson.java:479)
com.google.gson.Gson.toJsonTree(Gson.java:458)
skypark.RetriveIm.doGet(RetriveIm.java:66)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I don't know what this error tells. Please anyone help me to solve this...... thanks.....
You included two InputStream variables in your class, which are getting set to instances of OracleBlobInputStream, which your GSON provider cannot serialize. You probably want to store the image content as bytes instead (or as a (URL encoded) string).
public class ImageFileInfo implements Serializable {
// Other class variables
private byte[] thumbarray;
private byte[] fullarray;
// Constructors, Getters/Setters
}
ImageFile.setThumb(rs.getBytes("imagethumb"));
ImageFile.setFull(rs.getBytes("imagefull"));
On a side tangent, it looks like you are trying to return JSON content, but you have incorrectly specified your Content-Type as text/html, instead of application/json.