Setting Up Log4J in IntelliJ IDEA 13 - java

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");
}
}

Related

"Class path resource [config/game.properties] cannot be opened because it does not exist" IntelliJ - Spring project not looking in correct directory?

I'm making a Java Spring project in IntelliJ as an exercise and I don't understand a file configuration error I'm having.
Please look at my project directory layout as described in this screenshot:
The three most important files here are the Main & GameConfig classes, and the game.properties file. Or, to use their full package directory names, "console/src/main/java/academy.learnprogramming.console.Main", "core/src/main/java/academy.learnprogramming.config.GameConfig" and core/src.resources.config.game.properties
When I run project, the Main class tries to run the following code:
package academy.learnprogramming.console;
import academy.learnprogramming.MessageGenerator;
import academy.learnprogramming.NumberGenerator;
import academy.learnprogramming.config.GameConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
private static final Logger log = LoggerFactory.getLogger(com.sun.tools.javac.Main.class);
public static void main(String[] args) {
log.info("Guess the number");
//== create the context first ==
ConfigurableApplicationContext context
= new AnnotationConfigApplicationContext(GameConfig.class);
// rest of code, which we never get to because of an error with the above line
When I try to create ConfigurableApplicationContext, I am trying to call the GameConfig class from the Core package. But I get this runtime error instead:
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException: Failed
to parse configuration class
[academy.learnprogramming.config.GameConfig]; nested exception is
java.io.FileNotFoundException: class path resource
[config/game.properties] cannot be opened because it does not exist
I do not understand why it thinks GameConfig does not exist, or how to fix it. No solutions I have found seem to have the precise answer for this. I have gotten a configuration comparison from someone whose code is identical to mine, but neither of us understand why their version works and mine does not.
For comparison's sake, the GameConfig class has the following code:
package academy.learnprogramming.config;
import academy.learnprogramming.GuessCount;
import academy.learnprogramming.MaxNumber;
import academy.learnprogramming.MinNumber;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#ComponentScan(basePackages = "academy.learnprogramming")
#PropertySource("classpath:config/game.properties")
public class GameConfig {
//rest of GameConfig code here...
While game.properties is as simple as this:
game.maxNumber = 100
game.guessCount = 10
game.minNumber = 0
I can't find a question similar to this, nor do other websites point out what's going on. Does anyone have any idea why this error might be happening? Any advice would be invaluable

Jax-ws endpoint not asking to create wrapper classes

I'm following this simple tutorial: https://www.mkyong.com/webservices/jax-ws/jax-ws-hello-world-example-document-style/?fbclid=IwAR0vxhYrj9MKy1Q28h6luFVJoSxDP4KWBOLEu_v_Ss4uQztmB-9JuYsS4RI and at step 3 it mentions that I should receive the error:
Wrapper class com.mkyong.ws.jaxws.GetHelloWorldAsString is not found.
Have you run APT to generate them?
However, I do not get such error(no error at all) and I'm worried that it is not working as expected.
My classes:
Interface:
package com.soap3sk.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;
// Service Endpoint Interface
#WebService
#SOAPBinding(style= Style.DOCUMENT, use= Use.LITERAL) // optional
public interface NoteEndpoint {
//#WebMethod ArrayList<ToDoNote> getNotes();
#WebMethod String getHelloWorldAsString(String name);
}
Implementation:
package com.soap3sk.ws;
import javax.jws.WebService;
#WebService(endpointInterface = "com.soap3sk.ws.NoteEndpoint")
public class NoteEndpointImpl implements NoteEndpoint {
#Override
public String getHelloWorldAsString(String name) {
return "Hello World JAX-WS " + name;
}
}
Publisher:
package com.soap3sk.endpoint;
import javax.xml.ws.Endpoint;
import com.soap3sk.ws.NoteEndpointImpl;
public class NoteEndpointPublisher {
public static void main (String[] args) {
Endpoint.publish("http://localhost:5000/ws/hello", new NoteEndpointImpl());
}
}
Project structure: https://imagizer.imageshack.com/img924/3514/BAuOcl.png
What I also noticed that those 2 .class files(asString and Response that are mentioned in the guide) are not generated anywhere as well. I'm using Eclipse and created a maven project with the quickstart archetype. Runnning it as a standard java application.
I can access the wsdl file going here: http://localhost:5000/ws/hello?wsdl and the I can see getHelloWorldAsString and getHelloWorldAsStringResponse there, but they are nowhere to be seen in my project and no error is thrown that they could not be found as mentioned in the guide that it should.
I also tried downloading the sample project and deleting the .java files that should be required, but it is stil the same(no error, not asking to create those classes).
I would be very grateful if someone could help. Thank you.
EDIT
I found a similiar question here: Java web service not giving error message Could someone explain his answer? Is the creation of those two classes not necessary?
you're trying to replicate a situation reported almost 10 years ago. Don't you want to try a newer tutorial like the following:
https://www.baeldung.com/jax-ws
https://spring.io/guides/gs/producing-web-service/

Unit Testing with different behaviour on existance of a file

There are some cases that the software shall behave differently according to some environmental conditions, for example whether a file exists at some place or not.
In my case, I'm developing a library, and it is configured according to a configuration file in classpath, (and falls back to default behavior if the config file does not exists).
How shall I unit test this class?
I need to write tests for evaluating the class in following cases:
the file does not exists on classpath
the file with content A exist on classpath
the file with content B exist on classpath
But I don't know how to configure environment to justify all of them. And execute the test one after each other.
By the way I'm using Java, and I have both JUnit and TestNG on the test classpath.
Edit:
One of the problems is that the config file resides in classpath, so if the normal ClassLoader finds and loads it, it returns the same content as long as the same class loader is used.
And I believe using a custom ClassLoader for testing is so complicated, that it needs tests to validate the tests!
You can use a temporary file created by your test to mock out the path in your class.
ConfigurationTest.java:
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeThat;
import java.nio.file.Files;
import org.junit.Test;
public class ConfigurationTest {
private Configuration config = new Configuration();
#Test
public void testWithConfigFile() throws Exception {
config.configFile = Files.createTempFile("config_",".ini");
config.configFile.toFile().deleteOnExit();
assertFalse(config.isInDefaultMode());
}
#Test
public void testWithoutConfigFile() throws Exception {
assumeThat(Files.exists(config.configFile), is(false));
assertTrue(config.isInDefaultMode());
}
}
Configuration.java:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Configuration {
Path configFile = Paths.get("config.ini");
public boolean isInDefaultMode() {
return !Files.exists(configFile);
}
}

Tomcat keeps giving me a false positive on a compilation error

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?

import from external lib jython

I am trying to imported a java class from an external lib in jyhon and it does not work. An example
package run;
import import.Imported;
Class Run()
{
public static void main(String[] args){
pi = new PythonInterpreter(null);
pi.execfile('script.py');
}
}
//this is an external libary
package import;
Class Imported()
{
//some stuff;
}
//py script
from import import Imported //this line throws an error Module not found
#do some stuff
The strangest thing is that it runs when it is compiled in Eclipse, but does not from command line.
Any help?
Sounds like your classpath is probably set incorrectly at runtime. The easiest solution is typically just to add the directory or jar file containing 'import' to sys.path.
(Also, naming your packages 'import' is just asking for trouble.)

Categories