How to convert content of MultipartFile file into JSON string - java

I have one file Person.Java
public class Person {
private String firstName;
private String lastName;
}
file is stored at location say : "C:\Users\Person.Java"; This file is not part of the project.
I have written REST API endpoint which is accepting this file as a input and reading this file.
#PostMapping(value = "/poc/jsobj", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<ResponseMessage> convertToJson(#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
String completeData = new String(bytes);
//what should I write here
}}
After reading I want to convert content of this file into JSON format.
{
"firstName":" ",
"lastName":" "
}
so, the requirement is take java file (a class) as input to controller and generate corresponding json String as it's output.

Related

how to update the data along with the multipart file

I have created a form that has 2 file uploads and a few text content, it successfully uploads data in DB, when I'm trying to re-edit/update the same form. Either I'm getting bad request error if I use Multipart along with entity class. If I use multipart without entity it is creating new records but not updating the old records.
when add the entity class to this along with #RequestParam("file") MultipartFile file to save the file and other details iam getting an error while updating data.
Following is code:
#PostMapping("/update")
public String update(#RequestParam("bookPath") MultipartFile file, #RequestParam("bookCover") MultipartFile cover,
#RequestParam("bookName") String bookName, #RequestParam("totalpages") String totalpage,
#RequestParam("bookAuthor") String BA,#RequestParam("bookPrice") String Bp,
#RequestParam("bookPublicationDate") String bpd, #RequestParam("bookRating") String bookRating,
#RequestParam("bookDesc") String Bdes, #RequestParam("ReadingAge") String readingAge,
#RequestParam("AudioBook") String Ab,#RequestParam("isbn_num") String isbn,
#RequestParam("status") String satus,
#RequestParam("discount_option") String discount, #RequestParam("genres") String genras,
#RequestParam("dicsounted_price") String fixed_dis,
#RequestParam("percentge_value") String percentage, Book_dtls b)
Book_dtls is the entity class.
Error Imagelike below image.
i want to update the data along with files

Check if item already exists in DB

I am new to Java and Spring Framework, and I'm learning it by a file upload example. I have a controller for uploading of a file. Before I save anything to DB, I would like to check if the file with the same name already exists and return an error message for it. This is how the controller looks like:
#PostMapping("/file-upload")
public String postFile(#RequestParam("fileUpload") MultipartFile fileUpload, Authentication authentication, Model model) throws IOException {
if(fileUpload.isEmpty()) {
model.addAttribute("success",false);
model.addAttribute("message","No file selected to upload!");
return "home";
}
if(fileService.getByFilename(fileUpload.getOriginalFilename()) != null) {
model.addAttribute("success",false);
model.addAttribute("message","File with that name already exists");
return "home";
}
User user = this.userService.getUser(authentication.getName());
Integer userId = user.getUserId();
fileService.createFile(fileUpload, userId);
model.addAttribute("success",true);
model.addAttribute("message","New File added successfully!");
return "home";
}
And this is the fileService getByFilename method:
public File getByUsername(String filename) {
return fileMapper.getByUsername(filename);
}
And finally fileMapper getByFilename:
#Select("SELECT * FROM FILES WHERE filename = #{filename}")
File getByUsername(String filename);
But, when I try to upload a file like that, I get an error:
There was an unexpected error (type=Internal Server Error,
status=500). Error attempting to get column 'FILEDATA' from result
set. Cause: org.h2.jdbc.JdbcSQLDataException: Data conversion error
converting
This is how the table looks like:
CREATE TABLE IF NOT EXISTS FILES (
fileId INT PRIMARY KEY auto_increment,
filename VARCHAR,
contenttype VARCHAR,
filesize VARCHAR,
userid INT,
filedata BLOB,
foreign key (userid) references USERS(userid)
);
How should I fix this?
Here is the link to the repo.
This is the File class:
package com.udacity.jwdnd.course1.cloudstorage.model;
public class File {
private Integer fileId;
private String filename;
private String contenttype;
private Long filesize;
private byte[] filedata;
private Integer userid;
public File(Integer fileId, String filename, String contenttype, Long filesize, byte[] filedata, Integer userid) {
this.fileId = fileId;
this.filename = filename;
this.contenttype = contenttype;
this.filesize = filesize;
this.filedata = filedata;
this.userid = userid;
}
public Integer getFileId() {
return fileId;
}
public void setFileId(Integer fileId) {
this.fileId = fileId;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getContenttype() {
return contenttype;
}
public void setContenttype(String contenttype) {
this.contenttype = contenttype;
}
public Long getFilesize() {
return filesize;
}
public void setFilesize(Long filesize) {
this.filesize = filesize;
}
public byte[] getFiledata() {
return filedata;
}
public void setFiledata(byte[] filedata) {
this.filedata = filedata;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) { this.userid = userid; }
}
The structure of your table strongly suggests that a single row contains all the data: It does not represent a file at all, and there is no file on your file system: There is a bunch of binary data in the filedata column.
It is not possible to just treat this as a java.io.File object, which is a very light wrapper around a physical file on your file system (really - just check it out, File has one field, of type String, containing a path. That's all it has).
Therefore you just can't do what you want here. You need to find an alternative:
Save the data to an actual file
This involves having some sort of store on the disk, perhaps a tmp dir, where you explicitly write out all the blob data. You'll need to worry about clearing this stuff out or you're going to grow endless files in there.
Who cares about files?
Why do you NEED a file object? You should build software to be as abstract as seems reasonable at the time, and 'I need a file' is rarely the right level. The right level is usually either 'byte array' or 'InputStream' or something similar. Fix your program's flow so that they need only a byte array or better yet an inputstream and use JDBC's blob functionality to take care of this (I don't actually know how to unlock this using spring; you may have to write some code instead of just an #Select annotated method.

Java Json beautifying on save

I am saving a player to a .json file like this:
public static void savePlayer(Player player) {
final String username = player.getUsername();
final byte[] json = new Gson().toJson(player).getBytes();
final String path = "pack/players/" + username;
try {
Files.write(Paths.get(path + "/data.json"), json, StandardOpenOption.CREATE);
logger.info("Successfully SAVED player [username=%s]!", username);
} catch (IOException e) {
e.printStackTrace();
}
}
and I am using this Eclipse JSON editor plugin to view the json file: https://sourceforge.net/projects/eclipsejsonedit/
However, when looking at the file it is all compressed in one line and not beautified.
The resulting one line of json code is printed like this (instead of beautified):
{"inventory":{"data":[null]},"equipment":{"data":[null]},"playerCredentials":{"username":"kay","password":"password"},"attribute":{}}
What can I do to beautify the code before saving it?
Since you are using Gson you can use their prettyPrinting and create a new Gson obejct
Gson gson = new GsonBuilder().setPrettyPrinting().create();
And then create a String object from that
String output = gson.toJson(json);
If you use FileWriter you can simple use that string to write to a file.

Play Framework : Sending CSV file as an attachment

How to send a CSV file as an attachment in Play framework? I looked into the Play documentation by I didn't find what I'm looking for. I know I can return an input stream like that : ok(java.io.InputStream content, int chunkSize) but how to create and send the content to the csv file?
Play makes it easy to manipulate a HTTPResponse. You can find in the manual, how to add headers, set cookies etc. in a response.
The implementation differs according to the use case:
Some string source is converted to csv file while sending to the client.
An existing csv file is sent to the client.
Sending string as CSV file in a HTTPResponse
Play 2.4
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result string2CsvFile() {
String csvContent = "f1,f2,f3,f4";
response().setContentType("text/csv");
response().setHeader(CONTENT_DISPOSITION,
String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
return ok(new ByteArrayInputStream(csvContent.getBytes()));
}
Play 2.5
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result string2CsvFile() {
String csvContent = "f1,f2,f3,f4";
response().setHeader(CONTENT_DISPOSITION,
String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
return ok(new ByteArrayInputStream(csvContent.getBytes())).as("text/csv");
}
Sending existing CSV file in a HTTPResponse
Play 2.4
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result attachCsvFile() {
response().setContentType("text/csv");
response().setHeader(CONTENT_DISPOSITION,
String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
return ok(Play.application().getFile(CSV_FILE));
}
Play 2.5
static private final String CSV_FILE_NAME = "demo.csv";
...
public Result attachCsvFile() {
response().setHeader(CONTENT_DISPOSITION,
String.format("attachment; filename=\"%s\"", CSV_FILE_NAME));
return ok(Play.current().getFile(CSV_FILE)).as("text/csv");
}
Sounds like you're looking to do something like this:
public Result downloadCsv() {
response().setHeader("Content-disposition", "attachment; filename=example.csv");
return ok(Play.application().getFile("conf/resources/example.csv"));
}
PlayFramework already have a method to delivery files as attachments (see Results.ok too). Just do the following:
public Result deliveryFile() {
File file = ...
boolean inline = true;
return ok(file, inline);
}
Keep in mind that is up to you to ensure the file exists and is readable.

Java REST service. Info is not saved to file and my code doesnt read the file

I am creating my first Rest service using JSON objects for the data
transfer between user and server, with the help of the Gson library 2.5.
I am not using any frameworks like Jersey or anything like that. (That was my
project requirment). The java version i use is 1.6 (part of my requirment)
jboss server and Eclipse as IDE.
At the moment i have 2 small functions from a simple HTML form. The first is
suposed to requests the data from the JSON file and the second is suposed to
add a new json information to the json document.
Problem is: When i try to acces the JSON file, a array its returned with the
last submited Person. When i save a new Person information, that information is
not saved in the personsJsonFile but someplace else [have no ideea where].
My json file is found in the Projects main folder.
Any help is deeply apreciated.
GetData class:
#Path("/data")
public class GetDataClass {
#GET
#Produces("text/plain")
public ArrayList<PersonConstructor> displayJsonFile() throws IOException{
ArrayList<PersonConstructor> newLib = new ArrayList<PersonConstructor>();
File jsonFile = new File("personsJsonFile.json");
Scanner fileInput = new Scanner(jsonFile);
Gson gson = new Gson();
while(fileInput.hasNextLine()){
String jsonLine = fileInput.nextLine();
PersonConstructor singlePerson = gson.fromJson(jsonLine, PersonConstructor.class);
newLib.add(singlePerson);
}
fileInput.close();
return newLib;
}
}
AddData Class:
#Path("/add")
public class AddPersonsClass {
#POST
public String addPersons(
#FormParam("idInput") int idInput,
#FormParam("surnameInput") String surnameInput,
#FormParam("nameInput") String nameInput
) throws IOException
{
Gson gson = new Gson();
PersonConstructor newPerson = new PersonConstructor();
newPerson.setPersonId(idInput);
newPerson.setPersonNume(nameInput);
newPerson.setPersonPrenume(surnameInput);
File jsonFile = new File("personsJsonFile.json");
FileWriter jsonWriter = new FileWriter(jsonFile);
System.out.println(newPerson);
String jsonLine = gson.toJson(newPerson);
System.out.println(newPerson);
jsonWriter.write(jsonLine+"\n");
jsonWriter.close();
return "Element: " + newPerson + "has been added";
}
}
PersonConstructor Class:
public class PersonConstructor {
private int personId;
private String personNume;
private String personPrenume;
public PersonConstructor(int personId, String personNume,String personPrenume){
this.personId = personId;
this.personPrenume = personPrenume;
this.personNume = personNume;
}
public PersonConstructor() {
}
public int getPersonId(){
return personId;
}
public void setPersonId(int personId){
this.personId = personId;
}
public String getPersonNume(){
return personNume;
}
public void setPersonNume(String personNume){
this.personNume = personNume;
}
public String getPersonPrenume(){
return personPrenume;
}
public void setPersonPrenume(String personPrenume){
this.personPrenume = personPrenume;
}
public String toString(){
return String.format("\n%s %s %s\n", this.personId, this.personNume, this.personPrenume);
}
}
Json file contains:
{"personId":5,"personNume":"Ursu","personPrenume":"Niculae"},
{"personId":6,"personNume":"Ivan","personPrenume":"Claudiu"},
{"personId":7,"personNume":"Hap","personPrenume":"Dorel"}
Your problem seems to that you have not specified the path where to save the file.
Add the path when creating a file.
final String jsonDirectory = "path to file";
File file = new File(jsonDirectory + "\\results.txt");

Categories