I am using IntelliJ IDEA 15.0.4, Apache Tomcat 7.0.68, and JDK 1.8.0-74.
My Java project compiles successfully in IntelliJ. However, whenever I deploy my exploded WAR, I get this error from Tomcat:
SEVERE: Error configuring application listener of class com.myCompany.init.Log4jListener
java.lang.Error: Unresolved compilation problems:
The import org.apache.log4j cannot be resolved
...(stack trace removed for brevity)
My class looks like this:
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.Loader;
import com.myCompany.AbstractEnvironment;
public class Log4jListener implements ServletContextListener {
private static final String KEY_EMAIL = "Alert";
private static final String SYSTEM_KEY_EMAIL = "Alert";
private static final String PROPERTY_FILE = "properties.environment";
#Override
public void contextDestroyed(ServletContextEvent sce) {
// nothing to do
}
#Override
public void contextInitialized(ServletContextEvent sce) {
final PropertyResourceBundle bundle = (PropertyResourceBundle) ResourceBundle.getBundle(PROPERTY_FILE);
final String emailInfo = AbstractEnvironment.getProperty(bundle, KEY_EMAIL);
System.setProperty(SYSTEM_KEY_EMAIL, emailInfo);
PropertyConfigurator.configure(Loader.getResource("properties/log4j.properties"));
final Logger logger = LogManager.getLogger(Log4jListener.class);
logger.debug("Logger Initialized");
}
}
The org.apache.log4j package comes from a Gradle dependency, which is included in my project:
... and, in other classes in my project where I've instantiated a Log4j object from the same class, it doesn't complain about it.
What's even more interesting is that when a co-worker checked in my (the same exact) project on his computer, he didn't get this error, using the same version of IDEA, the JDK, and Tomcat.
IDEA doesn't tell me I have any Java errors. I did a Gradle clean and build task. I did a Make Project in IntelliJ. I rebuilt the artifacts in IntelliJ. I removed and re-added the artifact on the Tomcat Server, and I still get the same error.
This leads me to believe that this error isn't correct and may be a false positive, because the same exact project works on my co-worker's computer. Any ideas?
Related
I am migrating a Java code that is running on Java 8 and I need to compile it to run on Java 17, so Just downloaded eclipse 2021-09 import the code from Git, change project facet selecting Java, add to Java Build Path the libraries.
libraries added
This is the code:
package itksoluciones.avl.lst.dboperation;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class PoolConexionUC {
public static DataSource dataSourceUC;
public PoolConexionUC() {
inicializaDataSourceUC();
}
private void inicializaDataSourceUC() {
BasicDataSource basicDataSourceUC = new BasicDataSource();
basicDataSourceUC.setDriverClassName(DataConexion.driverUC);
basicDataSourceUC.setUsername(DataConexion.userUC);
basicDataSourceUC.setPassword(DataConexion.passUC);
basicDataSourceUC.setUrl(DataConexion.urlUC);
basicDataSourceUC.setMaxActive(Integer.parseInt(DataConexion.maxActiveUC));
basicDataSourceUC.setMaxIdle(DataConexion.defaultMaxIdleUC);
basicDataSourceUC.setMaxWait(DataConexion.defaultMaxWaitUC);
basicDataSourceUC.setRemoveAbandoned(DataConexion.removeAbandonedUC);
basicDataSourceUC.setRemoveAbandonedTimeout(DataConexion.removeAbandonedTimeoutUC);
basicDataSourceUC.setValidationQuery(DataConexion.validationQueryUC);
basicDataSourceUC.setTestOnBorrow(DataConexion.testOnBorrowUC);
dataSourceUC = basicDataSourceUC;
}
}
This are the two errors:
Import org.apache could not be resolved
and
BasicDatasourceCore could not be resolved to a type
Errors
As you could see from the error the library seems available, also it autocompletes when typing.
Also one of the solutions suggested by eclipse is to import org.apache.commons.dbcp.BasicDataSource. (after doing it by double clicking on the suggestion first error is resolved but the second one persists).
What is also very curious is that if I copy paste the class PoolConexionCore to PoolConexionCore2. The problem is gone in PoolConexionCore2.
BUT I HAVE MANY CLASSES WITH THE SAME PROBLEM so I really appreciate any suggestion to avoid having to be dedicated to copy pasted for several days.
After doing copy paste
I'm setting up a very simple project, just trying to get a basic Hibernate setup without maven. I've downloaded the jar, put it under a /lib directory within my project and added this directory as a library under module settings. I can access Hibernate's classes and compile the project.
However, after declaring that the method throws a HibernateException (that extends PersistenceException), the code doesn't compile:
HibernateStatesMain.java:
package example;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
public class HibernateStatesMain {
public static void main(String[] args) throws HibernateException {
Configuration config = new Configuration().configure();
}
}
And when I build, I get:
Error:(11, 24) java: cannot access javax.persistence.PersistenceException
class file for javax.persistence.PersistenceException not found
This should be a very simple thing, but I can't get my head around it. What am I doing wrong?
I'm trying to setup an application that runs on OSGi internally and have tried using the tutorial here, but I get the error "The method getBundleContext() is undefined for the type Framework" all the time. As far as I can tell, I'm using the right library, but it's not specified in the mentioned article, so I'm not 100% sure. I've also tried the examples on Apache's website, here, which results in the same issue. Code below:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
public class Main {
public static void main(String[] args) throws BundleException {
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();
Framework framework = frameworkFactory.newFramework(config);
framework.start();
// Throws error that it cannot find method getBundleContext()
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
installedBundles.add(context.installBundle("file:org.apache.felix.shell-1.4.2.jar"));
installedBundles.add(context.installBundle("file:org.apache.felix.shell.tui-1.4.1.jar"));
for (Bundle bundle : installedBundles) {
bundle.start();
}
}
}
The only thing that makes sense is that either I'm using the wrong libraries, or the libraries have changed and the method I'm attempting to call has since been deprecated out in the last 4 years. Anyone know how I can fix this?
I doubt it makes much of a difference, but in case it does, I'm using Bndtools for Eclipse to create this project.
Found the issue. Apparently, the import of osgi.core that was in the Bndtools' project build path was out of date, preventing the code from accessing the correct version of the framework libraries. Updating that fixed the issue.
Additional side-note; Since I'm using Bndtools, I was adding this to the project build path via the bnd.bnd file's build tab. This, however, was not grabbing the correct version of osgi.core, so I had to go under source and add the version=latest in order to force it to get the latest version available, so the line now appears as: osgi.core;version=latest where it was previously just osgi.core under the -buildpath: section.
I'm building a simple app in IntelliJ IDEA 13 and can't seem to figure out how to get log4j working. My app is a simple demo that I made to make sure I could build something functional, all it does is multiply two random numbers and uses apache tomcat to put it on a localhost that I can access via my browser.
Here is the class code:
package Sample;
log4j-api-2.0.jar;
log4j-core-2.0.jar;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
public class HelloWorld {
public static double getMessage() {
return Math.random()* Math.random();
}
private static Logger log = LogManager.getRootLogger();
log.debug("Debugging Message");
log.info("Informational message");
log.warn("Warning Message");
System.in.read();
}
I'm getting the error "class or interface expected" at the import lines and jar file lines so I don't think I've placed the corresponding files in the right directory. That's also causing the rest of the logging lines (from private static Logger... on) to generate errors.
1. The following isn't valid Java:
log4j-api-2.0.jar;
log4j-core-2.0.jar;
You only need the import lines, e.g.,
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
2. The .jar files must be associated with your project.
You can:
Right-click the "External Libraries" section and add them that way, or...
Use Maven and add them as project dependencies, or...
Use some other dependency management and/or build tool, e.g., Ant + Ivy, Gradle, etc.
3. You need to move the logging statements into a place where code is valid, like in a method:
package sample;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
public class HelloWorld {
private static final Logger log = LogManager.getRootLogger();
public static void main(String[] args) {
log.debug("Debugging Message");
log.info("Informational message");
log.warn("Warning Message");
}
}
I'm a newbie to Java and to EJB. Want to create a simple EJB.
So I've created an EJB Project via Eclipse (Eclipse Java EE IDE Juno Service Release 1 Build ID: 20120920-0800). Then I've added a Stateless Session Bean there with Remote and Local interfaces. Then I added a simple method that just returns a sum of 2 numbers. Here is the code:
Test.java:
package ejb;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
/**
* Session Bean implementation class Test
*/
#Stateless
#TransactionManagement(TransactionManagementType.BEAN)
public class Test implements TestRemote, TestLocal {
/**
* Default constructor.
*/
public Test() {
// TODO Auto-generated constructor stub
}
public int getSum(int a , int b) {
return (a + b);
}
}
TestLocal.java:
package ejb;
import javax.ejb.Local;
#Local
public interface TestLocal {
public int getSum(int a , int b);
}
TestRemote.java :
package ejb;
import javax.ejb.Remote;
#Remote
public interface TestRemote {
public int getSum(int a , int b);
}
I right-clicked on my EJB Project and exported it as a JAR file. Then I deployed it to GlassFish3 server: 1) Applications - Deploy and so on; 2) JNDI - Custom Resources. I've set Resource Type to ejb.TestRemote , Factory Class to org.glassfish.resources.custom.factory.EjbFactory . JNDI Name was Test. Then I've coded a simple client:
Main.java:
import javax.naming.InitialContext;
import ejb.TestRemote;
public class Main {
public static void main(String arg[]) {
try {
TestRemote testR = (TestRemote) new InitialContext().lookup("Test");
//System.out.println(new InitialContext().lookup("Test").toString());
//.toString displays: Reference Class Name: ejb.TestRemote
System.out.println(testR.getSum(50, 500));
} catch(Exception e) {
e.printStackTrace();
}
}
}
I've added gf-client-module.jar from C:\glassfish3\glassfish\modules and a JAR file of my EJB Project to Java Build Path (Project-Properties).
Then I tried to launch my client in Eclipse and got following message appeared immediately:
com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Then I got next message:
java.lang.ClassCastException: javax.naming.Reference cannot be cast to ejb.TestRemote
at Main.main(Main.java:16)
So, can anyone please help me with that?.. I'm really confused: .toString method called on a reference displays that it is a proper ejb.TestRemote class reference, as I mentioned before. But... It doesn't work ((
Any ideas? Thanks in advance.
RESOLVED FOR ME, BUT WITH SOME ANOTHER WAY
I've lost hope to make it with Eclipse and separately installed GlassFish. So, I've installed a GlassFish server to Eclipse, and deployed my EJB project there. It worked: now my Client works fine. The only change was - I should provide a full package name to .lookup: like .lookup("ejb.TestRemote").
Thanks everyone who tried/wanted/wished to help!