Class.forName(Driver.class) - jdbc

In context of making a database Connection, we normally import the required packages and use Class.forName() to load the required Driver classes by the classloader of the calling class.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
....
....
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(...);
Can not we simply drop off the Class.forName() as in this:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.*;
....
....
Connection con=DriverManager.getConnection(...);
My question is when the dependencies of a class are loaded by the same classloader that loaded the dependent class, by the same mechanism used with Class.forName(className) implicitly, the why to give Class.forName() explicitly. Just include the driver class in import statement.
Will the driver class not automatically loaded when it incounters the DriverManager.getConnection() line? com.mysql.jdbc package is in import statement.
Or do i need to add al line like
Class clazz=com.mysq.jdbc.Driver.class
to trigger the Class.forName() .

First, loading the driver class shouldn't be necessary anymore, because Java has a built-in service provider loading mechanism that looks in the jar files in the classpath to find available drivers.
Just importing a class is not sufficient to load it. All an import does is allow you, at compile time, to refer to the class using its simple name rather than its fully qualified name. But if you never actually load the class, it won't do anything.
You could indeed load the class without using reflection, but that means that you need to have tthe driver as a compile-time dependency, which is often unwanted: you shouldn't rely on database-specific classes from the driver, but only on standard JDBC interfaces. Not having the driver in the compile classpath makes that sure.

An import statement does not do anything at run-time. It is not even part of the compiled class. It just tells the compiler where to look for stuff.
A line like Class<?> dummy = com.mysql.jdbc.Driver.class will work, but then you have a compile-time dependency on the MySQL driver JAR file (which Class.forName does not have, but may not be a bad thing in the grand scheme of things).

As long as your driver is JDBC 4.0 compliant, you don't need the Class.forName().
Please read the introduction on DriverManager JavaDoc for how this has been handled.
Of cause, the driver still needs to be on the classpath. Which was true for Class.forName() as well (would've thrown ClassNotFoundException otherwise)

Related

package javax.annotation.security does not exist

I'm trying to start a Jersey/1.7 based project from scratch (as opposed to copying an existing project and adding new code on top, which is what my client normally does) in order to learn how stuff works. I'm stuck in a very early phase, trying to process a simple HTTP request:
package com.example.foo.view.rest;
import javax.ws.rs.Path;
import javax.annotation.security.RolesAllowed; // package javax.annotation.security does not exist
#Path("user")
#RolesAllowed("valid-users") // cannot find symbol
public class UserService extends BaseService {
public UserService() {
super();
}
}
I've copied these files from another project:
asm-3.1.jar
jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
jersey-client-1.17.jar
jersey-core-1.17.jar
jersey-json-1.17.jar
jersey-multipart-1.17.jar
jersey-server-1.17.jar
jersey-servlet-1.17.jar
jettison-1.1.jar
jsr311-api-1.1.1.jar
Project authentication works with Oracle SSO (Oracle Identity Directory).
The only javax.annotation.security.RolesAllowed I can find is an interface and I can certainly not see an actual implementation anywhere in my codebase. In fact the whole javax.annotation.security package is missing. I don't even know what library is supposed to provide it.
I'd appreciate any hint, no matter how obvious it looks.
javax.annotation is part of java, but not included directly in the jre.
It is not included in jersey.
You have to add this jar to your project for it to work.

How can we access the java security package in Jmeter?

I need to access the security package in Java using Jmeter on Bean Shell. Is there anyway to do this ?
I have got error like this.
Sourced file: inline evaluation of: ``import android.util.Base64.*; import java.security.spec.X509EncodedKeySpec;
Help on this is useful!
I suspect the problem is with import android.util.Base64.* - android package is not part of Java. You probably meant to have
import java.util.Base64;
Note that you need to have Java 8

missing dependencies in latest spring security test

I need to resolve certain methods (status, jsonPath, content) mentioned in code shown below -
mockMvc.perform(MockMvcRequestBuilders.get("/api/token")
.with(getAuthentication(getOauthTestAuthentication()))
.sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.username").value("cominventor"))
.andExpect(jsonPath("$.token").value("my-fun-token"));
When I searched for related projects containing these methods, many of them are importing the following
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
The problem is that I am unable to find a counterpart in package spring-security-test with version 4.2.2.RELEASE
The closest options that could have worked but haven't are
import static org.springframework.test.web.servlet.ResultMatcher.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
The above don't contain the methods I am looking for. Any idea where should I look for these methods or their newer counterparts.
Everything worked out once I set the spring-security-test version to 4.0.2.RELEASE
I had the same problem, and I solved it importing the artifact
org.springframework.security:spring-security-test:4.2.3.RELEASE
I am using spring-boot-starter-test:1.5.3, and for some reason the folks at Spring decided not to include spring-security-test in its POM.

Java EE #Singleton EJB for cache

I am developping an application in Java EE, I would like to implement a cache using a #Singleton EJB. This caches, referencial data, so I only need retrieved once from the DB and then store it in memory.
I would like to know from an implementation point of view if this is correct, using a #Singleton EJB ? or could you recommend me another approach ? and also if this is correct from an OOP perspective ?
And the #Singleton EJB is for read-only, is there any concurrency issues I could encounter ?
Regards,
The approach is ok, but the drawback is that is it not simple to enhance the solution later - no nice interface.
But possible with every JavaEE server without any migration effort as it is standard JavaEE.
Another solution depends a bit on the server you use.
WildFly (community): you might use the internal infinispan subsystem and use is in a HashMap manner. You can simple use it local to start with and change the configuration to clustered (replicated or distributes) if the cache grow and you need more memory to cache it.
JBoss EAP (Enterprise Product): Here you can't use the Infinispan subsystem, technical it is possible but it is not supported. You need to use the additional JBossDataGrid (JDG) which is based on infinispan.
Here you have more options, same as above use the cache in the same JVM local or dist/repl. Or on a different instance with remote access to the cache - often fast enough but you have one remote access - but the JVM is complete separated from the server and can be started maintained different. Also the server and cache did not affect each others memory.
For other vendors you can use the JDG approach (or Infinispan as OpenSource) also.
As a quick and easy solution Singleton EJB can help, especially if catalogs whose values do not change.
Just consider your EJB Singleton establish the following:
Concurrency Management by Container
All methods for establishing LockType.READ accessed concurrently by any arbitrary number of clients
For example:
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
#Singleton
#Startup
#ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class InitializationBean {
#PostConstruct
public void initialize() {
// load data
}
#Lock(LockType.READ)
public List<String> getCatalog01() {
return null;
}
#Lock(LockType.READ)
public List<String> getCatalog02() {
return null;
}
}

Apache Felix: inherit import package org.osgi.service.cm

I have one bundle which has Import-Package org.osgi.service.cm. In this bundle there is only an interface ConfigurationInterface, that declares a couple of methods, one throws an org.osgi.service.cm.ConfigurationException. This bundle exports only its own package, lets say com.foo.bar.configuration.
Then I have other API bundles that have an interface for the service, ServiceInterface, that extends ConfigurationInterface, so they are importing the package com.foo.bar.configuration. Obviously there are also implementations bundle for these api that implement ServiceInterface, so they are importing org.osgi.service.cm because every implementations need to have the method that throws an org.osgi.service.cm.ConfigurationException.
Everything is working fine, the problems come out when I declare these services as optional, because when they are not available the framework tries to instantiate a proxy from the interface and I get a java.lang.ClassNotFoundException: org.osgi.service.cm.ConfigurationException. The framework suggests to add an import for 'org.osgi.service.cm' to the API bundle.
Is there a way to make this import available from the configuration bundle so that it is not necessary to add the import to every API?

Resources