Fetching image from MySQL database in Spring boot and thymeleaf - spring-boot

I am trying to create a service which fetch image of a student along with other text details of student stored in database and display it on an html page. I tried but some hash value is being returned.
My Model Class
#Entity
#Table(name = "details")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#Column(name = "pic" , length = 2000)
private byte[] pic;
public Student(long id, String name, byte[] pic) {
super();
this.id = id;
this.name = name;
this.pic = pic;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "];
}
}
Without Using a rest contoller will it be achieved like this?
My Controller
#Controller
public class ImgShowController {
#Autowired
EntityRepository entityRepository;
#RequestMapping("/list")
public String getAllStudents(Model model) {
List<Imge> list = (List<Imge>) entityRepository.findAll();
model.addAttribute("students", list);
return "liststudents";
}
#RequestMapping(path= {"/particularlist","/particularlist/{id}"})
public String getImage(#PathVariable("id") Long id, Model model) {
final Optional<Student> imget = entityRepository.findById(id);
Imge imge = new Imge(imget.get().getId(), imget.get().getName(), decompressBytes(imget.get().getPic()));
model.addAttribute("particularStudent", imge);
return "particularstudent";
}
}
Decompress Byte function
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}

First of all, I would suggest mentioning that you store binary object (LOB) in pic column in your entity class:
#Lob
#Column(name = "pic" , length = 2000)
private byte[] pic;
And then, it seems that Thymeleaf does not allow you to inject image directly into model, so you have 2 ways to accomplish this:
1.Adding another controller to serve you images
#GetMapping("/students/{id}/image")
public void studentImage(#PathVariable String id, HttpServletResponse response) throws IOException {
var student = entityRepository.findById(id);
var imageDecompressed = decompressBytes(student.get().getPic());
response.setContentType("image/jpeg");
InputStream is = new ByteArrayInputStream(imageDecompressed);
IOUtils(is, response.getOutputStream());
}
and then referring to it from model like this:
<img th:src="#{'students/' + #{studentId} + '/image'}">
2.Using base64
You need to encode image as base64 string:
var base64EncodedImage = Base64.getEncoder().encodeToString(imageData);
and then setting into model like this:
<img th:src="#{'data:image/jpeg;base64,'+${base64EncodedImage}}"/>
I would suggest using the first way because otherwise you would depend on image size and overall payload would be 30% larger (base64), so by using the first way you let user's browser decide how and when to load particular image

Related

How to use List in another function

