I have an issue on instantiating servlet class wtih simple test application inserting records in DB using j7ee ejb 3.1 and jpa 2.1. I'm a newby to ejb and jpa and I'm trying to test a solution.
I'm using NetBeans 8.0.
I have separated layers for entity classes and for ejb.
I have entity class Doctor.java located in com.tsc.deo.entities (DEO is the name of application):
package com.tsc.deo.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author IK
*/
#Entity
#Table(name = "doctor")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Doctor.findAll", query = "SELECT d FROM Doctor d"),
#NamedQuery(name = "Doctor.findByIDDoctor", query = "SELECT d FROM Doctor d WHERE d.iDDoctor = :iDDoctor"),
#NamedQuery(name = "Doctor.findBySirname", query = "SELECT d FROM Doctor d WHERE d.sirname = :sirname"),
#NamedQuery(name = "Doctor.findByName", query = "SELECT d FROM Doctor d WHERE d.name = :name"),
#NamedQuery(name = "Doctor.findByPatientIDPatient", query = "SELECT d FROM Doctor d WHERE d.patientIDPatient = :patientIDPatient")})
public class Doctor implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "IDDoctor")
private Integer iDDoctor;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "Sirname")
private String sirname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "Name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "Patient_IDPatient")
private int patientIDPatient;
public Doctor() {
}
public Doctor(Integer iDDoctor) {
this.iDDoctor = iDDoctor;
}
public Doctor(Integer iDDoctor, String sirname, String name, int patientIDPatient) {
this.iDDoctor = iDDoctor;
this.sirname = sirname;
this.name = name;
this.patientIDPatient = patientIDPatient;
}
public Integer getIDDoctor() {
return iDDoctor;
}
public void setIDDoctor(Integer iDDoctor) {
this.iDDoctor = iDDoctor;
}
public String getSirname() {
return sirname;
}
public void setSirname(String sirname) {
this.sirname = sirname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPatientIDPatient() {
return patientIDPatient;
}
public void setPatientIDPatient(int patientIDPatient) {
this.patientIDPatient = patientIDPatient;
}
#Override
public int hashCode() {
int hash = 0;
hash += (iDDoctor != null ? iDDoctor.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Doctor)) {
return false;
}
Doctor other = (Doctor) object;
if ((this.iDDoctor == null && other.iDDoctor != null) || (this.iDDoctor != null && !this.iDDoctor.equals(other.iDDoctor))) {
return false;
}
return true;
}
#Override
public String toString() {
return iDDoctor + sirname + name + " | ";
}
}
I have the bean class:
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author IK
*/
#Stateless
#Named
public class DoctorSessionBean implements Serializable, DoctorSession, DoctorSessionLocal {
public DoctorSessionBean () {}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
#PersistenceContext
private EntityManager em;
// private Logger log = null;
public EntityManager getEntityManager() {
try {
// Context ctx = (Context) new InitialContext().lookup("java:comp/env");
// return (EntityManager) ctx.lookup("persistence/LogicalName");
return em;
} catch (Exception e) {
// Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
// throw new RuntimeException(e);
e.printStackTrace(System.out);
throw new RuntimeException(e);
}
}
public List<Doctor> getDoctors() {
return getEntityManager().createNamedQuery("Doctor.findAll").getResultList();
}
public void insertDBDoctor(Doctor doc) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
em.persist(doc);
em.getTransaction().commit();
em.close();
}
}
With Remote and Local interfaces:
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.util.List;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
/**
*
* #author IK
*/
#Remote
public interface DoctorSession {
public EntityManager getEntityManager();
public List<Doctor> getDoctors();
}
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.util.List;
import javax.ejb.Local;
import javax.persistence.EntityManager;
/**
*
* #author IK
*/
#Local
public interface DoctorSessionLocal {
public EntityManager getEntityManager();
public List<Doctor> getDoctors();
}
And I have a servlet which is trying to store new entity in DB (connect to DB works ok):
package com.tsc.deo.servlets;
import com.tsc.deo.beans.DoctorSessionBean;
import com.tsc.deo.entities.Doctor;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author IK
*/
#WebServlet(name = "TestUpdateDBServlet", urlPatterns = {"/TestUpdateDBServlet"})
public class TestUpdateDBServlet extends HttpServlet {
#EJB
private DoctorSessionBean doctorSessionBean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Doctor doc = new Doctor();
doc.setIDDoctor(8);
doc.setSirname("Материнка");
doc.setName("Оля");
doc.setPatientIDPatient(81);
doctorSessionBean.insertDBDoctor(doc);
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestUpdateDBServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestUpdateDBServlet at " + request.getContextPath() + "</h1>");
out.println(doctorSessionBean.getDoctors());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
After running the application the error message poped up in my browser:
"javax.servlet.ServletException: Error instantiating servlet class com.tsc.deo.servlets.TestUpdateDBServlet
In the root of cause it's said that it couldn't find DoctorSessionBean:
"javax.naming.NameNotFoundException: com.tsc.deo.beans.DoctorSessionBean#com.tsc.deo.beans.DoctorSessionBean not found"
What it the reason of this issue and how can I correct it?
Now GlassFish 4.0 in NetBeans is popping up the error message:
"SEVERE: The web application [/DEO] created a ThreadLocal with key of type [org.glassfish.pfl.dynamic.codegen.impl.CurrentClassLoader$1] (value [org.glassfish.pfl.dynamic.codegen.impl.CurrentClassLoader$1#2380e2]) and a value of type [org.glassfish.web.loader.WebappClassLoader] (value [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak."
In your code you have
#Named
public class DoctorSessionBean implements
This means that the bean will be name doctorSessionBean. If you don't specify a name it will use the bean name in lower case.
look here for http://docs.oracle.com/javaee/6/tutorial/doc/gjbak.html information.
Giving Beans EL Names
To make a bean accessible through the EL, use the #Named built-in qualifier:
import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named
#RequestScoped
public class Printer {
#Inject #Informal Greeting greeting;
...
The #Named qualifier allows you to access the bean by using the bean name,
with the first
letter in lowercase. For example, a Facelets page would refer to the bean as printer.
You can specify an argument to the #Named qualifier to use a nondefault name:
#Named("MyPrinter")
With this annotation, the Facelets page would refer to the bean as MyPrinter.
Related
I have a simple MyLibraryApplication which is having code to invoke POST(TransactionControllerImpl.issueBookToMember) and PATCH(TransactionControllerImpl.returnBookTransaction) methods. I have referred some links on net and tried my best to write code to invoke PATCH method. The code can be found in TransactionControllerTest(testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods). The code for invoking POST is working fine but the code for invoking PATCH is not working. Control never reaches returnBookTransaction inside TransactionControllerImpl.
Error: Invalid PATCH method.
I am looking for code snippet for TransactionControllerTest.testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods. Can someone help me in getting this code into proper shape?
package com.mycompany.techtrial;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.mycompany.techtrial.Transaction;
public interface TransactionController {
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params);
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId);
}
/**
*
*/
package com.mycompany.techtrial;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TransactionControllerImpl implements TransactionController{
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
* Example Post Request : { "book":"Java8 Primer","member":"Test 1" }
*/
#PostMapping(path = "/api/transaction")
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params){
String book = params.get("book");
String member = params.get("member");
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now());
transaction.setDateOfReturn(Transaction.getDefaultReturnDate());
return ResponseEntity.ok().body(transaction);
}
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
*/
#PatchMapping(path= "/api/transaction/{transaction-id}/return")
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId){
String book = "Java8 Primer";
String member = "Test 1";
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now().minusDays(10));
transaction.setDateOfReturn(LocalDateTime.now());
return ResponseEntity.ok().body(transaction);
}
}
package com.mycompany.techtrial;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TransactionControllerTest {
MockMvc mockMvc;
#Mock
private TransactionController transactionController;
#Autowired
private TestRestTemplate template;
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(transactionController).build();
}
#Test
public void testBookIssue() throws Exception {
HttpEntity<Object> transaction = getHttpEntity(
"{\"book\": \"Java8 Primer\", \"member\": \"Test 1\" }");
ResponseEntity<Transaction> response = template.postForEntity(
"/api/transaction", transaction, Transaction.class);
Assert.assertEquals("Java8 Primer", response.getBody().getBook());
Assert.assertEquals("Test 1", response.getBody().getMember());
Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingRestTemplate() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
Transaction transaction = template.patchForObject(
"/api/transaction/{transaction-id}/return",null, Transaction.class, uriVariables);
Assert.assertEquals(new Long(1), transaction.getId());
//Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingMockMvc() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
ResultActions obj = mockMvc.perform( MockMvcRequestBuilders
.patch("/api/transaction/{transaction-id}/return",transactionId)
.content("")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
System.out.println(obj.getClass());
HttpStatus status = obj.andReturn().getModelAndView().getStatus();
boolean success = status.is2xxSuccessful();
System.out.println("success="+success);
Assert.assertEquals(new Long(1), transactionId);
//Assert.assertEquals(200,response.getStatusCode().value());
}
private HttpEntity<Object> getHttpEntity(Object body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<Object>(body, headers);
}
}
package com.mycompany.techtrial;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Transaction implements Serializable {
private static final long serialVersionUID = 8951221480021840448L;
private static final LocalDateTime defaultReturnDate = LocalDateTime.of(LocalDate.of(2299, 12, 31), LocalTime.of(12, 0, 0));
Long id;
private String book;
private String member;
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
//Date and time of issuance of this book
LocalDateTime dateOfIssue;
//Date and time of return of this book
LocalDateTime dateOfReturn;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getDateOfIssue() {
return dateOfIssue;
}
public void setDateOfIssue(LocalDateTime dateOfIssue) {
this.dateOfIssue = dateOfIssue;
}
public LocalDateTime getDateOfReturn() {
return dateOfReturn;
}
public void setDateOfReturn(LocalDateTime dateOfReturn) {
this.dateOfReturn = dateOfReturn;
}
#Override
public String toString() {
return "Transaction [id=" + id + ", book=" + book + ", member=" + member + ", dateOfIssue=" + dateOfIssue + ", dateOfReturn=" + dateOfReturn + "]";
}
//#PrePersist
void preInsert() {
if (this.dateOfReturn == null)
this.dateOfReturn = defaultReturnDate;
}
public static LocalDateTime getDefaultReturnDate() {
return defaultReturnDate;
}
}
package com.mycompany.techtrial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(MyLibraryApplication.class, args);
}
}
It seems to be a known issue with the RestTemplate default Http client.
RestTemplate bug
A workaround for this would be to use the apache httpcomponents httpclient library in the RestTemplateBuilder.setRequestFactory and pass that in the constructor to TestRestTemplate
After that you can use the exchange method on the TestRestTemplate class and do a PATCH request.
Sample code to create TestRestTemplate:
Supplier<ClientHttpRequestFactory> supplier = () -> {
return new HttpComponentsClientHttpRequestFactory();
};
restTemplateBuilder.requestFactory(supplier);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
testRestTemplate.exchange("/api/transaction/{transaction-id}/return",HttpMethod.PATCH,null,Transaction.class,uriVariables);
Currently, i have function, which is to convert the data from MYSQL to CSV. The CSV function contain the webconfig where use the viewResolver. The problem is, when i used below function, the page cannot view but the CSV file can be download and vice versa. Is there anything that i need to configure ?
-Configure ContentNegotiatingViewResolver
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
WebConfig- full code
package com.portal.dmtt.csvDownload.config;
import com.portal.dmtt.csvDownload.viewResolver.CsvViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import java.util.ArrayList;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
}
Export Controller
package com.portal.dmtt.csvDownload.controller;
import com.portal.dmtt.repo.dmttDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExportController {
#Autowired
private dmttDAO dmttDAO;
/**
* Handle request to download an Excel document
*/
#GetMapping("/dl")
public String download(Model model) {
model.addAttribute("results", dmttDAO.getAllResultSet());
return "";
}
}
Abstract View
package com.portal.dmtt.csvDownload.view;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public abstract class AbstractCsvView extends AbstractView {
private static final String CONTENT_TYPE = "text/csv";
public AbstractCsvView() {
setContentType(CONTENT_TYPE);
}
#Override
protected boolean generatesDownloadContent() {
return true;
}
#Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
buildCsvDocument(model, request, response);
}
protected abstract void buildCsvDocument(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
CSV View
package com.portal.dmtt.csvDownload.view;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class CsvView extends AbstractCsvView {
#Override
protected void buildCsvDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse
response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"my-csv-file.csv\"");
List<FN_Result_Set> fnResultSetList = (List<FN_Result_Set>) model.get("results");
String[] header = {"SP_ID", "SP_ID", "XFER_XMIT_STATUS", "XFER_FILE_NAME", "UPDATE_TS", "YYMM", "REMARKS"};
try {
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
csvWriter.writeHeader(header);
for (FN_Result_Set user : fnResultSetList) {
csvWriter.write(user, header);
}
csvWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
View Resolver
package com.portal.dmtt.csvDownload.viewResolver;
import com.portal.dmtt.csvDownload.view.CsvView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
public class CsvViewResolver implements ViewResolver {
#Override
public View resolveViewName(String s, Locale locale) throws Exception {
return new CsvView();
}
}
One of the problems is that your CSVViewResolver is resolving a view for any view name. You may want to return null from CSVViewResolver.resolveViewName() if s, the view name, is not empty .
Another issue is that the browser (at least my Chrome) doesn't send text/csv as Accept header, but text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Set the media type explicitly in configureContentNegotiation for CSV:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true)
.mediaType("csv", MediaType.parseMediaType("text/csv"));
}
Remove the Bean contentNegotiatingViewResolver
You shouldn't create a contentNegotiatingViewResolver as one is provided by Spring Boot. If you provide one, you will have two of this type, and yours will not have the Thymeleaf ViewResolver. As your CSVViewResolver will return a view for any view name, the view will be resolved in the ContentNegotiatingViewResolver provided by you, not in the one provided by Spring.
Details:
The csvViewResolver bean will be picked up by the Spring Boot's ContentNegotiatingViewResolver along others like BeanNameViewResolver, ThymeleafViewResolver, ViewResolverComposite, InternalResourceViewResolver.
To debug this set a breakpoint on DispatcherServlet.resolveViewName:
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}
I am trying to implement pagination of dynamodb using java in my project, i have implemented it, I am struggling in how to get the no. of elements in result per page using DynamoDBScanExpression. Can anyone help. Thanks
Here is my code
package com.morrisons.extendedrange.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedScanList;
import com.amazonaws.services.dynamodbv2.datamodeling.QueryResultPage;
import com.amazonaws.services.dynamodbv2.datamodeling.ScanResultPage;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity;
import com.google.inject.Inject;
import com.morrisons.extendedrange.config.ExtendedRangeServiceConfiguration;
import com.morrisons.extendedrange.entity.ExtendedRangeEntity;
import com.morrisons.extendedrange.exception.ErrorCodes;
import com.morrisons.extendedrange.exception.ExtendedRangeServiceException;
import com.morrisons.extendedrange.model.ExtendedRange;
import com.morrisons.extendedrange.util.Logger;
import com.morrisons.extendedrange.util.LoggerFactory;
/**
* The Class ExtendedRangeDao.
*/
public class ExtendedRangeDao {
private static Logger LOGGER;
#Inject
private LoggerFactory logFactory;
Map<String, AttributeValue> lastEvaluatedKey = null;
#Inject
private void init() {
LOGGER = logFactory.getLogger(ExtendedRangeDao.class);
}
/** The range service configuration. */
#Inject
private ExtendedRangeServiceConfiguration extendedRangeServiceConfiguration;
/**
* Gets the range.
*
* #param storeId
* the store id
* #param catalogId
* the catalog id
* #return the range
*/
public ExtendedRange getExtendedRange(String catalogId, String productId, String page) {
LOGGER.debug("ExtendedRangeDao : getExtendedRange start ");
List<ExtendedRange> extendedRangeList = new ArrayList<ExtendedRange>();
try {
AmazonDynamoDBClient client = extendedRangeServiceConfiguration.getDynamoDBClient();
DynamoDBMapper mapper = new DynamoDBMapper(client);
Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":val1", new AttributeValue().withS(productId));
eav.put(":val2", new AttributeValue().withS(catalogId));
DynamoDBScanExpression scanExpression=new DynamoDBScanExpression()
.withFilterExpression("(productname =:val1 or productid =:val1) and catalogid = :val2 ")
.withExpressionAttributeValues(eav)
.withConsistentRead(true)
.withLimit(5)
.withExclusiveStartKey(lastEvaluatedKey) ;
ScanResultPage<ExtendedRangeEntity> queryResultPage = mapper.scanPage(ExtendedRangeEntity.class,
scanExpression, getDBMapperConfigForFetch());
List<ExtendedRangeEntity> extendedRangeEntityList = queryResultPage.getResults();
lastEvaluatedKey = queryResultPage.getLastEvaluatedKey();
if (extendedRangeEntityList.isEmpty()) {
String errorMessage = "No Record found or Multiple data found";
LOGGER.debug(errorMessage);
throw new ExtendedRangeServiceException(ErrorCodes.NO_RECORDS_FOUND, "ExtendedRangeEntity not found");
} else {
for (ExtendedRangeEntity extendedRangeEntity : extendedRangeEntityList) {
ExtendedRange extendedRange = new ExtendedRange();
copyProperties(extendedRange, extendedRangeEntity);
extendedRangeList.add(extendedRange);
LOGGER.debug("ExtendedRangeDao : getExtendedRange end ");
}
ExtendedRange returnExtendedRange = new ExtendedRange();
returnExtendedRange.setExtendedRangeList(extendedRangeList);
return returnExtendedRange;
}
} catch (AmazonServiceException e) {
String errorMessage = "Error in retrieving Data in DynamoDB";
LOGGER.error(errorMessage, e);
throw new ExtendedRangeServiceException(ErrorCodes.AMAZON_SERVICE_ERROR, errorMessage);
}
}
private DynamoDBMapperConfig getDBMapperConfigForFetch() {
String tableName = extendedRangeServiceConfiguration.getTableNameConfig()
.getTableName(ExtendedRangeEntity.class);
TableNameOverride tableNameOverride = new TableNameOverride(tableName);
DynamoDBMapperConfig dbMapperConfig = new DynamoDBMapperConfig(tableNameOverride);
return dbMapperConfig;
}
public ExtendedRangeServiceConfiguration getExtendedRangeServiceConfiguration() {
return extendedRangeServiceConfiguration;
}
public void setRangeServiceConfiguration(ExtendedRangeServiceConfiguration extendedRangeServiceConfiguration) {
this.extendedRangeServiceConfiguration = extendedRangeServiceConfiguration;
}
private void copyProperties(ExtendedRange target, ExtendedRangeEntity src) {
target.setProductId(src.getProductId());
target.setLeadTimeUOM(src.getLeadTimeUOM());
target.setCatalogId(src.getCatalogId());
target.setProductDesc(src.getProductDesc());
target.setProductName(src.getProductName());
target.setLeadTime(src.getLeadTime());
target.setCanBeOrderedFromDate(src.getCanBeOrderedFromDate());
target.setCanBeOrderedToDate(src.getCanBeOrderedFromDate());
}
}
The size() method should provide the number of elements in a page.
queryResultPage.getResults().size()
Please help. I am working on a Spring Boot Application that uses Spring JPA, Hateoas and Spring Data Rest MVC. The application can be broken down into 2 major parts a RESTFul API and a Web App. The Restful API Works perfectly. The only problem now is getting my JSP pages to work. I get the following log message when trying http://localhost:9003/home.
2015-04-06 21:09:02.016 WARN 6702 --- [nio-9003-exec-3] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/WEB-INF/jsp/index.jsp] in DispatcherServlet with name 'dispatcherServletRegistration'
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#SpringBootApplication
#EnableJpaRepositories
#EnableWebMvc
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
WebController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class WebController {
#RequestMapping(value = "/home", method=RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public ModelAndView index() {
return new ModelAndView("index");
}
}
DVDController.java
import com.stalinkay.rentadvd.domain.DVD;
import com.stalinkay.rentadvd.service.DVDService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/dvd")
public class DVDController {
private final DVDService dvdService;
#Autowired
public DVDController(DVDService dvdService) {
this.dvdService = dvdService;
}
/**
* Create DVD
*
* #param requestDVD Spring uses the RequestBody to create a new DVD
* to save to the database
* #return
*/
#RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.CREATED)
HttpHeaders create(#RequestBody DVD requestDVD) {
return dvdService.create(requestDVD);
}
/**
* Retrieve DVD
*
* #param dvdid
* #return
*/
#RequestMapping(value = "/{dvdid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
Resource<DVD> retrieve(#PathVariable Long dvdid) {
return dvdService.retrieve(dvdid);
}
/**
* Retrieve All DVDs
*
* #return
*/
#RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
List<Resource<DVD>> retrieveAll() {
return dvdService.retrieveAll();
}
/**
* Update DVD
*
* #param requestDVD Spring uses the RequestBody to create a new DVD
* to save to the database
* #return
*/
#RequestMapping(value = "", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
HttpHeaders update(#RequestBody DVD requestDVD) {
return dvdService.update(requestDVD);
}
/**
* Delete DVD
*
* #param dvdid
* #return
*/
#RequestMapping(value = "/{dvdid}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
void delete(#PathVariable Long dvdid) {
dvdService.delete(dvdid);
}
}
I included my DVDController.java just to show that I'm using #RestController for the RESTful API and #Controller for the Web App.
What can I do to get Spring to serve my JSP Pages? I don't want to use xml. And I would like to have both the RESTful API and the Web App in 1 project.
Thank you in advance.
This is what I ended up with.
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Updated application.properties to:
spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp
I had #EnableWebMvc and that was also causing the view resolution issues.
I stumbled upon this by looking at Spring's spring-boot-sample-web-jsp.
I have springmvc and angularjs app up and running.
In Springmvc i have a bean named userSessionBean.
Now i am adding an interceptor to spring mvc and in its pre handel method i am trying to access userSessionBean.
My question is "Can i inject userSessionBean inside interceptor "
/**
*
*/
package com.loginLite.remote.authentication.interceptors;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.remote.authentication.model.UserSessionBean;
/**
* #author jamju02
*
*/
public class AuthenticationInteceptor implements HandlerInterceptor {
#Autowired
private UserSessionBean userSessionBean = null;
/**
* #return the userSessionBean
*/
public UserSessionBean getUserSessionBean() {
return userSessionBean;
}
/**
* #param userSessionBean the userSessionBean to set
*/
public void setUserSessionBean(UserSessionBean userSessionBean) {
userSessionBean = userSessionBean;
}
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle");
return true;
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
Random rnd = new Random();
int tokenNumber = 100000 + rnd.nextInt(900000);
userSessionBean.setAuthTokenNumber(String.valueOf(tokenNumber));
response.addHeader("AUTH_TOKEN",userSessionBean.getAuthTokenNumber());
System.out.println("Post-handle");
}
#Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("After completion handle");
}
}
My dispatcher servlet
<mvc:interceptors>
<bean class="com.paychex.loginLite.remote.authentication.interceptors.AuthenticationInteceptor">
<property name="userSessionBean" ref="userSessionBean"></property>
</bean>
</mvc:interceptors>
<bean id="userSessionBean"
class="com.paychex.loginLite.remote.authentication.model.UserSessionBean"
scope="session">
<aop:scoped-proxy />
</bean>
I was finally able to solve the issue which i was troubling me.
The mistake was, i was implementing the interface "HandlerInterceptor" for my interceptor class, as soon as i removed the interface and extended class "HandlerInterceptorAdapter" dependency injection started working fine.