Java ExceptionInitializationError in static Block - java

I am trying to call the URL retrieving method inside the static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.
I am trying to get a WSDL url from the config file. this configuration data stored DB.
static
{
URL url = null;
WebServiceException e = null;
try
{
url = getVertexConfiguration();
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
}
private static URL getVertexConfiguration() throws MalformedURLException
{
try {
configuration = configurationDAO.getByRefName("tax/vertex",
SecureSession.getUser().getDataDomain() != null ?
SecureSession.getUser().getDataDomain() : "app.cantata");
} catch (B2BTransactionFailed b2BTransactionFailed) {
}
Map<String, DynamicAttribute> vertexTaxConfig = configuration.getConfigs();
vertexWsdlUrl = vertexTaxConfig.get("vertexWsdlUrl").getValue().toString();
return new URL(vertexWsdlUrl);
}
}
I am getting static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

The root cause is that static block is the earliest step when setup as class level initialization which even ahead of constructor calling. That is to say your dependency in static block such as that configurationDAO has not initialized yet. You shouldn't use static for it. Instead, you should make it a normal Instance method.

Why should you even try this? I think your configurationDAO is not even initialized at the moment you're trying to access it.
As we discussed in the comments, I would definitely recommend you, author, to inject your dependencies correctly, like:
#Service
public class ConfigurationService {
private final ConfigurationDao configurationDao;
private URL url;
public ConfigurationService(ConfigurationDao configurationDao) {
this.configurationDao = configurationDao;
}
#PostConstruct
private void init() {
// your stuff here
}
}
Or you can even initialize your url in constructor:
#Service
public class ConfigurationService {
private final ConfigurationDao configurationDao;
private final URL url;
public ConfigurationService(ConfigurationDao configurationDao) {
this.configurationDao = configurationDao;
this.url = getVertexConfiguration();
}
private URL getVertexConfiguration() {
// your stuff here
}
}

You get ExceptioninInitializerBlock if there are some errors in the static initializer block. You handle only MalformedURLException, however, there are may be others.
You should add another catch for all exceptions and see what happens there.
static {
URL url = null;
WebServiceException e = null;
try {
url = getVertexConfiguration();
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
} catch (Exception e) {
//real problem
}
}

That exception is a relaying mechanism for an error which occurred while running a static initializer. The exception should have a cause, which will describe the actual error. Per your description, above, there look to be three layers of exception: Error reporting from bean initialization, the ExceptionInInitializer exception, then the cause of the ExceptionInInitializer exception. The exception processing should display all three layers, but might not, which will make uncovering the base exception more difficult.
From the ExceptionInInitializer javaDoc:
* Signals that an unexpected exception has occurred in a static initializer.
* An <code>ExceptionInInitializerError</code> is thrown to indicate that an
* exception occurred during evaluation of a static initializer or the
* initializer for a static variable.
As a fall-back, you could put inside getVertexConfiguration a try-catch on Throwable, and have the catch block print out the stack:
private static URL getVertexConfiguration() throws MalformedURLException {
try {
// Code omitted
} catch ( Throwable th ) {
th.printStackTrace();
return null;
}
}

Related

Is using a lambda a safe, correct, and equivalent workaround for classes that do not implement AutoCloseable?