--------------------------------------Table 1--------------------------------------
#Entity
#Table(name = "student_details")
public class StudentDetails {
#Id
private Long studentId;
private String firstName;
private String lastName;
private String fatherName;
// with getter and setters
}
-------------------------------------Table 2---------------------------------
#Entity
#Table(name = "student_marks")
public class StudentMarks {
#Id
private Long studentId;
private int Maths;
private int English;
private int Computer;
// with getter and setters
}
------------------------------------class which combine these two table------------------
public class StudentReportData {
#Id
private Long studentId;
private String studentName
private String fatherName;
private int Maths;
private int English;
private int Computer;
//with getter and setters
}
-----------------------------------Service Class---------------------------
#Service
public class StudentService {
public ApiResponce<List<StudentReportData>> getStudentData() {
ApiResponce<List<StudentReportData>> responce = new ApiResponce();
Status status = new Status();
status setSuccess(true);
try {
List<StudentReportData> studentList = new ArrayList<StudentReportData>();
List<StudentMarks> findAll = studentMarksRepository.findAll();
for(StudentMarks sm : findAll) {
StudentReportData studentData = new StudentReportData();
BeanUtils.copyProperties(sm, studentData);
StudentDetails studentDetailsData = studentDetailsRepository.findByStudentId(sm.getStudentId());
studentData.setStudentName(studentDetailsData.getFirstName()+" "+studentDetailsData.getLastName());
studentList.add(studentData);
}
response.setData(studentList);
} catch (Exception ex) {
ex.printStackTrace();
ErrorData errorData = new ErrorData();
errorData.setErrorCode("ERR003");
errorData.setErrorMessage("Internal Server Error");
status.setErrorData(errorData);
status.setSuccess(false);
}
response.setStatus(status);
return response;
}
public ByteArrayInputStream load() {
ByteArrayInputStream in = ExcelHelper.studentreportToExcel(studentList);
return in;
}
}
I want to pass this studentList as an argument to the function studentReportToExcel from the function load. How can I get that List Inside the load function.
Add it as a class attribute, something like:
#Service
public class StudentService {
private List<StudentReportData> studentList; // class attribute to add
public ApiResponce<List<StudentReportData>> getStudentData() {
ApiResponce<List<StudentReportData>> responce = new ApiResponce();
Status status = new Status();
status setSuccess(true);
try {
studentList = new ArrayList<StudentReportData>(); // line changed
List<StudentMarks> findAll = studentMarksRepository.findAll();
for(StudentMarks sm : findAll) {
StudentReportData studentData = new StudentReportData();
BeanUtils.copyProperties(sm, studentData);
StudentDetails studentDetailsData = studentDetailsRepository.findByStudentId(sm.getStudentId());
studentData.setStudentName(studentDetailsData.getFirstName()+" "+studentDetailsData.getLastName());
studentList.add(studentData);
}
response.setData(studentList);
} catch (Exception ex) {
ex.printStackTrace();
ErrorData errorData = new ErrorData();
errorData.setErrorCode("ERR003");
errorData.setErrorMessage("Internal Server Error");
status.setErrorData(errorData);
status.setSuccess(false);
}
response.setStatus(status);
return response;
}
public ByteArrayInputStream load() {
ByteArrayInputStream in = ExcelHelper.studentreportToExcel(studentList);
return in;
}
}

Printing Json data that is in array using rest template in SpringBoot

