I am using Guava 14.0 jar and following is my code
package org.user.module.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class test
*/
#WebServlet("/test")
public class test extends HttpServlet {
private static final long serialVersionUID = 1L;
Cache<String, Integer> map;
public test() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException
{
map=CacheBuilder.newBuilder().
maximumSize(100).
expireAfterAccess(10, TimeUnit.MINUTES).
build();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String p=request.getParameter("v");
Integer a=map.getIfPresent(p);
if(a==null){
map.put(p, 1);
out.println("Putting The Integer:"+a);
}
else{
map.put(p,a++);
out.println("A is already present and the value is:"+a);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Error:
SEVERE: Allocate exception for servlet org.user.module.test.test
java.lang.ClassNotFoundException: com.google.common.cache.Cache at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546)
at java.lang.Class.getDeclaredFields0(Native Method) at
java.lang.Class.privateGetDeclaredFields(Class.java:2317) at
java.lang.Class.getDeclaredFields(Class.java:1762) at
org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(DefaultInstanceManager.java:276)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:143)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1136)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:857)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
downloaded jar from here Downlaod Link
Link to my project folder(Project name:test2) LINK
Obvious answer is that;
The Google guava jar is not found from the classpath dictated by the application server. The jar should be present in either WEB-INF/classes or WEB-INF/lib. Apache Tomcat also loads common classes from $CATALINA_HOME/lib folder.
Related
I followed the Quarkus Azure Functions guide to create a new project. I added a POST to the vert.x greeting class and to the servlet class. Both return a 500 with no body, and when viewed from the Application Insights page, contain similar errors related to converting RpcHttpRequestDataSource to byte[]. But locally, both work fine.
Here's the servlet POST which works when running locally via mvn quarkus:dev:
import java.io.IOException;
import java.util.stream.Collectors;
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(name = "ServletGreeting", urlPatterns = "/servlet/hello")
public class GreetingServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(200);
resp.addHeader("Content-Type", "text/plain");
resp.getWriter().write("hello servlet");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setStatus(200);
resp.addHeader("Content-Type", "text/plain");;
resp.getWriter().write("hello " + req.getReader().lines().collect(Collectors.joining(System.lineSeparator())));
}
}
Exception while executing function: Functions.quarkus Result: Failure
Exception: ClassCastException: Cannot convert com.microsoft.azure.functions.worker.binding.RpcHttpRequestDataSource#7e569681to type com.microsoft.azure.functions.HttpRequestMessage<java.util.Optional<byte[]>>
Stack: java.lang.ClassCastException: Cannot convert com.microsoft.azure.functions.worker.binding.RpcHttpRequestDataSource#7e569681to type com.microsoft.azure.functions.HttpRequestMessage<java.util.Optional<byte[]>>
at com.microsoft.azure.functions.worker.binding.DataOperations.generalAssignment(DataOperations.java:191)
at com.microsoft.azure.functions.worker.binding.DataOperations.apply(DataOperations.java:120)
at com.microsoft.azure.functions.worker.binding.DataSource.computeByType(DataSource.java:56)
at com.microsoft.azure.functions.worker.binding.RpcHttpRequestDataSource.computeByType(RpcHttpRequestDataSource.java:20)
at com.microsoft.azure.functions.worker.binding.DataSource.computeByName(DataSource.java:42)
at com.microsoft.azure.functions.worker.binding.RpcHttpRequestDataSource.computeByName(RpcHttpRequestDataSource.java:20)
at com.microsoft.azure.functions.worker.binding.BindingDataStore.getDataByName(BindingDataStore.java:55)
at com.microsoft.azure.functions.worker.broker.ParameterResolver.resolve(ParameterResolver.java:59)
at com.microsoft.azure.functions.worker.broker.ParameterResolver.resolve(ParameterResolver.java:42)
at com.microsoft.azure.functions.worker.broker.JavaMethodExecutorImpl.execute(JavaMethodExecutorImpl.java:52)
at com.microsoft.azure.functions.worker.broker.JavaFunctionBroker.invokeMethod(JavaFunctionBroker.java:57)
at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:33)
at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:10)
at com.microsoft.azure.functions.worker.handler.MessageHandler.handle(MessageHandler.java:45)
at com.microsoft.azure.functions.worker.JavaWorkerClient$StreamingMessagePeer.lambda$onNext$0(JavaWorkerClient.java:92)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Is this a Quarkus issue, or something else?
Exception when writing the response back using jackson. Unable to find any solutions on the net. I am not sure what is the cause of error. Tried flushing the response but still the same error
import com.In10s.DBProperties.OracleDBConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
public class GetTable extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
try {
JSONArray data = new JSONArray();
Connection con = OracleDBConnection.getConnection();
String query = "Select * from CREDIT_CARD_TRANSACTIONS";
Statement st = con.createStatement();
ResultSet rSet = st.executeQuery(query);
List<Map<String, Object>> result = new ArrayList<>();// JDK7++
while (rSet.next()) {
Map<String, Object> row = new HashMap<>();
row.put("CARD_NUMBER", rSet.getString("CARD_NUMBER"));
row.put("FIRST_NAME", rSet.getString("FIRST_NAME"));
row.put("OPENING_BALANCE", rSet.getString("OPENING_BALANCE"));
row.put("WITHDRAWAL", rSet.getString("WITHDRAWAL"));
row.put("DEPOSIT", rSet.getString("DEPOSIT"));
row.put("CLOSING_BAL", rSet.getString("CLOSING_BAL"));
row.put("TXDATE", rSet.getString("TXDATE"));
row.put("USAGE_TYPE", rSet.getString("USAGE_TYPE"));
result.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
try {
response.getWriter().write(mapper.writeValueAsString(response));
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Here is stack trace:
com.fasterxml.jackson.databind.JsonMappingException: getWriter() has already been called for this response (through reference chain: org.apache.catalina.connector.ResponseFacade["outputStream"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:190)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:671)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3383)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2777)
at com.In10s.getTable.GetTable.doGet(GetTable.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:644)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:196)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:536)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663)
... 28 more
You're trying to transform the HttpServletResponse into JSON, and send it to the HttpServletResponse. You want to transform the result list to JSON instead:
response.getWriter().write(mapper.writeValueAsString(result));
I'm having a problem trying to call a method of session bean, when calling firstly the servlet from a JSP, then the servlet calling the method of session bean to obtain some data it seems to get a NullPointerException. On the other hand if I just run the servlet on it's own it does the job and retrieves the data from session bean.
The following is the code of the servlet;
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import auction.ItemRegistrationSessionBeanRemote;
/**
* Servlet implementation class processItem
*/
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
public ArrayList<String> categories = new ArrayList<String>();
#EJB ItemRegistrationSessionBeanRemote itemRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
}
#PostConstruct
public
void init() {
System.out.println("init()");
categories = itemRegistrationSession.getCategories();
System.out.println("init() categories = " + categories.toString());
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
#PostConstruct
public void obtainCategories() {
categories = itemRegistrationSession.getCategories();
}
#PostConstruct
public ArrayList<String> getCategories() {
return categories;
}
}
This is the part of JSP that calls the servlet:
<jsp:useBean id="obj" scope="page" class="web.processItem" />
<select name="affiliation" id="categories-dropdown">
<% obj.init(); %>
<c:forEach var="aff" items="${obj.getCategories()}"
<%System.out.println("categories = " + obj.getCategories()); %>
<option value="${aff}">${aff}</option>
</c:forEach>
</select>
This is the Session Bean:
package auction;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.sun.jersey.spi.resource.Singleton;
import entity.Category;
/**
* Session Bean implementation class ItemRegistrationSessionBean
*/
#Stateful #Singleton
public class ItemRegistrationSessionBean implements ItemRegistrationSessionBeanRemote {
#PersistenceContext(name = "MiniEbayEJB")
private EntityManager emgr;
/**
* Default constructor.
*/
public ItemRegistrationSessionBean() {
// TODO Auto-generated constructor stub
}
#Override
public ArrayList<String> getCategories() {
System.out.println("Hello from SessionBean getCategories");
ArrayList<String> categories = new ArrayList<String>();
List<Category> obtainedCategories = (List<Category>) emgr.createNamedQuery("Category.findAll", Category.class).getResultList();
for (int i = 0; i < obtainedCategories.size(); i++) {
categories.add(obtainedCategories.get(i).toString());
System.out.println("Current ArrayList of categories = " + categories);
}
return categories;
}
}
And here is the stack trace when calling from jsp->servlet->session bean:
2014-02-28T14:48:21.696+0000|WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
at web.processItem.init(processItem.java:35)
at org.apache.jsp.insert_jsp._jspService(insert_jsp.java:166)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)
You can't call the "servlet" instance from the JSP like you do.
What you actually do with:
<jsp:useBean id="obj" scope="page" class="web.processItem" />
is to create a "new" instance of web.processItem which is not container managed at all - hence it does not have your dependencies.
The servlet only call does work, because the container did create and manage the instance of processItem and you got your dependencies injected.
i am developing a project KNOWLEDGE based community sharing system.
in which users can login and share their resources to other Users....
I'm getting a problem in uploading a file to mysql database....
PS..my Instructor strictly Says to use MVC architecture So, i have to use the same..
So i have created only one Servlet named Controller.java.
here i will redirect to other java programs for calculations...
Here is the code for Controller.java
package com.kbcss.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {super();}
#SuppressWarnings("rawtypes")
private Map commands = new HashMap();
#SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException{
super.init();
System.out.println("i am in init");
this.commands.put("login", new LoginCommand());
this.commands.put("user", new UserCommand());
this.commands.put("resource", new ResourceCommand());
System.out.println("i am about to exit init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in doget");
processCommand(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in dopost");
processCommand(request, response);
}
private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in processCommand");
String formAction = request.getParameter("form_action");
System.out.println("i am in processCommand state 2");
Commands command = (Commands) commands.get(formAction);
command.execute(request, response);
System.out.println("i am about to exit processCommand");
}
}
and here is the code for saving the resources to MY database table.... Named ResourceCommand .java
package com.kbcss.command;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;
import com.oreilly.servlet.MultipartRequest;
public class ResourceCommand extends HttpServlet implements Commands{
private static final long serialVersionUID = 1L;
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//
// JNDI to connect to database
//
Connection conn = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
conn = ds.getConnection();
//
// Save file(s) temporarily to filesystem
//
MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
Enumeration files = multi.getFileNames();
String filename = "";
File f = null;
while(files.hasMoreElements()) {
String name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
f = multi.getFile(name);
}
//
// Insert file into database
//
InputStream is = new FileInputStream(f);
String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
PreparedStatement stmt = conn.prepareStatement(sql);
// Set some Title
stmt.setString(1, "some thing");
// Set some category
stmt.setString(2, ".net");
// Set some user
stmt.setString(3, "sri");
// Set Filename
stmt.setString(4, f.getName());
// Set the data
stmt.setBinaryStream(5, is, (int) f.length());
// Set Likes
stmt.setInt(6, 2);
stmt.executeUpdate();
is.close();
//
// Release connection
//
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
} catch(Exception e) {
System.out.println(e);
}
}
}
And here is the jSP file where i will upload from....
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>UPLOAD FILE page</title></head>
<body>
<form method="post" action="Controller" enctype="multipart/form-data">
<input type="hidden" name="form_action" value="resource" />
<b>File to upload to database:</b>
<input type="file" name="attachment" size="36">
<input type="submit" value="Upload">
</form>
</body></html>
And this is the error i'm getting :(
INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
at com.kbcss.controller.Controller.processCommand(Controller.java:69)
at com.kbcss.controller.Controller.doPost(Controller.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and by the way..i have created a Command.java interface here it is.
package com.kbcss.command;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public interface Commands {
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ
i'm stuck for a day and Half and have no clue what i'm doing...
This is what happens if u ask an electrical engineering student to do a Java Project !!!!
GREAT GREAT thanks from My side.....
Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.
Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).
One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:
private Map<String,Command> commands = new HashMap<String,Command>();
After you do that, you shouldn't have to suppress the warning on the Map.
Did anyone encountered this exception while using Jena in Java Web Application... Please Kindly help me ..
Here is my servlet code
package com.mycompany.servlet;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.ontology.*;
/**
* Servlet implementation class GreetingServlet
*/
#WebServlet("/GreetingServlet")
public class GreetingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GreetingServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String SOURCE ="file:E:\\healthcare.owl";
OntModel base = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
base.read( SOURCE );
for (Iterator<OntClass> i = base.listClasses(); i.hasNext(); )
{
OntClass c = i.next();
//System.out.println( "Class" + c.getLocalName());
}
}
}
Exception is
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class com.mycompany.servlet.GreetingServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: com/hp/hpl/jena/rdf/model/Model
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
java.lang.Class.getConstructor0(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.Model
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
java.lang.Class.getConstructor0(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.11 logs.
root cause
java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.Model
That means that tomcat can't find the Jena libraries. Make sure you have all the right jars in the right place.
You need to copy each of the *.jar files from $JENA/lib (where $JENA is the directory you installed your local installation of Jena into) to the WEB-INF/lib directory of your servlet application.
just copy the jena jars declared on the build path project to the lib directory of tomcat, in my case it is located at
C:\Apache Software Foundation\Tomcat 6.0\lib