update profile image functionality is not working while hosting as jar - spring

Hi I am new to Springboot I was trying to develop a application, One of its functionality is to upload profile Image. It was working fine in STS but when I pack it in jar and hosting it on AWS EC2 envirnment I am getting some error while processing that image
Error:
handler for profile picture:
#PostMapping("/process-contact")
public String processContact(#ModelAttribute Contact contact, #RequestParam("profileImage") MultipartFile file,
HttpSession session) {
try {
contact.setUser(user);
user.getContacts().add(contact);
// processing and uploading photo
if (file.isEmpty()) {
System.out.println("File is empty");
contact.setImage("contact.png");
} else {
//Processing Image
InputStream inputStream = file.getInputStream();
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
Files.copy(inputStream, paths, StandardCopyOption.REPLACE_EXISTING);
contact.setImage(file.getOriginalFilename());
}
// Success Message
session.setAttribute("message", new Message("Your contact is added...", "success"));
this.userRepository.save(user);
System.out.println("Successfully Added");
} catch (Exception E) {
E.printStackTrace();
// Failed message
session.setAttribute("message", new Message("Something went wrong "+E.getMessage(), "danger"));
}
return "normal/add_contact_form";
}
It is working fine in IDE after some research I found way of writing data in jar is diffrent could some please help me how can I implemenr it for jar also.
Thankyou

all you need to do is replace this line:
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
With:
Path paths = Paths.get(new FileSystemResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
THat will work like charm.

Related

Saving an image to a newly created folder with Uri?

The app i am creating is supposed to save a picture in a sub folder of the pictures folder. As long as i save the picture to the base folder it works fine, but it returns an error as soon as i try to target the subfolder. Permission for writing/reading external storage are given. Do i need to create the folder another way to use it? How do i get the URI of the folder itself?
The error for v1 is: "Failed to write destination file".
The error for v2 is: "Unknown or unsupported URL:content://media/external/images/media/ProxF/"
private void captureImage(ImageCapture imageCapture)
{
//Folder
File dir = new File(getExternalStoragePublicDirectory(DIRECTORY_PICTURES) +"/ProxF");
try{
if(dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
}catch(Exception e){
e.printStackTrace();
}
//MEDIA API
String FotoString="picture1";
ContentValues contentValues=new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, FotoString);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
//Saving to the picture folder - working
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//V1 - not working
File folder = new File(getExternalStoragePublicDirectory(DIRECTORY_PICTURES).toString() + "/ProxF/");
Uri uri1=Uri.fromFile(folder);
//V2 - not working
Uri uri2 = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI+"/ProxF/")
ImageCapture.OutputFileOptions fileOptions= new ImageCapture.OutputFileOptions.Builder(getContentResolver(),uri,contentValues).build();
imageCapture.takePicture(fileOptions, Executors.newCachedThreadPool(), new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
runOnUiThread(() -> Toast.makeText(KameraAc.this, "Image Saved ",Toast.LENGTH_SHORT).show());
startCamera();
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
runOnUiThread(() -> Toast.makeText(KameraAc.this, "Failed to save: "+exception.getMessage(), Toast.LENGTH_SHORT).show());
startCamera();
}
});
}

Unable to get image after reinstalling the app

I am not able to get the images stored in Parse-Server as a file, once I reinstall the app. It works fine while a user is logged in but once the app is uninstalled only files are unable to access.It shows exception saying :- File doesn't exist . And I am not able to download image in parse server as well .It will redirect me to role section.
Tried changing version of parse in gradle.
I should be able to access images after reinstalling app. And I should be able to download image in parse.
code written to upload image-----------------------
ParseFile filename = new ParseFile("name.png", Byte);
filename.saveInBackground();
classObject.put("imagePic", filename);
classObject.saveInBackground();
Retrieving from Parse server--------------
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if(e == null) {
if(data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
imageView.setImageBitmap(bitmap);
}
}
});

Polling from a network directory

I have been working on the following project, some background:
I am an intern currently developing a new search system for my organization. The current setup is microsoft sharepoint 2013 in which the users upload files etc.. and on the other hand is the system I am developing which indexes all data being uploaded to apache SOLR.
I have been succesfull in mapping the sharepoint content repository to a network drive, and I can manually start my program to start indexing the conent of this network drive to SOLR using the Solrj api.
The problem I am facing however is that I am unable to poll events from this network drive. In my test build which ran local I used a watcher service to launch code (reindex documents, delete indexes) on file create, file modify and file delete.
This does not work unfortunantly with a url pointing to a network drive :(.
So the big question: Is there any API / library available for polling events from network drives?
Any help would be extemely appreciated !
So I fnally figured this one out, tried looking at .net's variant of the watcher service (system.io.filesystemwatcher) and i was having the same problem. I finally got it working by using java.io.FileAlterationMonitor / observer.
Code:
public class UNCWatcher {
// A hardcoded path to a folder you are monitoring .
public static final String FOLDER =
"A:\\Department";
public static void main(String[] args) throws Exception {
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
try {
// "file" is the reference to the newly created file
System.out.println("File created: "
+ file.getCanonicalPath());
if(file.getName().endsWith(".docx")){
System.out.println("Uploaded resource is of type docx, preparing solr for indexing.");
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "
+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "
+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
System.out.println("Starting monitor service");
monitor.start();
}
}

write file into spring boot folder

my spring boot project structure is like this
src
|-main
|--|-java
|--|-resources
static
|-css
|-images
|-js
now I want to write a file into the static/images folder
I tried to new File like
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("static/images")));it will throw "No such file or directory" exception
but in other html file I can get the js by "js/jsFile.js"
new File("static/images") is right
I used new File("/static/images") so I got an Exception
I was in the situation where using Spring Boot I had to save the image into one directory which is accessed statically.
Below code worked perfect
byte[] imageByteArray ....
String fileName = "image.png";
String fileLocation = new File("static\\images").getAbsolutePath() + "\\" + fileName;
FileOutputStream fos = new FileOutputStream(fileLocation);
fos.write(imageByteArray);
fos.close();
Hope it helped.
#zhuochen shen is correct.
The thing is to happen me is Eclipse doesn't show write file. So I looked at file explore. File is writing correctly.
try {
Path path=Paths.get("static/images/"+productDto.getImage().getOriginalFilename());
Files.write(path,productDto.getImage().getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
enter image description here
enter image description here

How to send email with attachments

I want to send an email with an image attached with it. I am using spring 3 with velocity templates. I am able to do that but for some reasons when I add an extension with the image name I don't get the email delivered.
Following is the code I am using for it:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
Using the code above I could add formstack1 as attachment but it has no extension so I don't get the formstack1.jpg image file. But when I use formstack1.jpg for the name of resource to be attached in helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); as formstack1 changed to formstack1.jpg I don't get even the email delivered. I am using smtp.gmail.com and 25 for port. I do get the email sent successfully message on the console though. But the email
is never delivered.
EDIT: If I keep it like helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); and change the extension from nothing to .jpg while downloading the attached image I do get the desired image.
Could someone help me understand why is it happening and how send email with 1 or more attachments using spring 3.
Thanks.
You should better use Apache Commons HtmlEMail
http://commons.apache.org/email/userguide.html

Resources