#Component
public class JsonData {
#JsonProperty("id")
private Integer id;
#JsonProperty("createdAt")
private Date cratedAt;
#JsonProperty("name")
private String name;
#JsonProperty("email")
private String email;
#JsonProperty("imageUrl")
private String url;
public JsonData() {
}
public JsonData(Integer id, Date cratedAt, String name, String email, String url) {
this.id = id;
this.cratedAt = cratedAt;
this.name = name;
this.email = email;
this.url = url;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCratedAt() {
return cratedAt;
}
public void setCratedAt(Date cratedAt) {
this.cratedAt = cratedAt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Controller
#RestController
public class JsonDataController {
#RequestMapping(value = "/template/products")
public void getAllData() {
RestTemplate template = new RestTemplate();
String url = "https://5ef99e4bbc5f8f0016c66d42.mockapi.io/testing/data";
ResponseEntity < JsonData[] > response = template.exchange(url, JsonData[].class);
for (JsonData jsonData: response.getBody()) {
System.out.println(jsonData.getName());
System.out.println(jsonData.getEmail());
}
}
}
I am trying to print json data that is array using rest template but I am getting error in this line "ResponseEntity < JsonData[] > response = template.exchange(url, JsonData[].class);" my error is "cannot resolve method" Can anyone tell me correct way of doing this .I am new to spring I do not have proper understanding it would be helpful if some one can give their suggeestion in this code
RestTemplate does not have any method with signature exchange(String, Class<T>).
That is why you are getting "cannot resolve method" error for template.exchange(url, JsonData[].class);.
Here is an example of correct usage of one of the methods from RestTemplate.exchange API:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<JsonData[]> response = restTemplate.exchange(url, HttpMethod.GET, null, JsonData[].class);
RestTemplate also has another method - getForEntity that makes a GET call with the given URL and expected return type. (without need for passing null for not required fields)
RestTemplate template = new RestTemplate();
String url = "https://5ef99e4bbc5f8f0016c66d42.mockapi.io/testing/data";
ResponseEntity <JsonData[]> response = template.getForEntity(url, JsonData[].class);

springboot - Json object return invalid

Currently, I am using rest template to get data from external api in getter method. While printing in console log, valid json format is coming. But, through postman output, invalid json output is coming (with \"). Pls suggest.
public class Product {
#Id
public Integer id;
private String name;
public Product() {
}
public Product(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
final String uri = "http://example.com/";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri + this.getId(), String.class);
System.out.println(result);
return result;
}
public void setName(String name) {
this.name = name;
}
}
//console.log (example)
{"product":{"rating_and_review_reviews":{"hasErrors":false,"offset":0,
"totalResults":0,"locale":"en_US","limit":10,"duration":1,"result":
[]},"question_answer_statistics"
// POSTMAN - HTTP GET (coming with \)
{
"id": 1,
"name": "{\"product\":{\"rating\":{\"hasErrors\":false,\"offset\":0,
\"totalResults\":0,\"locale\":\"en_US\",\"limit\":10,
\"duration\":1,\"result\":[]}

Spark insert to Hbase

I have a pojo class of emp like below:
I am able to read streaming data and I want to insert data to Hbase
#JsonInclude(Include.NON_NULL)
public class empData implements Serializable {
private String id;
private String name;
#Override
public String toString() {
return "id=" + id + ", name="+ name ;
}
public String id() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Below is spark code:
empRecords.foreachRDD(new Function<JavaRDD<empData>, Void>() {
private static final long serialVersionUID = 1L;
#Override
public Void call(JavaRDD<empData> empDataEvent)throws Exception {
Configuration conf = HBaseConfiguration.create();
Configuration config = null;
config = HBaseConfiguration.create();
config.set("hbase.zookeeper.quorum", "**********);
HBaseAdmin.checkHBaseAvailable(config);
config.set(TableInputFormat.INPUT_TABLE, "tableName");
Job newAPIJobConfiguration1 = Job.getInstance(config);
newAPIJobConfiguration1.getConfiguration().set(TableOutputFormat.OUTPUT_TABLE, "empHbase");
newAPIJobConfiguration1.setOutputFormatClass(org.apache.hadoop.hbase.mapreduce.TableOutputFormat.class);
JavaPairRDD<ImmutableBytesWritable, Put> inesrts = empData.mapToPair(new PairFunction<Row, ImmutableBytesWritable, Put>() {
public Tuple2<ImmutableBytesWritable, Put> call(Row row) throws Exception
{
Put put = new Put(Bytes.toBytes(row.getString(0)));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("id"),Bytes.toBytes(row.getString(1)));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("name"),Bytes.toBytes(row.getString(2)));
return new Tuple2<ImmutableBytesWritable, Put>(new ImmutableBytesWritable(), put);
}
});
inserts.saveAsNewAPIHadoopDataset(newAPIJobConfiguration1.getConfiguration());
}
});
jssc.start();
jssc.awaitTermination();
}
The problem in the code is this step:
JavaPairRDD<ImmutableBytesWritable, Put> inesrts =empDataEvent.mapToPair(new PairFunction<Row, ImmutableBytesWritable, Put>()
How to use empDataEvent and how to insert..
How do I insert as mapToPair empDataEvent class object so that I can insert into Hbase.
Any help appreciated..
Aman,
In your code you have refer "Row", can you please elaborate where it is coming from? because there is no reference for it.
See updated code below, use class name "empData" instead of "Row" object.
JavaPairRDD<ImmutableBytesWritable, Put> inesrts = empData.mapToPair(new PairFunction<empData, ImmutableBytesWritable, Put>() {
public Tuple2<ImmutableBytesWritable, Put> call(empData row) throws Exception
{
Put put = new Put(Bytes.toBytes(row.id));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("id"),Bytes.toBytes(row.id));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("name"),Bytes.toBytes(row.getName));
return new Tuple2<ImmutableBytesWritable, Put>(new ImmutableBytesWritable(), put);
}
});

GWT 2.5 + Spring 3 + Hibernate 3 clear example

I saw questions about GWT + SPRING + HIBERNATE integration but none is clear or up to date with the current versions!
Please if there is anyone who has a clear and simple example of the integration (form submit and saving in DB) I will be extremely thankful!
If you could put the simple project in a ZIP and upload it (with its jars it will be great)
Thank you!
I guess this one using gwt 2.5.0-rc1, Spring 3.1.2.RELEASE and Hibernate 4 will be helpful. This project is using maven, so install maven which will take care of required dependencies. git clone it, command-line build with $ mvn clean install and dive into.
The basic gwt server-shared-client architecture is
Entity
#Entity
#Table(name = "TBL_BOOK")
public class Book implements Serializable {
private static final long serialVersionUID = -687874117917352477L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "TITLE", nullable = false)
private String title;
#Column(name = "SUBTITLE")
private String subtitle;
#Column(name = "AUTOR", nullable = false)
private String autor;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "ISBN")
private String isbn;
#Column(name = "GENRE")
private String genre;
#Temporal(TemporalType.DATE)
#Column(name = "PUBLISHED_DATE")
private Date publishedDate;
#Column(name = "PUBLISHER")
private String publisher;
public Book() {
}
public Book(Long id, String title, String subtitle, String autor,
String description, String isbn, String genre, Date publishedDate,
String publisher) {
this.id = id;
this.title = title;
this.subtitle = subtitle;
this.autor = autor;
this.description = description;
this.isbn = isbn;
this.genre = genre;
this.publishedDate = publishedDate;
this.publisher = publisher;
}
public Book(Book bookDTO) {
this.id = bookDTO.getId();
this.title = bookDTO.getTitle();
this.subtitle = bookDTO.getSubtitle();
this.autor = bookDTO.getAutor();
this.description = bookDTO.getDescription();
this.isbn = bookDTO.getIsbn();
this.genre = bookDTO.getGenre();
this.publishedDate = bookDTO.getPublishedDate();
this.publisher = bookDTO.getPublisher();
}
//getters and setters
#Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", subtitle=" + subtitle
+ ", author=" + autor + ", description=" + description
+ ", isbn=" + isbn + ", genre=" + genre + ", publishedDate="
+ publishedDate + ", publisher=" + publisher + "]";
}
}
web configuration
<!-- SpringGwt remote service servlet -->
<servlet>
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
<servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
<url-pattern>/GwtSpringHibernate/springGwtServices/*</url-pattern>
</servlet-mapping>
Client side stub for RPC
/**
* The client side stub for the RPC service.
*/
#RemoteServiceRelativePath("springGwtServices/bookService")
public interface BookService extends RemoteService {
public void saveOrUpdate(Book book) throws Exception;
public void delete(Book book) throws Exception;
public Book find(long id);
public List<Book> findAllEntries();
}
Server
#Service("bookService")
public class BookServiceImpl extends RemoteServiceServlet implements BookService {
private static final long serialVersionUID = -6547737229424190373L;
private static final Log LOG = LogFactory.getLog(BookServiceImpl.class);
#Autowired
private BookDAO bookDAO;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveOrUpdate(Book book) throws Exception {
//
}
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void delete(Book book) throws Exception {
//
}
public Book find(long id) {
return bookDAO.findById(id);
}
public List<Book> findAllEntries() {
//
}
}
Client View
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class GwtSpringHibernate implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Book service.
*/
private final BookServiceAsync bookService = GWT.create(BookService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
DateBox.DefaultFormat defaultFormatter = new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd.MM.yyyy"));
// Add new Book Area
final TextBox titleField = new TextBox();
titleField.setFocus(true);
final TextBox subtitleField = new TextBox();
final TextBox autorField = new TextBox();
final TextBox descriptionField = new TextBox();
final TextBox isbnField = new TextBox();
final TextBox genreField = new TextBox();
final DateBox publishedDateField = new DateBox();
publishedDateField.setFormat(defaultFormatter);
final TextBox publisherField = new TextBox();
final Button saveButton = new Button("Save");
saveButton.addStyleName("button");
final Button retrieveButton = new Button("Retrieve");
retrieveButton.addStyleName("button");
final Label errorLabel = new Label();
// Add fields to the Rootpanel
RootPanel.get("title").add(titleField);
RootPanel.get("subtitle").add(subtitleField);
RootPanel.get("autor").add(autorField);
RootPanel.get("description").add(descriptionField);
RootPanel.get("isbn").add(isbnField);
RootPanel.get("genre").add(genreField);
RootPanel.get("publishedDate").add(publishedDateField);
RootPanel.get("publisher").add(publisherField);
RootPanel.get("btnSave").add(saveButton);
RootPanel.get("btnRetrieveAllEntries").add(retrieveButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending request to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
saveButton.setEnabled(true);
saveButton.setFocus(true);
retrieveButton.setEnabled(true);
}
});
class SaveBookHandler implements ClickHandler, KeyUpHandler {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
saveBook();
}
}
public void onClick(ClickEvent arg0) {
saveBook();
}
private void saveBook() {
errorLabel.setText("");
String _title = titleField.getText();
String _subtitle = subtitleField.getText();
String _autor = autorField.getText();
String _desc = descriptionField.getText();
String _isbn = isbnField.getText();
String _genre = genreField.getText();
Date _publishedDate = publishedDateField.getValue();
String _publisher = publisherField.getText();
// First, we validate the input.
if (Validator.isBlank(_title) || Validator.isBlank(_autor)) {
String errorMessage = "Please enter at least the Title and the Autor of the book";
errorLabel.setText(errorMessage);
return;
}
Book bookDTO = new Book(null, _title, _subtitle, _autor, _desc, _isbn, _genre, _publishedDate, _publisher);
saveButton.setEnabled(false);
serverResponseLabel.setText("");
textToServerLabel.setText(bookDTO.toString());
bookService.saveOrUpdate(bookDTO, new AsyncCallback<Void>() {
public void onFailure(Throwable caught) {
dialogBox.setText("Remote Procedure Call - Failure");
serverResponseLabel.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(Void noAnswer) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML("OK");
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the book info to the server
SaveBookHandler saveBookHandler = new SaveBookHandler();
saveButton.addClickHandler(saveBookHandler);
publisherField.addKeyUpHandler(saveBookHandler);
// Create a handler for the retrieveButton
class RetrieveAllEntriesHandler implements ClickHandler {
/**
* Fired when the user clicks on the retrieveButton.
*/
public void onClick(ClickEvent event) {
retrieveAllEntries();
}
private void retrieveAllEntries() {
// Nothing to validate here
// Then, we send the input to the server.
retrieveButton.setEnabled(false);
errorLabel.setText("");
textToServerLabel.setText("");
serverResponseLabel.setText("");
bookService.findAllEntries(
new AsyncCallback<List<Book>>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox.setText("Remote Procedure Call - Failure");
serverResponseLabel.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(List<Book> data) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel.removeStyleName("serverResponseLabelError");
if(data != null && !data.isEmpty()){
StringBuffer buffer = new StringBuffer();
for (Book book : data) {
buffer.append(book.toString());
buffer.append("<br /><br />");
}
serverResponseLabel.setHTML(buffer.toString());
} else {
serverResponseLabel.setHTML("No book information store in the database.");
}
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler
RetrieveAllEntriesHandler retrieveAllEntriesHandler = new RetrieveAllEntriesHandler();
retrieveButton.addClickHandler(retrieveAllEntriesHandler);
}
}
For more widgets, go through official widget library, UiBinder.
1) Download the zip file cited above from https://github.com/chieukam/gwt-spring-hibernate-tutorial/archive/master.zip and extract it somewhere
2) In Eclipse, create a new Maven project. Since there is no .project file provided in the above zip, you will need to confiugre all this manually.
3) Import "File System" from the place where you unzipped this project into your new Maven project.
At this point, I have some errors:
BookServiceAsync appears to be nonexistent, resulting in 6 compile errors.
"Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-war-plugin:2.1.1:exploded (execution: default, phase: compile)" in pom.xml, lines 162 and 185
This example seems to be somewhat incomplete. Am I missing something??

Resources