Category Archives: Programming

java.lang.NoSuchMethodError javax.servlet.ServletContext.getVirtualServerName()

Recently while working on my Spring Boot project, I came across an error method not found getVirtualServerName. This error was very frequent and bothersome. During the execution of Spring Boot project, I ran into NoSuchMethodError javax.servlet.ServletContext.getVirtualServerName() exception.  Despite going through maven dependency, it was harder to find out where the servlet-api jar was coming into my project build path. In my handling exceptions post, I showed how to handle exceptions better.

getVirtualServerName

Issue –

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122) [na:1.8.0_91]
at java.util.concurrent.FutureTask.get(FutureTask.java:192) [na:1.8.0_91]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:911) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:890) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1403) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393) [tomcat-embed-core-8.5.6.jar:8.5.6]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.6.jar:8.5.6]
... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.6.jar:8.5.6]
... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.authenticator.NonLoginAuthenticator[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:170) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.6.jar:8.5.6]
... 8 common frames omitted
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
at org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1125) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.6.jar:8.5.6]
... 10 common frames omitted

Reason

Depending on the build path, servlet-api jar that exists is not the right version. If it is older than 3.1, it doesn’t contain method getVirtualServerName().

How did I resolve this issue?

I describe the solution separately, but how I analyzed the issue here. I went through servlet-api jar and tried to find the class ServletContext that contains this method. But the Jar file that I had in my project, didn’t contain this method. That’s why the issue. Then it was simple to figure out based on maven dependencies. Once I had a dependency tree, I was able to nail down the dependency that was bringing the old version of servlet-api jar.

Solution –

  1. Change the version of servlet-api jar
  2. Considering this is a spring-boot project, provide a version of tomcat instead of using default tomcat 8.x which spring-boot provides.
  3. In my case, the fix was to remove javaee.jar from the build path which was bringing servlet-api of an older version. When I changed the Java runtime library from 1.8 to 1.7, the project ran like a charm.

Conclusion

In this post, I showed how to resolve the error getVirtualServerName in ServletContext. If you enjoyed this post, subscribe to my blog.

 

 

 

Avoid common mistakes when handling exceptions

During vulnerability scanning, we figured out there were a lot of exceptions handled through the print statement. That’s not a very efficient way of handling exceptions.

Print statements are still better than not writing anything to handle. That’s known as swallowing an exception. A good approach to handle exceptions is to write some way to log those exceptions or throw those exceptions with stack trace during runtime. In this post, I showed some ways of handling exceptions.

What are the exceptions?

Exceptions are error events. These events happen during the runtime of a program. This generally disrupts the flow of the program.

There are three components to exception handlers – try, catch, and finally.

try – This part of exception handling contains code that will be executed during every flow.

catch – If code in try part throws a runtime exception, that will be caught in catch part.

finally – This contains the code you want to execute after trying part of the execution is done. This ensures that finally block is executed even when unexpected exceptions occur. It is mostly used to clean up resources.

Types of Exceptions 

  • Unchecked Exceptions – Exception types that are direct or indirect subclasses of a class RuntimeException , those are the unchecked exceptions.
  • Checked Exceptions – Exceptions that inherit Exception class are known as checked exceptions. RuntimeException are also extended from Exception , but client code doesn’t have to handle them, while Checked exceptions have to be handled by catch or throws clause.

How to handle Exceptions

What exceptions to use? Checked or Unchecked?

In case the code doesn’t know what to do if an exception is thrown, it should be an unchecked exception. If code using an exception knows what to do to recover from that exception along with logging that information, that should be checked exception.

Preserve encapsulation

Don’t propagate an exception from the data access layer to the business object layer.
Example – SQLException is a RuntimeException. If the data access layer throws this exception in the following manner, the catch block will not do anything but will suppress it.

public void dataAccessCode()
{
    try
    {

    }
    catch (SQLException ex)
    {
        ex.printStacktrace();
     }
}

On the other hand, to preserve encapsulation, the same runtime exception can be converted into another unchecked exception like below

public void dataAccessCode()
{
    try
   {

   }
   catch (SQLException ex)
   {
      throw new RuntimeException(ex);
    }
}

Best practices for Exceptions

1) Use finally block for cleaning the code
2) Do not ignore or suppress an exception
3) Log exceptions once
4) Do not use exceptions for flow control

