TelegramBot. SenDocument pdf - java

I send file pdf through custom app telegramBot to client in telegram. Client get .txt (default type)
// file = "application/pdf;base64,JVBERi0xLjMN...DAwMT=="
private String sendFileToClient(String clientExtId, String file) {
String fileLink;
byte[] data = DatatypeConverter.parseBase64Binary(file);
SendDocument sendDocument = new SendDocument(clientExtId, data);
try {
SendResponse execute = telegramBot.execute(sendDocument);
Document document = execute.message().document();
final String documentId = document.fileId();
fileLink = getFileLink(documentId);
return fileLink;
} catch (Exception e) {
....
}
}
public String getFileLink(String fileId) {
GetFile getFile = new GetFile(fileId);
GetFileResponse fileResponse = telegramBot.execute(getFile);
File file = fileResponse.file();
log.info("getRelativeFilePath filePath : {}", file.filePath()); // documents/file_203.txt ????
return telegramBot.getFullFilePath(file);
}
Why my file return .txt not pdf?
when I send photo, return - photos/file_202.jpg
What problem? Pls help)
UP: compile('com.github.pengrad:java-telegram-bot-api:X.X.X')

solution:
new SendDocument(clientExtId, data).fileName(fileName.pdf);

Related

How to solve ERROR java.nio.file.AccessDeniedException: D:\workspace_intellij_forKiri\Kiri\server\kiri\temp\28004d6bc31cfiles.png

I am going to convert MultipartFile to File and upload it to S3 bucket.
However, when running the test, an error occurs in the process of converting MultipartFile to File.
ERROR : java.nio.file.AccessDeniedException: D:\workspace_intellij_forKiri\Kiri\server\kiri\temp\8b28a2f2-7276-4036
multipartFile.transferTo(file);
Please advise if there is anything I am missing.
The spring boot version is 2.7.7 version.
Test code
#WithAccount("creamyyyy")
#DisplayName("image save test")
#Test
public void createImageTest() throws Exception {
//given
String filename = "files";
String contentType = "png";
MockMultipartFile image1 = new MockMultipartFile(
filename,
filename + "." + contentType,
"image/png",
filename.getBytes());
//when
//then
this.mockMvc.perform( //== ERROR!!!
MockMvcRequestBuilders
.multipart("/api/posts/image")
.file(image1)
.contentType(MediaType.MULTIPART_FORM_DATA)
.characterEncoding("UTF-8")
)
.andDo(print())
.andExpect(status().isOk());
}
ImageService Code
// FileSave
public List<ImageResDto> addFile(List<MultipartFile> multipartFiles) throws IOException {
List<ImageResDto> imageResDtoList = new ArrayList<>();
/**
* <ImageResDto>
* private Long image_id;
* private String imgUrl;
*/
String absolutePath = new File("").getAbsolutePath() + File.separator + "temp";
for (MultipartFile multipartFile : multipartFiles) {
String contentType = multipartFile.getContentType();
if(ObjectUtils.isEmpty(contentType)) {
throw new RuntimeException("FILE TYPE NOT FOUND");
} else if(!verifyContentType(contentType)){
throw new RuntimeException("FILE TYPE NOT FOUND");
}
}
for (MultipartFile multipartFile : multipartFiles) {
String filename = UUID.randomUUID() + multipartFile.getOriginalFilename();
// save in local
String fullFilePath = absolutePath + File.separator + filename;
System.out.println("fullFilePath = " + fullFilePath);
File file = new File(fullFilePath);
if(!file.exists()) { file.mkdirs(); }
multipartFile.transferTo(file); // ERROR ... OTL
file.createNewFile();
// S3 upload
amazonS3.putObject(
new PutObjectRequest(bucket, filename, file)
.withCannedAcl(CannedAccessControlList.PublicRead)
);
String imgUrl = amazonS3.getUrl(bucket, filename).toString();
Image newImage = Image.builder()
.filename(filename)
.filepath(filename)
.imgUrl(imgUrl)
.build();
imageRepository.save(newImage);
ImageResDto imageResDto = ImageResDto.of(newImage);
imageResDtoList.add(imageResDto);
file.delete(); // local file delete
}
return imageResDtoList;
}
ImageController Code
#PostMapping(value = "/api/posts/image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity createImage(#RequestPart(value = "files") List<MultipartFile> multipartFiles) throws IOException {
System.out.println("ImageController Runnnn");
// get member
PrincipalDetails principalDetails = (PrincipalDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Member member = principalDetails.getMember();
List<ImageResDto> imageResDtoList = imageService.addFile(multipartFiles);
return new ResponseEntity(imageResDtoList, HttpStatus.CREATED);
}
I tried to specify a separate route using Path, but I failed.
// Error ..java.nio.file.AccessDeniedException => Path
// multipartFile -> File
Path path = Paths.get(fullFilePath).toAbsolutePath();
multipartFile.transferTo(path.toFile());
Files.createFile(path);
What is incomprehensible is that when tested using PostMan, the file is normally uploaded to the S3 bucket.
Please tell me if I applied anything wrong.

