How to test RESTful application? - java

I have an application example with a service:
RestApp.java
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/webapi")
public class RestApp extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>();
classes.add(MessageService.class);
return classes;
}
}
MessageService.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
#Stateless
#Path("/messages")
public class MessageService {
#Inject
private MessagesManager messagesManager;
#GET
#Path("all")
#Produces({MediaType.APPLICATION_JSON})
public List<Message> getMessages() {
return messagesManager.getMessages();
}
}
and the service depends on the singleton MessagesManager.java:
import javax.ejb.*;
import javax.inject.Singleton;
#Singleton
#Startup
#ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class MessagesManager implements Serializable {
private List<Message> messages = new ArrayList<>();
#Lock(LockType.READ)
public List<Message> getMessages() {
messages.add(new Message(1, "message text"));
return messages;
}
}
and this app works fine. But during the test occurs error of injection:
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=MessagesManager,parent=MessageService,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1232089028)
Test code is:
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;
public class RestAppTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(MessageService.class);
}
#Test
public void testGet() {
final Response response = target("messages/all").request().get();
assertEquals(200, response.getStatus());
}
}
Why it happens and how to fix it?

The class MessagesManager is missing in an application context. Add the class to configure method like this:
return new ResourceConfig(MessageService.class, MessagesManager.class);

You need couple of things
1> Well formed JSON structure for your REST API
2> Some kind of REST client such as advanced REST client for chrome, Mozilla etc which can be used as a plugin. POSTMAN is also a useful tool

Related

Springboot adding a "_class" field in POST Request

I am new to SpringBoot and I am trying to connect my SpringBoot App to MongoDB. The GET Request is working completely fine but the POST Request is adding a "_class" field in the data which I don't want. I did some searching and found that I have to add a #Configuration class to solve this issue but when I added the #Configuration class, I am getting the following error :
Field mongoDbFactory in com.example.demo.configuration.MongoConfig required a bean of type 'org.springframework.data.mongodb.MongoDbFactory' that could not be found.
My Confuguration class code is as follows :-
MongoConfig.java :-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
#Configuration
public class MongoConfig {
#Autowired
private MongoDbFactory mongoDbFactory;
#Autowired
private MongoMappingContext mongoMappingContext;
#Bean
public MappingMongoConverter mappingMongoConverter() {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver,
mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
}
Controller.java :-
import com.example.demo.model.Todo;
import com.example.demo.services.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class Controller {
#Autowired
private TodoService todoService;
#GetMapping("/")
public List<Todo> getTodos() {
return todoService.getTodos();
}
#PostMapping("/")
public Todo addTodo(#RequestBody Todo todo) {
return todoService.addTodo(todo);
}
}
TodoService.java :-
import com.example.demo.model.Todo;
import java.util.List;
public interface TodoService {
public List<Todo> getTodos();
public Todo addTodo(Todo todo);
}
TodoServiceImplementation.java :-
import com.example.demo.model.Todo;
import com.example.demo.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class TodoServiceImplementation implements TodoService{
#Autowired
private TodoRepository todoRepository;
#Override
public List<Todo> getTodos() {
return todoRepository.findAll();
}
#Override
public Todo addTodo(Todo todo) {
return todoRepository.save(todo);
}
}
It is asking me to do the following action :-
Consider defining a bean of type 'org.springframework.data.mongodb.MongoDbFactory' in your configuration.

How to wire classes and objects in SpringBoot

Have SpringBoot Java app with different classes. I am not able to inject the dependencies and initialize/access the object of one class into another . Have seen the spring doc and used the annotations (#component,#Autowired etc. ), still there is an issue.
following are the classes.
Main Class ()
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class CostmanagementApplication {
public static void main(String[] args) {
SpringApplication.run(CostmanagementApplication.class, args);
}
}
Controller class
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Component
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
//here not able to access the getToken() method
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}
RequestToken Class
package com.test;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class RequestToken {
public String getToken() throws IOException, InterruptedException {
// TODO Auto-generated method stub
// code to get the token
return token;
}
}
now eventhough , I have all annotation in place , not getting why the getToken() method is not accessible in controller class using rt object. please suggest
Okay, let's go in order.
First of all, all the annotations #Service, #Controller and #Repository are specifications from #Component, so you don't need to specify #Component and #Controller in your HighChartsController.
Actually, if you check what the annotation #Controller definition is, you'll find this:
#Component
public #interface Controller {
...
}
Secondly, I don't really know what do you mean with that you aren't able to access the getToken() method, but as you wrote it seems you tried to access to that method as an static method.
You're injecting the object, so you use the methods of the objects like in plain Java: rt.getToken(). The only difference is that the RequestToken object will be already initialized at the moment you call it.
package com.test;
import javax.swing.text.rtf.RTFEditorKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HighChartsController {
#Autowired
private RequestToken rt;
#GetMapping("/costdata")
public static String customerForm(Model model) {
String token = rt.getToken();
...
model.addAttribute("costdata", new CostDataModel());
return "costdata";
}
}

