How Can I extract the .dat file(contain image) using java API - java

if i using HMEFContentsExtractor in POI jar, it can extract html only it is not able extract the image content form winmail.dat(attchment mail sent from oulook), is there any jar file to do this & explain how to use that.
HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));
File dir = new File(directoryName);
File rtf = new File(dir, "message.rtf");
if(! dir.exists()) {
throw new FileNotFoundException("Output directory "+dir.getName()+" not found");
}
HMEFMessage msg = new HMEFMessage(new FileInputStream(winmailFilename));
msg.getAttachments();ext.extractMessageBody(rtf);

Related

How to create temp directory in heroku/docker using Java?

I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if (!tempDirectory.exists()) {
tempDirectory.mkdir();
}
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if(tempDirectory.exists()){
System.out.println("something");
}else{
tempDirectory.mkdirs();
}
File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
if(!file.exists()){
file.createNewFile();
}
String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();
System.out.println(file2);
Works totally fine at my end. The only problem you might be having is
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();
This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using
file.transferTo(wherefileneedstobesavedlocation);

how to include signature in outlook javamail

I'm trying to create an email using javamail where i can attach many files and also configure the body message , destination and many settings... at the end i save this email in a temp file to use it in outlook 2016 where i can now open outlook and pass the eml file using outlook command line with switch /eml.
The problem is is a try to attach one file with outlook using the switch /a, i can see the signature the footer of the body message but when i use the created eml file i can not see any signature.
what i tried to do is to load the pre-saved signature in roaming folder from different format (htm, rtf and txt) with txt file there is no problem and can put it inside the message in eml file but using rtf i cannot visualize the content as i see in ms word, using the htm file the images (if exist) still not visible.
I'm wondering how i can use one of the two (html or rtf file) to include the signature in the bottom of the body message automatically.
Hope that someone already worked on the same subject.
I think you can take a snapshot of the signature and save it in a particular directory and send a HTML email by inserting the image . You can find something here on how you can send inline HTML images in the message body. Hope it helps.
The problem is mainly in the path's image included in the htm file, so I parsed the original path with the absolute one, so i can visualize the image correctly
public static String getSignature() throws IOException {
String content ="";
String appDataPath = System.getenv("APPDATA")+"\\Microsoft\\Signatures\\";
System.out.println(appDataPath);
File folder = new File(appDataPath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".htm")) {
content = FileUtils.readFileToString(file , "windows-1252");
content =content.replaceAll("src=\"", "src=\"" +appDataPath.replace("\\", "/"));
}
}
return content;
}
Then I retrieve the content and I put it inside the message that I want to send.
MimeBodyPart body = new MimeBodyPart();
body.setDisposition(MimePart.INLINE);
body.setContent(signature, "text/html");
mmp.addBodyPart(body);
I added some enhancement on the code:
public static String[] getSignature() throws IOException {
String content = "";
String appDataPath =System.getenv("APPDATA") + "\\Microsoft\\Signatures\\";
System.out.println(appDataPath);
File folder = new File(appDataPath);
File[] listOfFiles = folder.listFiles();
String imagePath ="";
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".htm")) {
content = FileUtils.readFileToString(file, "windows-1252");
content = content.replaceAll("src=\"", "src=\"" + appDataPath.replace("\\", "/"));
}else if(file.isDirectory()){
File[] listOfHtmlFiles = file.listFiles();
for (File f : listOfHtmlFiles) {
if(Files.probeContentType(f.toPath()).contains("image")) {
imagePath = f.getPath();
}
}
}
}
return new String[]{content,imagePath};
}
i this new code i retrieve the signature from html and the image path from html files folders.
Then i created image an image as joint file ( attached to the email)
then i modify src in the signature as follow :
MimeBodyPart imgBP = new MimeBodyPart();
DataSource fds = new FileDataSource(imgPath);
imgBP.setDataHandler(new DataHandler(fds));
imgBP.setHeader("Content-ID", "<image>");
mmp.addBodyPart(imgBP);
signature = signature.replaceFirst("(src=)([\"|\'])(.*)([\"|\'])",
"$1$2cid:image$4");
MimeBodyPart body = new MimeBodyPart();
body.setDisposition(MimePart.INLINE);
body.setContent("<br><br><br>" + signature, "text/html");
mmp.addBodyPart(body);

File picker for uploading to Google Drive