How to write JUnit Test for uploading Image in Amazon S3 in Spring Boot

I have a problem about writing a test to upload Image in Amazon s3 in Spring Boot.
I tried to write its test method but I got an error shown below.
How can I fix it?
Here is the method of Rest controller
#RestController
#RequestMapping("/api/v1/bookImage")
#RequiredArgsConstructor
public class ImageRestController {
#PostMapping
public ResponseEntity<String> uploadImage(#RequestParam("bookId") Long bookId, #RequestParam("file") MultipartFile file) {
final String uploadImg = imageStoreService.uploadImg(convert(file), bookId);
service.saveImage(bookId, uploadImg);
return ResponseEntity.ok(uploadImg);
}
private File convert(final MultipartFile multipartFile) {
// convert multipartFile to File
File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(multipartFile.getBytes());
return file;
} catch (IOException e) {
throw new RuntimeException("Failed to convert multipartFile to File");
}
}
Here is the method of imageService.
public String uploadImg(File file, Long bookId) {
s3amazon.putObject(BUCKET_NAME, bookId.toString(), file);
return baseUrl + bookId;
}
Here is the test method shown below.
#Test
void itShouldGetImagePath_WhenValidBookIdAndFile() throws Exception{
// given - precondition or setup
String bookId = "1";
String imagePath = "amazon-imagepath";
String baseUrl = String.format(imagePath + "/%s", bookId);
Long bookIdValue = 1L;
MockMultipartFile uploadFile = new MockMultipartFile("file", new byte[1]);
// when - action or the behaviour that we are going test
when(imageStoreService.uploadImg(convert(uploadFile), bookIdValue)).thenReturn(baseUrl); -> HERE IS THE ERROR
// then - verify the output
mvc.perform(MockMvcRequestBuilders.multipart("/api/v1/bookImage")
.file(uploadFile)
.param("bookId", bookId))
.andExpect((ResultMatcher) content().string(baseUrl))
.andExpect(status().isOk());
}
private File convert(final MultipartFile multipartFile) {
// convert multipartFile to File
File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(multipartFile.getBytes());
return file;
} catch (IOException e) {
throw new RuntimeException("Failed to convert multipartFile to File");
}
}
Here is the error : Failed to convert multipartFile to File (java.lang.RuntimeException: Failed to convert multipartFile to Filejava.io.FileNotFoundException: )
How can I fix it?
Here is the solution shown below.
#Test
void itShouldGetImagePath_WhenValidBookIdAndFile() throws Exception{
// given - precondition or setup
String bookId = "1";
String imagePath = "amazon-imagepath";
String baseUrl = String.format(imagePath + "/%s", bookId);
Long bookIdValue = 1L;
String fileName = "sample.png";
MockMultipartFile uploadFile =
new MockMultipartFile("file", fileName, "image/png", "Some bytes".getBytes());
// when - action or the behaviour that we are going test
when(imageStoreService.uploadImg(convert(uploadFile), bookIdValue)).thenReturn(baseUrl);
doNothing().when(bookSaveService).saveImage(bookIdValue,baseUrl);
// then - verify the output
mvc.perform(MockMvcRequestBuilders.multipart("/api/v1/bookImage")
.file(uploadFile)
.param("bookId", bookId))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$").value(baseUrl))
.andExpect(content().string(baseUrl));
}

