Java class not found errors while running - java

I have a class that is having some dependency problems referencing external library files. Every time I try to run this on the server I get errors saying class not found, such as this:
SEVERE: Class [ org/json/JSONException ] not found. Error while loading [ class com.myproj.logic.Driver ]
this is preventing the class from executing. I tried taking out the specific throws execption by just saying "throws exception" and got the following error:
WARNING: A system exception occurred during an invocation on EJB Driver method public void com..logic.Driver.initURL() throws java.lang.Exception
javax.ejb.EJBException: javax.ejb.CreateException: Initialization failed for Singleton Driver
Caused by: java.lang.ClassNotFoundException: org.apache.commons.io.IOUtils
#Singleton
public class Driver {
#EJB RSSbean rssbean;
#PostConstruct
#Schedule(hour ="*/1", minute ="*/1", second ="*/1", persistent = false)
public void initURL() throws IOException, JSONException{
URL twitterSource = new URL("http://search.twitter.com/search.json?q=news");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
JSONObject thisobject = new JSONObject(urlContents);
JSONArray names = thisobject.names();
JSONArray asArray = thisobject.toJSONArray(names);
JSONArray resultsArray = thisobject.getJSONArray("results");
JSONObject jsonObject = resultsArray.getJSONObject(0);
String twitterText = jsonObject.getString("text");
//System.out.println(twitterText);
System.out.println("Calling rssbean from Driver");
rssbean.updateDatabase("twitterText");
}
}
I have edited the Java classpath and added a user library for each of these as well as editing the Build Path of the project. The libraries are displayed in the list and I don't get compiler errors so at least Eclipse has recognized them. The problem comes during execution so I think something is wrong there.
Should I edit the classpath in Windows>Preferences>Java>Classpath> and add the Jars there? I have not had to do this for any other libraries before.

I found out you have to add any library files in the Glassfish/domain/lib directory before they're recognized by glassfish on the server.

Related

Exception In Initializer Error in Java

I'm trying to execute a protocol through R's console and everytime I get this error:
Error in .jnew("gr.demokritos.iit.radio.home.orchestration.Controller") :
java.lang.ExceptionInInitializerError
I tried to google the error and I only understand that there's something wrong with the static block. Although it seems normal to me.
The two static blocks that exist in the mentioned class:
static ComputationService service;
static {
String conf_path = System.getProperty("config.file", "/root/application.conf");
Config my = ConfigFactory.parseFile(new File(conf_path));
Config config = my.withFallback(ConfigFactory.load());
service = ComputationService$.MODULE$.apply(ActorSystem.apply("benaloh", config));
}
The full source files that are referenced:
ttest.r (jnew at line 55)
controller.java

REST-Driver ClientDriverRule error on instantiation

I decided to try the rest-driver library for my unit tests.
I have the following code:
public class RemoteSessionAccountantTest {
#Rule
public ClientDriverRule driver = new ClientDriverRule();
// ...
#Test
public void singleUserSession() throws IOException, JSONException {
driver.addExpectation(
onRequestTo("http://myTestUrl/anyUsername").withMethod(Method.GET),
giveResponse("[{\"contractCode\":\"1234\"}]", "application/json"));
// ...
}
// ...
}
But I'm not even reaching the test case because instantiating the ClientDriverRule results in an error:
com.github.restdriver.clientdriver.exception.ClientDriverSetupException:
Error starting jetty on port 0
...
Caused by: java.lang.IllegalStateException: Local port was not set
Now I've tried setting a specific port, but it didn't help.
I have jetty v9.3.0 (also tried versions 8.x.x, 9.1.x, 9.2.x with no luck)
rest-client-driver version 1.1.42
The problem seems to be coming from jetty, but I cannot figure out what exactly.

Spring Error java.lang.NullPointerException

My Main
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
System.out.println("hola");
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:201)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:551)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:465)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.tutorialspoint.MainApp.main(MainApp.java:9)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.
DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:108)
... 7 more
The NullPointerException error is at almost impossible location:
static {
ClassLoader cl = DefaultListableBeanFactory.class.getClassLoader();
try {
javaxInjectProviderClass = cl.loadClass("javax.inject.Provider"); /* line 108 */
} catch (ClassNotFoundException ex) {
// JSR-330 API not available - Provider interface simply not supported then.
}
}
This means that the class is not able to get its own classloader. You must have done something really bad to get this error. Check your JRE/JDK, IDE, ...
UPDATE
There is no explanation other than that you are probably trying to put Spring JARs into JRE's library folder (${java.home}/jre/lib). If that is the case, that is simply wrong. If you really want to include external JARs within JRE, then put them in the official extension directory - ${java.home}/jre/lib/ext.

How to run the servlet test by using HttpUnit servlet runner? Problems in Starting up with ServletUnit?