Jersey 3 - Configuring binding with bindFactory

Using Jersey 3.0.1, I am struggling to get binding working.
I have this binding module with the factories below:
public static class MyBinder extends AbstractBinder {
#Override
protected void configure() {
LOG.info("Attempting to configure binder");
bindFactory(DataSourceFactory.class).to(HikariDataSource.class).in(Singleton.class);
bindFactory(JooqConfigFactory.class).to(Configuration.class).in(Singleton.class);
bindFactory(DSLContextFactory.class).to(DSLContext.class).in(Singleton.class);
LOG.info("Configured binder");
}
}
public static class DataSourceFactory implements Supplier<HikariDataSource> {
#Override
public HikariDataSource get() {
...
return new HikariDataSource(config);
}
}
public static class JooqConfigFactory implements Supplier<Configuration> {
#Inject
HikariDataSource dataSource;
#Override
public Configuration get() {
...
return conf;
}
}
public static class DSLContextFactory implements Supplier<DSLContext> {
#Inject
Configuration config;
#Override
public DSLContext get() {
return DSL.using(config);
}
}
Then I have the setup for my Servlet using embedded Jetty:
public void start() throws Exception {
int port = appConfig.getProperty("http.port", 9998);
Server server = new Server(port);
ServletContextHandler ctx =
new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
ctx.setContextPath("/");
server.setHandler(ctx);
ResourceConfig config = new JerseyConfig();
ServletHolder servlet = new ServletHolder(new ServletContainer(config));
servlet.setInitOrder(1);
ctx.addServlet(servlet, "/*");
server.start();
server.join();
}
public static class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("com.sodonnell.jersey", "jersey.config.server.provider.packages");
register(new MyBinder());
}
}
And in my Rest service I simply try to inject a private instance variable:
public MyClass {
#Inject // javax.inject.Inject
private DSLContext dslContext;
}
However this dslContext is always null. I can see from the logs, that it prints the LOG.info("Configured binder"); message. However putting similar logs in my factory classes show they never get called.
Has anyone got any idea what I am missing?
EDIT
To make things simpler, I created this class:
public class SimpleClass {
private static Logger LOG = LoggerFactory.getLogger(SimpleClass.class);
public SimpleClass() {
LOG.info("Call the simple class constructor");
}
Changed my binder module:
import com.google.inject.Injector;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.Properties;
import java.util.function.Supplier;
...
// This is a nested class
public static class MyBinder extends AbstractBinder {
#Override
protected void configure() {
LOG.info("Attempting to configure binder");
bind(new SimpleClass()).to(SimpleClass.class);
}
}
Then attempted to inject just SimpleClass:
package com.sodonnell.hdfs3.rest;
import com.sodonnell.hdfs3.SimpleClass;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import org.jooq.DSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
#Inject
private SimpleClass simpleClass;
...
But its still null, although I see both the log messages. There must be some fundamental setup I am missing.
Full cut down code with the SimpleClass example at:
github.com/sodonnel/jerseyBind
The answer is quite simple. You are using Jersey 3.0 which has switched to the new Jakarta naming. javax is thrown out the window - this includes javax.inject. All the javax package names have now been changed to jakarta. So to get the inject to work, the #Inject import should be
import jakarta.inject.Inject;
This change is part of the change of Java EE to Jakarta EE Starting from Jakarta EE 8 to Jakarta EE 9, all the namespacing has changed from javax to jakarta. So things like javax.servlet will now be jakarta.servlet. Weird, yes a huge breaking change with no backward compatibility.
In your case you have all the correct components to work with Jakarta (i.e. Jersey 3.0 and Jett 11), but you just need to make use of the new namespacing. Notice all the JAX-RS imports are now jakarta also.

How to use an EJB in a Web Services Java EE

I'm trying to use the methods that I have in a DAO interface. When i'm calling there in a Servlet, I have no problems, for example, if I test
#WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
//etc
#EJB
InterfacesDao dao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//dao.getUsers(); //works well
//System.out.println(dao); //will print the dao object correctly
Boolean logged = dao.login("myLogin","mystrongpassword"); //works
request.setAttribute("logged",logged);
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
//etc
}
But I want to use ajax and so pass by a WebServices.
I can test
#WebService
#Path("/users")
public class UserService {
#POST
#Path("/login")
#Produces("application/json")
public String login(#FormParam("login") String login, #FormParam("pwd") String mdp) {
return "Hello World" + login;
}
}
If I go to http://[...]/rest/users/login with an json object which contains a login and a pwd, I get Hello World theloginientered
But I need to use EJB
#WebService
#Path("/users")
public class UserService {
#EJB
InterfacesDao dao;
#POST
#Path("/login")
#Produces("application/json")
public String login(#FormParam("login") String login, #FormParam("pwd") String mdp) {
//System.out.println(dao); //dao null ?
//dao.getUsers(); //erros because dao null
Boolean logged = dao.login(login,pwd); //doesn't work
//I not arrive till here because NullPointerException error
return "Hello World" + login;
}
}
I tried to instance by passing the reference of the dao in my servlet to my Web Service, but doesn't work
I tried to have just 1 EJB in my WebService, init in constructor, and get it from my Servlet by a getter, but again null
I think I forgot a config for the EJB dependency injection but in my Servlet I do no more less.
Import for the web services
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.servlet.annotation.WebServlet;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.supinfo.interfaces.InterfacesDao;
import com.supinfo.servlet.Index;
Import for the Servlet
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.supinfo.interfaces.InterfacesDao;
Interfaces DAO Web side and EJB side
package com.supinfo.interfaces;
import java.util.List;
import javax.ejb.Remote;
import com.supinfo.entity.User;
#Remote
public interface InterfacesDao {
public boolean login(String login, String mdp);
public boolean signin(String login, String mdp);
public List<User> getUsers();
}
The Implementation
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.supinfo.database.PersistenceManager;
import com.supinfo.entity.User;
import com.supinfo.interfaces.InterfacesDao;
#Stateless
public class InterfaceDaoImpl implements InterfacesDao{
#Override
public List<User> getUsers() {
EntityManager em = PersistenceManager.getEntityManager();
Query query = (Query) em.createQuery("Select u FROM User u ");
List<User> persons = query.getResultList();
return persons;
}
#Override
public boolean login(String login, String mdp) {
EntityManager em = PersistenceManager.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> person = query.from(User.class);
query.where(cb.equal(person.get("login"), login)).where(cb.equal(person.get("mdp"), mdp));
List<User> persons = em.createQuery(query).getResultList();
//Boolean isEmpty = persons.isEmpty();
//return !(isEmpty == null ? false : isEmpty);
return !persons.isEmpty();
}
Thanks for reading
The import statements are not included in the sample code, but I assume that you are trying to use JAX-RS and not a WebService. In that case, you should delete the #WebService annotation.
Depending on the server (and version) you are using the injection of the dao will not instantly work using #EJB as annotation. You can however transform the JAX-RS endpoint to a #Stateless bean, that should take care of your injection problem.
In short use:
#Stateless
#Path("/users")
public class UserService {
#EJB // #Inject is also an option
InterfacesDao dao;
You may also want to use the newer #Inject annotation instead of #EJB.

Spring with JUnit Testing and Dependency Injection does not work

I try to use Springs own Dependency Injection in a Junit test case:
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.binarisinformatik.api.AppConfig;
import org.binarisinformatik.satzrechner.SatzRechner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=AppConfig.class)
//#SpringApplicationConfiguration(classes = {AppConfig.class})
public class SatzRechnerTest {
#Autowired
private SatzRechner satzRechner; //SUT
#Before
public void setUp() {
// AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SatzRechnerTest.class);
//satzRechner=context.getBean(SatzRechner.class);
}
#Test
public void addiere_satz_4komma6_zu_zahlwert_10() {
assertThat("Addition von \"4,6\" ergibt nicht 10!",
satzRechner.summe("4,6"), is(equalTo(10)));
}
Im testing a class names SatzRechner in which Spring should also autowire some variables. Here is my Class under test:
#Component
public class SatzRechner {
#Autowired //#Inject
private Rechner taschenRechner;
#Autowired
private Zahlenfabrik zahlenfabrik;
public Integer summe(String zeichenSatz) {
return taschenRechner.summe(zahlenfabrik.erzeugeZahlen(zeichenSatz));
}
}
And AppConfig.class which is using as Configurationfile looks like that:
#Configuration
#ComponentScan(value={"org.binarisinformatik"})
public class AppConfig {
}
What is here the problem?
If you want to use a Spring configuration class, this one must have beans definitions. Please find an example below :
Test class:
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.binarisinformatik.api.AppConfig;
import org.binarisinformatik.satzrechner.SatzRechner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=AppConfig.class)
public class SatzRechnerTest {
#Autowired
private SatzRechner satzRechner;
#Test
public void addiere_satz_4komma6_zu_zahlwert_10() {
assertThat("Addition von \"4,6\" ergibt nicht 10!",
satzRechner.summe("4,6"), is(equalTo(10)));
}
}
Configuration class :
You have to declare #Bean annotated methods. These beans are managed by Spring container.
#Configuration
public class AppConfig {
// Beans present here will be injected into the SatzRechnerTest class.
#Bean
public SatzRechner satzRechner() {
return new SatzRechner();
}
#Bean
public Rechner taschenRechner() {
return new TaschenRechner();
}
#Bean
public Zahlenfabrik zahlenfabrik() {
return new Zahlenfabrik();
}
}
Note : I let you properly handle returned types here and beans parameters (if present in your context).
There are two things you have to ensure before you run the test case successfully:
1) Classes SatzRechner, Rechner & Zahlenfabrik should be under "org.binarisinformatik" package
2) Classes Rechner & Zahlenfabrik should also be annotated with #Component as SatzRechner.

Categories