How could I download a PDF generated without store it on the server?

I have a Jhipster application that generate PDF with iText library, this PDF is saved in the computer in the route that I indicated.
I would like that when generating the pdf, a dialog box will appear to download the pdf. I am indifferent if the pdf is saved in the project folder or not saved in any place.
I have seen many posts giving possible answers on this page and on the internet, but many are already obsolete and others have not worked for me.
generatePDF
public void generatePDF(User u) {
String dest = "D:/PDF/result.pdf";
String src = "D:/PDF/template.pdf";
try {
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue(u.getFirstName());
fields.get("surname").setValue(u.getLastName());
fields.get("email").setValue(u.getEmail());
pdf.close();
} catch (IOException e) {
log.debug(e.getMessage());
}
}
UserResource
#GetMapping("/print-user/{id}")
#Timed
public ResponseEntity<User> printUserTemplate(#PathVariable Long id) {
User user = userRepository.findOne(id);
userService.generatePDF(user);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(user));
}
EDIT
entity.component.ts
downloadFile() {
this.entityService.downloadFile().subscribe();
}
entity.service.ts
downloadFile(): Observable<any> {
return this.http.get(SERVER_API_URL + 'api/downloadFile');
}
Use this to download the file:
#GetMapping("/downloadFile")
public ResponseEntity<Resource> downloadFile(HttpServletRequest request) {
// Load file as Resource
Resource resource = testService.loadFileAsResource();
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
log.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(
HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource);
}
And this to generate the file:
public Resource loadFileAsResource() {
try {
Path path = Paths.get("D:\\PDF\\template.pdf");
Path filePath = path.normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
return null;
}
}
References:
https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
download a file from Spring boot rest service

Upload document on google drive in a folder