References

  1. Best Practices for Exceptions
  2. Checked Vs Unchecked Exceptions

 

SSO with PingFederate using SAML

Ping Federate is a third party vendor that provides capabilities for Single Sign On (SSO) using either SAML or WS-Federation protocol. I recently worked on a project where we had to provide these capabilities to applications.

Here I document how I achieved this through SAML protocol.

SAML stands for Security Assertion Markup Language and it is an open-standard data format for exchanging information related to authentication and authorization (Source-Wikipedia – SAML ). SAML is used mostly for web browser SSO.

Ping Federate plays the role of an Identity Provider or Service Provider depending on what purpose you are using it for.

In this particular post, we will be seeing how an SP-initiated SSO works with Ping Federate.

SSO with Ping  Federate-

Create an SP connection in Ping Federate

Firstly, create a unique connection for your SP service in Ping Federate, this unique connection will be identified by Ping Federate with Entity Id which you will create in Ping Federate. Provide an Assertion Consumer Service (ACS) URL in your connection in Ping Federate. Basically, Ping will send a response back at ACS URL. There is a step-by-step process to create an SP connection in Ping Federate.

You will need to specify a protocol for this connection. For our post purposes, we are using SAML 2.0. What binding to use? Post, Redirect, Artifact, SOAP. For this post, we will be using Post or Redirect.

During the process, you also provide an IdP adapter in the connection. IdP adapter is nothing but a way of authentication – how do you want a user to be authenticated? Through an HTML form or Windows Account?

You will also need to provide a signing certificate if you are going to send a signed login request to Ping Federate.

Once you create a connection, you set that connection as ACTIVE in ping.

Changes on SP Side

Now when you send a Login request to ping, it will post on the protocol endpoint URL from the ping side. So Ping provides certain static endpoints for your connection. If Ping is installed on a server called abc.com, the endpoint for Ping will be abc.com/idp/SSO.saml2 and this is where you will post your login request. Here is a sample Login request looks like


<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_bec424fa533dj2ff020502892fghjjf221" Version="2.0" IssueInstant="2016-02-10T11:39:34Z" ForceAuthn="false" IsPassive="false" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="http://abc.bloodycoders.com/login/saml2/sp/AssertionConsumerService.php">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
urn:mace:bloodycoders.com:services:abc.bloodycoders.com
</saml:Issuer>
<samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" SPNameQualifier="abc.bloodycoders.com" AllowCreate="true" />
<samlp:RequestedAuthnContext xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Comparison="exact">
<saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
</saml:AuthnContextClassRef>
</samlp:RequestedAuthnContext>
</samlp:AuthnRequest>

Ping Federate will verify the request based on entity id and where it needs to send the response. If the request is valid, it will send a response. On the SP side, you then verify the response if it is coming from an authentic source.

(I have not included a response back from Ping Federate for post purposes).

If you enjoyed this post, send me a response here.

Thread-safe code

Yes, just like every other programmer, I have been asked “Is this code thread safe?” and many times I have pondered in my head , what that actually means. Honestly I am not competent enough in multi-threading programming and even answering this question. But then there comes a time when you learn about this and say “Yes, the code is thread safe and it will execute correctly in case of simultaneous execution by multiple threads.”

Wikipedia says about thread-safety

“A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time “

Most of the problems arise in multi-threaded environment when accessing shared data.

Here is an example of the code which can be safe in a single-threaded environment, but not in multi-threaded.

public class Counter
{
   private static int count = 0;
   public static int incrementCount()
   {
      return count++;
   }
}

count is a shared integer variable here. In a multi-threaded environment, it can lose the right value during the update operation. Increment operation for count performs read, add, and update. In case if two threads are accessing incrementCount method and not synchronized, they can cause the wrong value of count.

How to make this code thread-safe

public class Counter
{
   private static int count = 0;
   public static synchronized int incrementCount()
   {
      return count++;
   }
}

synchronized adds that mutual exclusion between threads while accessing incrementCount method. So at one time, only one thread can access the method. Instead of making the whole method synchronized, only part of the code can also be made synchronized.

Conclusion

I showed how we can write thread safe programming. If you enjoyed this post, subscribe to my blog. If you want to learn more about thread safety, read this post.