I was planning to unit test my Servlet through ServletUnit and ran across some problems :
- As a starting point, we are supposed to create a ServletRunner object. One of the constructors expects File object with web.xml file. I provide the full path of my web.xml file but somehow it ignores the path provided and searches at the top level folder. The code-snippet and error message is below:
Code Snippet
ServletRunner sr = new ServletRunner(new File("* C:/eclipse-workspaces/pocs/lms-csd/src/main/webapp/WEB-INF/web.xml*"));
ServletUnitClient sc = sr.newClient();
WebRequest request = new PostMethodWebRequest("path to be specified" ); request.setParameter( "userId", "test" );
request.setParameter( "password", "csd" );
WebResponse response = sc.getResponse(request);
String text = response.getText();
Assert.assertTrue(text.contains("Welcome to Leave Management System"));
stack trace
com.meterware.httpunit.HttpInternalErrorException:
Error on HTTP request: 500 org.apache.jasper.JasperException: java.io.FileNotFoundException: * C:\eclipse-workspaces\pocs\lms-csd\WEB-INF\web.xml*
(The system cannot find the path specified)
[http://localhost/login] - Why does the system keep on looking at the folder structure to be .../WEB-INF/web.xml.
Mine is a maven project and I would not like to change the structure of the project to adapt this way. How can I make ServletRunner class to read from a specified folder ? - In the Servlet code,
I use the following code :
String result = null if (someCondition) result = "/welcome.jsp"; } else { logger.warn("Password Validation failed"); request.setAttribute("failedlogin", new Boolean(true)); result = "/index.jsp"; } } RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(result); requestDispatcher.forward(request, response);
Again ServletUnit expects welcome.jsp to be at root foler, though jsp files are present at .../src/main/webapp/ folder. Again how can ServletUnit be told about the target folder location ?
Many thanks in advance.
Best Regards
M.SuriNaidu
This is the sort of thing I do. This is a facsimile of the base class of my servlet tests. In this case I pass the relative path of the web.xml file as it exists in my source tree. I run these tests from ant and eclipse.
abstract public class ServletTestCase {
protected ServletRunner m_runner;
protected ServletUnitClient m_client;
protected String m_userAgent = "something/1.0";
#Override
protected void setUp() throws Exception {
super.setUp();
initHttpUnit();
}
#Override
protected void tearDown() throws Exception {
shutdownHttpUnit();
super.tearDown();
}
protected void initHttpUnit() throws IOException, SAXException {
shutdownHttpUnit();
// We are expecting UTF-8 character handling in URLs, make it the default
HttpUnitOptions.setDefaultCharacterSet("UTF-8");
// Find the servlet's web.xml file and use it to init servletunit
File file = new File("tests/web.xml"));
m_runner = new ServletRunner(file);
m_client = m_runner.newClient();
m_client.getClientProperties().setUserAgent(m_userAgent);
}
protected void shutdownHttpUnit() {
if (m_runner != null) {
m_runner.shutDown();
}
m_client = null;
m_runner = null;
}
}

NullPointerException is thrown when trying to call JDBC from a servlet

I'm running my servlet RegistrationServlet , and I try to create a Database object
Here is the servlet :
#WebServlet("/register")
public class RegistrationServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
// create a new connection to mysql database , with this we put the new client in the database
Database myDabatase = null;
try {
myDabatase = new Database();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} // create a new database
myDabatase.createDatabaseAndTables(); // create the tables of the database
HttpSession session = request.getSession();
synchronized(session)
{
boolean returnValue = myDabatase.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
if (returnValue == true) // client was added
{
String addressPath = "/WEB-INF/results/show-name.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(addressPath);
dispatcher.forward(request, response);
}
else if (returnValue == false) // client was not added becuase he's already registered
{
}
}
}
}
Here is the complete class :
But when I execute that line in my servlet :
boolean returnValue = myDabatase.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
I get a NullPointerException that says :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at db.Database.<init>(Database.java:18)
at servlets.RegistrationServlet.doGet(RegistrationServlet.java:28)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Which led me to the line :
Class.forName("com.mysql.jdbc.Driver");
in the constructor of the Database class , and as you can see in the track trace :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
But , when I execute the same program as a Main program :
public class Main {
public static void main(String [ ] args) throws Exception
{
Database myConnection = new Database();
myConnection.createDatabaseAndTables();
boolean returnValue = myConnection.addNewClient("david", "cole", "jamie", "123456789", "johnny", "blabla");
}
}
Everything is okay , and I get no NullPointerException .
Then what's wrong if I do that same thing from a servelt ? why the NullPointerException ?
Regards
The MySQL driver is missing from the classpath when you run the servlet. The JAR file with the driver probably needs to be added to the WEB-INF/lib directory of your webapp.
Make sure mysql driver jar is in your lib folder (or classpath if its console app). Try to specify port to mysql (3306 if you didn't change it).
The MySQL jar is missing from the classpath of your server's container whereas it is present when you run the standalone main application.
I had the same problem, in the same line, but I solved it by adding to the project the JAR for the MySQL connection.
Before, it was not included in the project because all the data for the connection had been added within the server configuration (Payara Server 5), just for this reason the error does not occur when displaying the project on the server. However, when running it in JUnit this is not taken into account, so it is necessary to add the JAR to make the connection directly from the project and not from the server.
I hope this is useful, for those who have the same problem.

Categories

Resources