I'm learning about Google Api for uploading file on Android and did find the good sample about it.(you can take a look on that sample here:
https://github.com/sdivakarrajesh/Uploading-Files-to-Google-drive-using-java-client-api-in-Android/blob/master/app/src/main/java/com/dev/theblueorb/usingdrivejavaapi/DriveActivity.java)
However, it's only show how to upload files, not how to select the file and upload it to GG drive. Here are the code for uploading and creating folder on GG drive:
private void uploadFile() throws IOException {
File fileMetadata = new File();;
fileMetadata.setName("Sample File");
fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
// For mime type of specific file visit Drive Doucumentation
file2 = new java.io.File(path);
InputStream inputStream = getResources().openRawResource(R.raw.template);
try {
FileUtils.copyInputStreamToFile(inputStream,file2);
} catch (IOException e) {
e.printStackTrace();
}
FileContent mediaContent = new FileContent("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",file2);
File file = mService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
Log.e(this.toString(),"File Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"File created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
}
private void createFolderInDrive() throws IOException {
File fileMetadata = new File();
fileMetadata.setName("Sample Folder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(),"Folder Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"Folder created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
Any body knows how to select the file on device, then upload it to selected folder on GG drive or the sample for that?
Referencing these docs for basic file upload, you should be able to "select the file on device" by specifying the complete file path as fileName in this line below:
java.io.File fileContent = new java.io.File(filename);.
For example, if you had a file called coolpic inside the directory media, you could use media/coolpic for the filename. The next doc I reference reinforces this strategy. The path will depend on the root location which, is something you can easily investigate.
Then, check out this doc for working with folders in Google Drive. You'll want to find the folder id and set this on upload using
fileMetadata.setParents(Collections.singletonList(folderId));
Note you can upload and then move in two steps, or use my method above and set the folder on upload.

how to upload file to Box subfolder using Java SDK

How to upload files to my Box Sub-Folder using either by subfolder name or ID
Example say I have 2 subfolders(subfolder1 and subfolder2) in my Box, How to upload files to subfolder2 using java sdk.
Can we upload using any new methods.
Successful in uploading files to Box root folder using the code below
BoxFolder bfolder = BoxFolder.getRootFolder(api);
FileInputStream stream= null;
filePath = "c:\\UploadFile.txt";
stream = new FileInputStream(filePath);
fileName = FilenameUtils.getBaseName(filePath.toString());
bfolder.uploadFile(stream, fileName);
You probably need to enumerate the folders till you find subfolder1, then create a new BoxFolder from that. Something like this (edit for compile errors):
BoxFolder bfolder = BoxFolder.getRootFolder(api);
Iterator<BoxFolder.Info> it = bfolder.getChildren().iterator();
for(BoxFolder.Info i : it){
if(i.getName().equals(subfolder1)){
BoxFolder folder = new BoxFolder(api, i.getID());
FileInputStream stream= null;
filePath = "c:\\UploadFile.txt";
stream = new FileInputStream(filePath);
fileName = FilenameUtils.getBaseName(filePath.toString());
folder.uploadFile(stream, fileName);
break;
}
}

How to store uploaded mulitple pdf file to a specific location in java?

i want to store uploaded file in a specific location in java. if i upload a.pdf then i want it to store this at "/home/rahul/doc/upload/". i went through some questions and answers of stack overflow but i am not satisfied with solutions.
i am working with Play Framework 2.1.2. i am not working with servlet.
i am uploading but it is storing file into temp directory but i want that file store into a folder as not a temp file i want that file like a.pdf in folder not like temp file.
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
but i am not satisfied with this solution and i am uploading multiple doc files.
for eg. i upload one doc ab.docx then after upload it is storing temp directory and file is this:
and it's location is this: /tmp/multipartBody5886394566842144137asTemporaryFile
but i want this: /upload/ab.docx
tell me some solution to fix this.
Everything's correct as a last step you need to renameTo the temporary file into your upload folder, you don't need to play around the streams it's as simple as:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
BTW you should implement some checking if targetPath doesn't exist to prevent errors and/or overwrites. Typical approach is incrementing the file name if file with the same name already exists, for an example sending a.pdf three times should save the files as a.pdf, a_01.pdf, a_02.pdf, etc.
i just completed it. My solution is working fine.
My solution of uploading multiple files is :
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}

Categories

Resources