I want to upload my document on google drive but in a folder. can you please suggest how i insert this into the folder. I have uploaded but this is not in folder. Code is -
#RequestMapping(value = "/uploadDDFile", method = RequestMethod.POST)
public ModelAndView uploadDDFile(#RequestParam(value = "ddid", required = true) Integer ddid,
#RequestParam(value = "catageryId", required = true) Integer catageryId,
#RequestParam(value = "document", required = true) GMultipartFile document[], HttpServletRequest request) {
System.out.println("-------------------------");
String name = "";
DdeDriveDocuments ddeDriveDocuments = new DdeDriveDocuments();
if (ServletFileUpload.isMultipartContent(request) && document != null) {
for (GMultipartFile gdocument : document) {
try {
boolean user = true;
List<DdeDriveDocuments> dds = ddeDriveDocumentsService.fatchData(ddid, catageryId);
for (DdeDriveDocuments file : dds) {
System.out.println(file.getDocument_name());
if (file.getDocument_name().equals(gdocument.getOriginalFilename())) {
user = false;
}
}
if (user == true) {
Client client = sessionService.getClient();
System.out.println(gdocument.getOriginalFilename());
ddeDriveDocuments
.setDocument_name((gdocument.getName() != null ? gdocument.getOriginalFilename() : ""));
ddeDriveDocuments.setDocument_uploadby(client.getEmail());
ddeDriveDocuments.setDocument_created(new Date());
ddeDriveDocuments.setCatagery_id(catageryId);
ddeDriveDocuments.setDd_id(ddid);
ddeDriveDocuments.setDd_uuid(GeneralUtil.getUUID());
ddeDriveDocuments.setClientID(client.getClientID());
Lawyer googleAuthToken = lawyerService
.getAuthorisedUserToken(Configurator.getInstance().getDriveAccountEmail());
if (googleAuthToken != null) {
// upload file in drive
if (ServletFileUpload.isMultipartContent(request) && document != null) {
// It's value either we need to get from form.
String description = "Testing";
File file = DriveService.uploadDocumentToDrive(googleAuthToken, gdocument,
ddeDriveDocuments.getDocument_name(), description);
File thumFile = DriveService.getFileById(googleAuthToken, file.getId());
System.out.println("thumFile ====" + thumFile);
System.out.println("thab url" + thumFile.getIconLink());
if (file != null) {
ddeDriveDocuments.setDocument_drive_id(file.getId());
ddeDriveDocuments.setImageurl(thumFile.getIconLink());
ddeDriveDocuments = ddeDriveDocumentsService.create(ddeDriveDocuments);
}
}
} else {
System.out.println("Autorised token not available for configured drive account.");
}
} else {
System.out.println("wroung Input");
System.out.println("wroung Input");
name = name.concat(gdocument.getOriginalFilename() + " , ");
System.out.println("This is ::::::::::::: " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(name !=""){
sessionService.setUnupload_files_name(name);
}
return new ModelAndView("redirect:/al/client/ddeclientportal/" + ddid + "/" + catageryId);
}
public static File uploadDocumentToDrive(Lawyer googleAuthToken,
GMultipartFile file, String fileName, String description) {
File driveFile = null;
try {
InputStream fileStream = file.getInputStream();
String mimeType = DocumentListEntry.MediaType.fromFileName(
file.getOriginalFilename()).getMimeType();
GoogleCredential googleCrednetial = getGoogleCredential(googleAuthToken);
Drive drive = buildService(googleCrednetial);
String file_name = fileName.contains(FilenameUtils.getExtension(file.getOriginalFilename())) ? fileName : fileName + "." + FilenameUtils.getExtension(file.getOriginalFilename());
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
} catch (Exception e) {
e.printStackTrace();
}
return driveFile;
}
Please help i want insert my document in folder.
By Using
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
body.setParents(Arrays.asList(new ParentReference().setId(driveFile.getId())));
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
Now can you please suggest how i can generate subfoler.

Write String into a file, which the user chooses from <input type="file">

I want to write a String to a file, which the user chooses from . I'm unable to do it because I need the fileName and fileLocation to write my String to the file. But the request.getParamater("") gives me just the fileName. I know that it won't return the fileLocation because of security issues. Then, how do I write my String from the file chosen on my jsp. Please advise.
You cannot write to that file directly.
Short answer : Make a copy file on server.
Long answer:
1) Get the file.
2) Save it on server.
3) Append to that file. Do not overwrite.
4) Again send back the file to user with response.
Do some steps
Get file name using getFileName() method. Store it on server side
if some one wants to Save Same file name again then you append Some Date after file Name. so you can easily get all the files without any code changes.
After write String into file close the file and flush .
See i have upload the file form Front End and Store it on Some local system . when you try to upload Same file again then it append Date with File name
public class uploadFile {
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String upload() throws IOException {
try {
destPath = System.getProperty("user.home") + System.getProperty("file.separator") + "File-Uploads";
File destFile = new File(destPath, myFileFileName);
File file1 = new File(destFile.toString());
boolean b = false;
Date date = new Date();
if (!(file1.exists())) {
b = file1.createNewFile();
}
if (b) {
FileUtils.copyFile(myFile, destFile);
} else {
String fileContent = "";
File f = new File(file1.toString());
FileInputStream inp = new FileInputStream(f);
byte[] bf = new byte[(int) f.length()];
inp.read(bf);
fileContent = new String(bf, "UTF-8");
System.out.println("file===>" + fileContent);
String filename = destFile.toString() + date;
FileWriter fw = new FileWriter(filename, true);
fw.write(fileContent);
fw.close();
FileUtils.copyFile(myFile, destFile);
}
return SUCCESS;
} catch (IOException e) {
return SUCCESS;
}
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}

Categories