How to automatically add code to every class I create - java

In Eclipse (Java), how do I automatically add code to every class I create. Suppose I create a class called Foo, I want this code to automatically go in the preamble/state:
private final Logger log = LoggerFactory.getLogger(this.getClass());
and the appropriate slf4j import to be automatically imported. Similarly, I would like the constructor to automatically show up. Full example of what I would like to see after I click the create button:
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public Foo() {
}
}

This should help. You can modify whichever template suits your purpose.

You could change the New Java Files and Class body templates to get what you want.
In the Preferences, under Java-> Code Style -> Code Templates, there is New Java Files where you would add the imports, at the appropriate place.
Change the Class body template like this
private final Logger log = LoggerFactory.getLogger(this.getClass());
public void ${type_name}() {
}
to add the logger and a default, public constructor.
Making those 2 changes will automatically add what you want when you create a new Java class file with Eclipse.

Related

#Path Annotation requirements?

I'm new to specifying resource routes in Java, and I'm having issues specifying the route. So far I have one Class which simply extends Application, and one class that reacts to input. What are the routing requirements for these classes? My code below does not work and im trying to figure out why. I've tried to find sources for these, but haven't had much luck.
Can I just use a / for the ApplicationPath? All this class does is extend Application so it can find routes.
Example:
package com.sentiment360.helloworld;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* JAXActivator is an arbitrary name, what is important is that javax.ws.rs.core.Application is extended
* and the #ApplicationPath annotation is used with a "rest" path. Without this the rest routes linked to
* from index.html would not be found.
*/
#ApplicationPath("/")
public class JAXActivator extends Application {
}
Does each class need to have a declared #Path (or can they all be #Stateless)?
#Path("/helloservice")
public class HelloService {
private static Logger _logger;
public HelloService(){
_logger = Logger.getLogger(HelloService.class.getName());
}
private Connection conn() throws SQLException {...}
}
The short version for #1 is yes.
BUT: behavior is implementation dependent. See https://stackoverflow.com/a/16747253/1063501 for a thorough explanation.
As for #2, yes, you generally need to specify a #Path for every endpoint you want. The fact that it is #Stateless is irrelevant as you'll need a way to address it.

log4j hierarchy between different packages

I am new in log4j. As I read on internet, child logger inherit parent logger settings. Usually examples are given are for two classes in same package. But what if the classes will be in different packages? For example
import com.foo.Bar;
public class MyApp{
static Logger logger = Logger.getLogger(MyApp.class);
public static void main(String[] args) {
BasicConfigurator.configure(); // default logging level is debug
Bar bar = new Bar();
bar.doIt();
}
}
and the second class in different package
package mypackage;
import org.apache.log4j.Logger;
public class Bar {
static Logger logger = Logger.getLogger(Bar.class);
public void doIt() {
logger.debug("Did it again!");
}
}
So what will be the level of logger in class Bar?
MyApp is in default package. Note that it is not recommended to use default package as has been answered in this question.
I think it is impossible to define a custom <logger> for the default package, so it must be <root> applied.
Unless you define a custom <logger> for mypackage.Bar, <root>also applies for that class.
Apart from the fact that they both may be ruled by <root>, MyApp and Bar are unrelated when it comes to log configuration.

How to add "import" statements from templates in IntelliJ?

I have defined the following live template in IntelliJ:
private static final Logger log = LoggerFactory.getLogger($CLASS_NAME$.class);
I use it to insert logger variable to a class.
Is it possible to define so that template also adds
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
to the file if these definitions are still absent?
Define it fully in the Live template:
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger($CLASS_NAME$.class);
and IntelliJ should auto reformat the expression to an import. (Assuming you already have the lib JAR downloaded and configured with IntelliJ).
Edit: As comment says: the Shorten FQ Names check-box should be checked (which it is by default)
Tested with IntelliJ IDEA 15.0.4
Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}

How to define template to automatically create logger whenever creating any class with corresponding type?

Could you help me define code preset/template so that whenever I create any class the line would be inserted as well. How to do it in IntelliJ?
private Logger LOGGER = LoggerFactory.getLogger(TheClassWithinWhichContained.class);
E.g.
#RestController
public class EndPointsController {
// after I defined the class IntelliJ should suggest me/or forcefully create
private Logger LOGGER = LoggerFactory.getLogger(EndPointsController.class);
}
Also correct me if I am wrong but I don't follow static notation for loggers as within IoC any component is singleton therefore there is ever going to be only one instance?
Found the solution myself:
Search in settings for "File and Code Templates"-> Class:
Replaced existing with slightly modified version:
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ${NAME} {
private Logger LOGGER = LoggerFactory.getLogger(${NAME}.class);
}
Not sure everyone is same lazy as I am but... :-) Hopefully it helped somebody.

how to generate the instance for logger?

Here is my code
package com.my;
import org.apache.log4j.spi.LoggerFactory;
import java.io.*;
import java.util.logging.*;
public class Log {
public static void main(String[] args) {
try{
FileHandler hand = new FileHandler("vk.log");
Logger log = Logger.getLogger("log_file");
log.addHandler(hand);
log.warning("Doing carefully!");
log.info("Doing something ...");
log.severe("Doing strictily ");
System.out.println(log.getName());
}
catch(IOException e){
System.out.println(e)
}
}
}
Your code should work if you delete the superfluous log.getLogger(""); statement and fix the imports.
A couple of comments:
If you have multiple loggers you can selectively turn them on and off. It is conventional to create multiple loggers based on class or package names; e.g.
Logger log = Logger.getLogger(this.getClass());
or
Logger log = Logger.getLogger(SomeClass.class);
You are instantiating and associating the handler programmatically. It is a better idea to put the logging configurations into an XML or properties file, and use one of the configurers to load it and wire up the logging handlers. This allows you ... or the user ... to adjust the logging without modifying your code.
You should probably READ the log4j introduction document that explains the above and other things about using log4j.
The above assumes that you were trying to use log4j. Is you are really trying to use java.util.logging, some details are not exactly right. (And, IMO, you would be better off with using log4j or one of its offspring.)
Your code is more or less fine (check the imports) and should work correctly if you remove the line:
log.getLogger("");
A working implementation of your class would then be:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class test {
public static void main(String[] args) {
try {
FileHandler hand = new FileHandler("vk.log");
Logger log = Logger.getLogger("log_file");
log.addHandler(hand);
log.warning("Doing carefully!");
log.info("Doing something ...");
log.severe("Doing strictily ");
System.out.println(log.getName());
} catch (IOException e) {
// Handle error.
}
}
}
Can you explain further your problem?
Here are a couple suggestions.
Watch your imports, you are mixing
Log4j or java.util.logging imports
no need to call getLogger() twice
Do something with your exceptions,
even if that means using a
System.out.println() e.printStackTrace() in this test
case. If there were problems thrown,
you were hiding them.

Categories

Resources