Background: I use the Java class InitialDirContext to access LDAP directories. Unfortunately, it does not implement interface AutoCloseable, so it cannot be used in try-with-resources blocks.
Here is the original code I wrote: (inspired by this answer)
final Properties props = new Properties();
// Populate 'props' here.
final InitialDirContext context = new InitialDirContext(props);
Exception e0 = null;
try {
// use 'context' here
}
catch (Exception e) {
// Only save a reference to the exception.
e0 = e;
// Why re-throw?
// If finally block does not throw, this exception must be thrown.
throw e;
}
finally {
try {
context.close();
}
catch (Exception e2) {
if (null != e0) {
e0.addSuppressed(e2);
// No need to re-throw 'e0' here. It was (re-)thrown above.
}
else {
throw e2;
}
}
}
Is this a safe, correct, and equivalent replacement?
try (final AutoCloseable dummy = () -> context.close()) {
// use 'context' here
}
I think the answer is yes, but I want to confirm. I tried Googling for this pattern, but I found nothing. It is so simple! Thus, I am suspicious it may not be correct.
Edit: I just found this answer with a similar pattern.
As explained in the other answer you linked to, it is not strictly equivalent because you have to either catch or throw Exception from AutoCloseable.close() and you must be sure not to do anything with context after the try block because it is not out of scope as if InitialDirContext directly implemented AutoCloseable. Still I agree with others that this workaround is quite nice.
Of course, you could also extend InitialDirContext and make it implement AutoCloseable directly or (for final classes) use a delegator pattern and wrap the target object.
package de.scrum_master.stackoverflow;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;
import java.util.Properties;
public class TryWithResourcesAutoCloseableWrapper {
public static void main(String[] args) throws NamingException {
final Properties props = new Properties();
props.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
variant1(props);
variant2(props);
variant3(props);
}
public static void variant1(Properties props) throws NamingException {
final InitialDirContext context = new InitialDirContext(props);
try (final AutoCloseable dummy = context::close) {
lookupMX(context);
}
catch (NamingException ne) {
throw ne;
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void variant2(Properties props) throws NamingException {
final InitialDirContext context = new InitialDirContext(props);
try (final MyCloseable dummy = context::close) {
lookupMX(context);
}
}
public static void variant3(Properties props) throws NamingException {
try (final MyInitialDirContext context = new MyInitialDirContext(props)) {
lookupMX(context);
}
}
private static void lookupMX(InitialDirContext context) throws NamingException {
System.out.println(context.getAttributes("scrum-master.de", new String[] { "MX" }));
}
public interface MyCloseable extends AutoCloseable {
void close() throws NamingException;
}
public static class MyInitialDirContext extends InitialDirContext implements AutoCloseable {
public MyInitialDirContext(Hashtable<?, ?> environment) throws NamingException {
super(environment);
}
}
}
A few more thoughts about how to use these workarounds:
Both variant1 and variant2 come at the cost of dummy objects which inside the try block you will never use, unless you cast them to InitialDirContext first. Instead, you could directly use the outer context objects, of course, which is also what you suggested.
In variant3 the auto-closable context object directly has the correct (sub-)type, so you can actually work with it seamlessly without casting or dummy object. This comes at the cost of a special subclass.

How to handle while throwing multiple custom exception

From a single method trowing two different custom exceptions based on the condition. While creating a custom exception passing two things one is an error message and another one is error code as a string. But I'm unable to get the error based on the error code. getting an error while calling processErrorCodes() method. Could anyone please help me in fixing this.
// BackgroundException is a custom EXCEPTION
public class BackgroundException extends Exception {
private static final long serialVersionUID = 4664456874499611218L;
private String errorCode="Unknown_Exception";
public BackgroundException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}
// Similarly I have InvalidException custom exception
public class MyExceptionTest {
public void methodTest(){
String policyId =null;
String policyNotification = null;
String policyStatus = null;
try {
if(policyNotification !=null) {
if(policyStatus!=null) {
if(policyId!=null) {
}
else{
throw new InvalidException("Policy ID Is Null","POLICY_ID");
}
}else{
throw new BackgroundException("Policy Status Is Null","POLICY_STATUS");
}
}
else{
throw new BackgroundException("Policy Notification Is Null","POLICY_NOTIFICATION");
}
} catch (BackgroundException | InvalidException e ) {
// TODO Auto-generated catch block
try {
processErrorCodes(e);
} catch (MyExcep e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.getMessage();
}
}
private static void processErrorCodes(Exception e) throws BackgroundException,InvalidException {
switch(e.getErrorCode()){
case "POLICY_NOTIFICATION":
System.out.println(e.getMessage());
throw e;
case "POLICY_ID":
System.out.println(e.getMessage());
throw e;
case "POLICY_STATUS":
System.out.println(e.getMessage());
throw e;
default:
System.out.println("Unknown exception occured, lets log it for further debugging."+e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
MyExceptionTest mt = new MyExceptionTest();
mt.methodTest();
}
}
I just want to handle those exceptions based on the error code.
You need a common superclass for all your custom exceptions, let say MessageCodeException, extending Exception and the accept this super class type as a parameter inside of your processErrorCodes method
public abstract class MessageCodeException extends Exception {
public abstract String getCode();
// you can have a same abstract method for message
}
public class BackgroundException extends MessageCodeException {
// ...
}
public class InvalidException extends MessageCodeException {
// ...
}
//and now the process method will look like
private static void processErrorCodes(Exception e) throws ... {
// ...
}
That's abvious that for current implementation you cannot access code field, because Exception class interface does not provide anything like this
BTW it seems to be very bad idea to create Exception driven business validation logic. Wouldn't it be better to create some kind of ValidationResult object with list (lists) of errors/warning/successes and to process such validation result at the end? The purpose of the Exception existence is not to control application flow, but to force user to provide some support for critical situations (or to handle somehow unexpected situations with RuntimeException)

Sending application error message to your email

I want to send a message to notify the user when there is an exception occur in your application. I am wondering what is the best way to do it in Java?
In my program, I have a properties files call mail.properties. I declared some of the properties in this file. I successfully read the properties from my properties file. Now I need to detect an error in my program and send an error message to my email account
mail.properties
smtpServer = smtp.gmail.com
smtpUsername = myemail#gmail.com
smtpPassword = 123456
smtpPort = 465
In my main method, I have declared my properties file. I call this main.java
public class main{
private static String smtpServer;
private static String smtpUsername;
private static String smtpPassword;
private static String smtpPort;
public static void main (String[] args){
//Method for initialize the properties
initialize();
//Code go here (Sending message and stuff)
try{
}
catch(Exception ex)
{
}
}
private static void initialize() throws Exception{
//loadProperties is where I check and get the properties file (no need to worry about it
Properties props = PropertiesUtil.loadProperties("mail.properties");
smtpServer = props.getProperty("smtpServer")
smtpUsername = props.getProperty("smtpUsername")
smtpPassword = props.getProperty("smtpPassword")
smtpPort = props.getProperty("smtpPort")
}
}
The Best Practice is create a RuntimeException, throw that exception upto top of the layer. at the top of the layer pass exception to the utility and send the exception message as email body.
Maybe you want notify error only when they are RuntimeException subclases because they indicate an unexpected error that you are not controlling.
Exception is too spread and you will notify to the user with anything error condition. I suggest you catch RuntimeException and only some checked exceptions.
public class Main {
public static void main(String[] args) {
try {
Job job = new Job();
job.doSomething();
} catch (RuntimeException | MustNotifyException re) {
sendMessage();
}
}
public static void sendMessage() {
}
}
class Job {
void doSomething() throws MustNotifyException {
}
}
class MustNotifyException extends Exception {
}

JUnit testing with annotations

Hey all I am trying to get these Unit tests to fail but can't it uses annotations, which is new to me. Any ideas would be great!
I have been trying all sorts of ways to get them to fail by either setting the test class variables to null, or trying to use if/else statements in the minimum test, but they always come out passing. Is this correct?
public class ValidationServiceTest extends BaseServiceTest {
ValidationService validationService;
ValidationException ve;
TestDto test;
Field f;
#Before
public void setup() {
validationService = new ValidationService();
ve = null;
}
#Test
public void validateNotNull(){
try {
validationService.validate(ve, test.xx);
assertNotNull("testing notNull()", ve);
} catch (Exception e) {
}
}
#Test
public void validateMin(){
try {
validationService.validate(ve, test.xy);
if(test.xy > f.min()){
assertTrue("testing min()" , test.xy > -1);
}
} catch (Exception e) {
}
}
public class TestDto{
#Field(notNull=true)
public Integer xx = null;
#Field(min=2)
public Integer xy = -5;
}
}
Do not catch Exception, mark test method with throws Exception instead.
The test field is never initialized in your test, which means it's null. This causes NullPointerException whenever you try to access fields of test. The assertion line is skipped and exception is suppressed in the catch clause. Removing the try/catch block and marking test method with throws Exception instead will cause the test to report error and you will see what's wrong instantly.

How can I create a static final java.net.URL?

My question is simple. I'm trying to make a set of java.net.URLs that are public static final, so that any class can access them from any context, as these URLs won't change during runtime. However, when I try to create them, I get a compiler error telling me that I must catch or declare thrown a java.net.MalformedURLException, but that is impossible outside a method. Is there any way to circumvent such a constructor that throws a non-java.lang Throwable?
Some dummy code below to visualize my problem:
public class Main
{
public static final java.net.URL STATIC_URL = new java.net.URL("http://example.com/");
public static void main(String[] args)
{
GUI gui = new GUI();
gui.setVisible(true);
}
}
public class GUI extends java.awt.Window
{
public GUI()
{
add(new java.awt.Label(Main.STATIC_URL.toString()));
}
}
If you try to compile this, it will tell you that you can't because of line 3. Hence my question.
An "alternative" which I'd prefer to #HosamAly method:
private static final java.net.URL STATIC_URL = makeUrl("http://www.example.com");
public static java.net.URL makeUrl(String urlString) {
try {
return new java.net.URL(urlString);
} catch (java.net.MalformedURLException e) {
return null; //Or rethrow an unchecked exception
}
}
Use a static initializer:
public class Main {
private static final java.net.URL STATIC_URL;
static {
java.net.URL temp;
try {
temp = new java.net.URL("http://www.example.com");
} catch (java.net.MalformedURLException e) {
temp = null;
}
STATIC_URL = temp;
}
}
Note: The usage of a temporary variable is required to avoid a compilation error about assigning to the final static field twice. If the field is not final, the assignment could be done directly.
If you're sure you want to hardwire a URL. Are you sure? java.net.URL is one of the most comprehensively broken classes in the JDK. In regards to use as a "constant", there is DNS lookup involved and it uses a mutable static (albeit one guarded by a security check, if you have a SecurityManager installed).
If it's just one, a static initialiser should be fine.
private static final java.net.URL STATIC_URL;
static {
try {
STATIC_URL = new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
(Note, you can't qualify the static field name with the class name.)
Note: You really do not want a null - throw an error of some sort and stop the class loading. I've made the constant private as it really isn't the sort of thing you want dependencies on.
If you have lots, then a method for the common code and assignment at the site of the definition is appropriate.
private static final java.net.URL STATIC_URL = constantURL("http://example.com/");
private static URL constantURL(String str) {
try {
return new java.net.URL("http://example.com/");
} catch (java.net.MalformedException exc) {
throw new Error(exc);
}
}
Again, no nulls!
The only way I got this to compile is by removing final and using the static initializer block.
/**
*
*/
package com.neurologic.example;
import java.net.MalformedURLException;
import java.net.URL;
/**
* #author The Elite Gentleman
* #since 06 December 2011
*
*/
public class StaticUrlTest {
public static URL url = null;
static {
try {
url = new URL("http://www.google.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}

Categories