Spring boot wont call my dao [duplicate] - java

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 4 years ago.
I am getting simple Null pointer exception which I am unable to resolve.
Have tried debugging the application but it just wont go in the dao class where i want it to go. It shows : Unable to Install breakpoint and Absent Line control message. But as i learned from other questions on stack overflow this message was to be ignored ,so that I did.
Details for issue:
Exception :
in test controller
in create Service
at com.service.DesignerService.create(DesignerService.java:20) at
com.controller.HomeController.test(HomeController.java:26) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)in create service java.lang.NullPointerException
My controller method :
#GetMapping("/test")
public String test() {
System.out.println( "in test controller");
DesignerService obj = new DesignerService();
try {
obj.create();
} catch (Exception e) {
e.printStackTrace();
}
return "index";
}
My service calling :
public void create (){
System.out.println("in create service");
Designer designer = getDesigner();
designerDao.createDesigner(designer);
}
And Dao where the debugger never reaches
public void createDesigner(Designer designer) {
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
String id = String.valueOf(session.save(designer));
System.out.println("Designer ID :"+id);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
}
}
Please help me run this project . Many thanks in advance

Instead of creating a object why don't you Autowire your service using
#Autowired
private DesignerService obj
and where did you initialise this object designerDao

Related

How to disable springboot authentication for internal method invoke. [AuthenticationCredentialsNotFoundException]

I was trying to invoke all the controller methods when the service is up to warmup the cache.
But our methods has some permission control like:
#PreAuthorize(value = "hasPermission(#securedObject.application(), 'READ_PRODUCT')
The way how I invoke methods is like this:
private void adaptAndExecute(HandlerMethod handlerMethod, Map requestParas, List<Future> taskStaus) {
Object[] parameters = adaptParas(handlerMethod.getMethodParameters(), requestParas);
Object controllerInstance = applicationContext.getBean(handlerMethod.getBeanType());
taskStaus.add(pool.submit(() -> {
try {
handlerMethod.getMethod().invoke(controllerInstance, parameters);
} catch (Exception e) {
logger.warn("invoke method failed.", e);
}
}));
}
But I got this errors:
Caused by: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:336)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:200)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:58)
So, how can I disable the authentication if I invoke internally?
Thanks
Currently I have no idea about this.

i have a weird error of NullPointerException i ask how to fix it? [duplicate]

This question already has answers here:
how to resolve the NullPointerException in JEE? [duplicate]
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm beginner in JEE and i'm trying to fetch object from my db but i has encountered an error of nullpointerexception, i tried to locate the origin of the nullpointerexception(i understood that the connection passed as null) by System.out.println() but i failed, i forgot to tell you that i have class singletonconnection for connection and i call it in my function by .getconnection() also i add a jdbc driver (version 8.0.18) to the project build path(i ask if this error can be due to the jdbc driver version??),,
please if someone can help and thanks in advance.
here is the function that connects to the db and brings objects where i have the error that i told you about in line PreparedStatement ps=connection.prepareStatement("req")
System.out.println("connection");
Connection connection=SingletonConnection.getConnection();
System.out.println(connection);
try {
PreparedStatement ps=connection.prepareStatement("SELECT * FROM PRODUITS WHERE DESIGNATION LIKE ?");
ps.setString(1, mc);
ResultSet rs=ps.executeQuery();
here is the error log
HTTP Status 500 – Internal Server Error
Type Exception Report
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.NullPointerException
dao.ProduitDaoImpl.produitsParMC(ProduitDaoImpl.java:48)
web.ControleurServelet.doGet(ControleurServelet.java:49)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
here is my singleton connection
public class SingletonConnection {
private static Connection connection;
//le block static charge la classe en mémoire lors de son appel
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try {
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/db-natal","root","");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
The error says the null pointer is in your Dao, and controller.
Try setting break points around each of the line numbers in each file to see what is happening in debug mode.
It should give you a good idea of what's going wrong.
Also are you setting the result set data to object variables??

JDBC connection not working with PowerMockito

I am trying to use PowerMockito to mock by DBUtil. Unlike typical testcase, I don't want to mock the db calls completely. Whenever Dbutil.getConnection() is called. I want to return the connection object to my local Database.
The simple jdbc connection code below is not working when i call from #BeforeClass method. But it works when I call from the java class.
public static Connection getConnection() throws Exception {
System.out.println("-------- Connecting to " + Constants.CONNECTION_STR + " ------");
try {
Class.forName(Constants.ORACLE_DRIVER_NAME);
}
catch (ClassNotFoundException e) {
throw new Exception("JDBC Driver not found... " + e);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("getConnection :: exp :: "+ e);
}
System.out.println("Oracle JDBC Driver Registered Sucessfully!");
Connection connection = null;
try {
connection = DriverManager.getConnection(Constants.CONNECTION_STR, Constants.USERNAME, Constants.PASSWORD);
}
catch (SQLException e) {
throw new Exception("Connection Failed!",e);
}
if (connection != null) {
System.out.println("Connected to Database Sucessfully, take control your database now!");
return connection;
}
System.out.println("Failed to make connection!");
return null;
}
My Testclass
#RunWith (PowerMockRunner.class)
#PrepareForTest(DbUtil.class)
public class MyUtilTest {
#Mock
private DbUtil dbUtil;
#InjectMocks
private MyUtil myUtil;
private static Connection myDBConn;
#BeforeClass
public static void beforeClass() throws Exception {
myDBConn = OracleJDBCConnetion.getConnection(); // This always throws invalid username/password exception.
}
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void testIsAdminUser() throws Throwable{
PowerMockito.mockStatic(DbUtil.class);
PowerMockito.when(DbUtil.getConnection()).thenReturn(myDBConn);
String accId= "TH123" ;
boolean isAdmin = MyUtil.isAdminUser(cloudAccGuid);
System.out.println("isAdmin : " + isAdmin);
//then
PowerMockito.verifyStatic(Mockito.times(1));
DbUtil.getConnection();
assertTrue(isAdmin);
//Finally I am closing my connection.
if(myDBConn!=null && !myDBConn.isClosed())
OracleJDBCConnetion.closeConnection(myDBConn);
}
}
The beforeClass method always throws below expection.
Connection Failed! java.sql.SQLException: ORA-01017: invalid username/password; logon denied
But the same code works, when i try from normal Java class.
Can anyone help in understanding whats wrong here?
I am using ojdbc6.jar and powermokito-1.5.6 and my Oracle database version is 11.2.0.4.0
Thanks.
Edit :
I found that #PrepareForTest annotation is causing the error. without the annotation connection is successful but mock does not work. can anyone help me in understanding what is happening? I am very new to these mocking stuff.
The problem with #PrepareForTest annotation is, it recursively creates stubs for all dependent classes. Since DBUtil class uses java.sql.Connection class , a stub is created for Connection class also.
So, When i try to create connection, it refers to stub class and throws expection.
Add #PowerMockIgnore annotation to the class,to avoid it. #PowerMockIgnore annotation tells the powermock not to create for the classes that falls under the given package.
#RunWith (PowerMockRunner.class)
#PrepareForTest({DbUtil.class})
#PowerMockIgnore({"java.sql.*"})
public class MyUtilTest {
...
}
This worked for me.

Simple Java web service issue

I want to create a webservice in Java that accesses a database stored in an external server. I have created a BeepWebService class containing the main information:
#WebService
public class BeepWebService {
private Connection conn = null;
private String url = "jdbc:mysql://xxxxxx.ipagemysql.com/";
private String dbName = "beep";
private String userName = "beep_user_name";
private String password = "pswrd";
private String db_str = " select Name beep.SW where Name = ";
public BeepWebService(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
}catch (Exception e) {
System.out.print("failed");
}
}
#WebMethod
public String returnFormat(#WebParam(name="input_value") String input){
String str = null;
String query = db_str+input;
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
str = rs.getString(2);
System.out.println(str);
}
rs.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
}
I have then created the publisher class, named BeepWebServicePublisher:
public class BeepWebServicePublisher {
public static void main(String[] args){
System.out.println("Web Service initiating...");
Endpoint.publish("http://xxxxxx.ipagemysql.com/", new BeepWebService());
}
}
Unfortunately after compiling successfully the two classes and run the application, the output message is 'failed' (meaning that the connection couldn't be estabilished with the database) followed by an exception error. This is the complete output:
Web Service starting..
failedException in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.HttpEndpoint.publish(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at com.BeepServicePackage.server.BeepWebServicePublisher.main(BeepWebServicePublisher.java:17)
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.net.httpserver.ServerImpl.<init>(Unknown Source)
at sun.net.httpserver.HttpServerImpl.<init>(Unknown Source)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(Unknown Source)
at com.sun.net.httpserver.HttpServer.create(Unknown Source)
... 6 more
As I am a novice in this field, can someone tell me if there is something wrong in the code or the problem may be with the server? Thanks!
Print out the entire stack trace; it'll give you more information than your "failed" message.
Where did you register the MySQL JDBC driver? I don't see it.
UPDATE: I'd recommend that you decompose the problem. Don't put the database code in the web service. Create an interface-based POJO that you can test off line. Get it working, then give an instance to the web service to use.
You have 99 problems, son. Start by fixing one at a time.
This is wrong:
private String db_str = " select Name beep.SW where Name = ";
You need a binding parameter:
private String db_str = " select Name beep.SW where Name = ?";
You need a PreparedStatement, not a Statement.
Then you want to bind the name you pass in.
You only have one column returned by the SELECT; why do you setString on column 2?
Wrong in so many ways.

Custom exceptions handling - java Web Services

Its my first time posting here so please be patient and correct me whenever necessary...
I am building simple web service-based application using NetBeans with GlassFish. NetBeans does help a lot in terms of generating code for new web services and their operations, one thing drives me mad though - web service exception handling. Operation like:
#WebMethod(operationName = "checkUserExist")
public String checkUserExist(#WebParam(name = "login") String login, #WebParam(name = "password") String password) throws LoginException {
String auth_code = "";
bk_end.Validate val = new bk_end.Validate();
boolean isValidated = val.check(login, password);
if(isValidated)
{
auth_code = val.return_AuthCode();
bank_services.CustomerSerice.setAuth_Code(auth_code);
return auth_code;
}
throw new LoginException("Something is wrong!");
}
and the exception class:
public class LoginException extends Exception
{
String message;
public LoginException(String message)
{
super();
this.message = message;
}
public String getErrorMessage()
{
return this.message;
}
}
throws a massive
Exceptions details : java.lang.reflect.InvocationTargetException
plus tons of other exceptions..
I realise it is a very much so nooby question, but after many hours of trying various things I just do not know what tot do.
I've read about the #WebFault thing but got no idea how to specify this correctly (attach my exception to a particular method..)
Please help, all ideas are more than welcome!
Exceptions that I'm getting:
Service invocation threw an exception with message : null; Refer to the server log for more details
Exceptions details : java.lang.reflect.InvocationTargetException
javax.servlet.ServletException: java.lang.reflect.InvocationTargetException
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:330)
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.invoke(WebServiceTesterServlet.java:106)
at org.glassfish.webservices.EjbWebServiceServlet.service(EjbWebServiceServlet.java:114)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.doFilter(ServletAdapter.java:1002)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.invokeFilterChain(ServletAdapter.java:942)
at com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:404)
...
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:301)
... 24 more
Caused by: bank_services.LoginException_Exception: excepts.LoginException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:145)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:123)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:93)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:144)
at $Proxy383.checkUserExist(Unknown Source) ... 29 more
Oh ok. You want to see the "Something is wrong" message.
So I think the ultimate problem here is that you are not using the standard detailMessage field in the Throwable. If you just pass the message to the base class (super(message);) then I bet you would see the exception in the trace. Did you try another Exception type such as just Exception?
You could also define the LoginException.toString() to be something like:
#Override
public String toString() {
String s = getClass().getName();
return (message != null) ? (s + ": " + message) : s;
}
Alternatively, you will need to do something like this:
try {
...
} catch (Exception e) {
if (e instanceof ServletException) {
e = e.getCause();
}
if (e instanceof InvocationTargetException) {
e = e.getCause();
}
if (e instanceof LoginException) {
System.err.println("Login exception returned message: "
+ ((LoginException)e). getErrorMessage());
} else {
System.err.println("Exception returned message: " + e);
}
}
But I think my recommendation is to use super(message); in your constructor.

Categories