How to read image metadata into text file - image

i am using org.apache.commons.imaging to access metadata of jpeg file and write it to a text file. But instead of writing metadata to file, program writes random characters to text file. Can someone please help me resolve this issue? Following is the code
//Method to access image metadata and write to text file
public void removeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().removeExifMetadata(jpegImageFile, os);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
File metadata=new File("matadata.txt");
if(!metadata.exists()){
metadata.createNewFile();
}
System.out.printf("in try block\n");
FileOutputStream fos = new FileOutputStream(metadata);
TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
PrintStream ps = new PrintStream(myOut);
System.setOut(ps);
System.out.printf("in final block\n");
}
}
//call to removeExifMetadata from main
File imageFile=new File("toddler.jpg");
File out=new File("exif.txt");
e.removeExifMetadata(imageFile, out);

Related

Spring Boot | Upload an image to relative path in resources

I get "System can't find the path specified." when I try to upload an image to project folder inside resources.
Here is my project structure:
|Project
|src
|main
|resources
|META-INF.resources
|images
Project Structural Hierarchy can be seen here in the image format.
I have defined the path as
String path = "\\resources\\images\\" + imageName; File file = new File(path );
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(path );
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
What can be the exact path to images folder under META-INF.resources directory?
The following should work fine:
//App.java
String path = "\\META-INF.resources\\images\\" + imageName;
InputStream is = App.class.getClassLoader().getResourceAsStream(
path);
In a nut shell, use "getClassLoader().getResourceAsStream()" instead of FileInputStream or FileOutputStream.
Following worked for me.
In application.properties I defined my path string as:
image.path = src/main/resources/META-INF/resources/images/uploads/
Here is my uploadImage function in a class file.
#Autowired
private Environment environment;
public String uploadImg(FileUploadEvent event, String imagePrefix) {
String path = environment.getProperty("image.path");
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
String name = fmt.format(new Date())
+ event.getFile().getFileName().substring(
event.getFile().getFileName().lastIndexOf('.'));
name = String.format("%s%s" ,imagePrefix ,name );
String finalPath = String.format("%s%s" ,path ,name);
System.out.println("image is going to save # " +finalPath);
File file = new File(finalPath).getAbsoluteFile();
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
return name;
}
I am not sure whether it will work at production or not. Basically I get absolute path of the project and then append my relatively extracted path. Correct me if I am wrong.

try with resource printwriter

I am trying to learn how to use try with resources. First I tried to put java.io.File myFile = new java.io.File(filename) in the resource parenthesis, but netbeans told me that it is not autoclosable. Am I properly handling this exception? I was under the impression that the Exception would be generated in the line where I define the file class object.
//This method writes to a csv or txt file, specify full filepath (including
//extension) Each value will be on a new line
public void writeFile(String filename)
{
java.io.File myFile = new java.io.File(filename);
try(java.io.PrintWriter outfile = new java.io.PrintWriter(myFile))
{
for (int i = 0; i < size; i++)
{
//print all used elements line by line
outfile.println(Integer.toString(this.getElement(i)));
}
} catch (FileNotFoundException fileNotFoundException)
{
//print error
}
}//end writeFile(String)----------------------------------------------------

Writing to a file in S3 from jar on EMR on AWS

Is there any way in which I can write to a file from my Java jar to an S3 folder where my reduce files would be written ? I have tried something like:
FileSystem fs = FileSystem.get(conf);
FSDataOutputStream FS = fs.create(new Path("S3 folder output path"+"//Result.txt"));
PrintWriter writer = new PrintWriter(FS);
writer.write(averageDelay.toString());
writer.close();
FS.close();
Here Result.txt is the new file which I would want to write.
Answering my own question:-
I found my mistake.I should be passing the URI of S3 folder path to the fileSystem Object like below:-
FileSystem fileSystem = FileSystem.get(URI.create(otherArgs[1]),conf);
FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path(otherArgs[1]+"//Result.txt"));
PrintWriter writer = new PrintWriter(fsDataOutputStream);
writer.write("\n Average Delay:"+averageDelay);
writer.close();
fsDataOutputStream.close();
FileSystem fileSystem = FileSystem.get(URI.create(otherArgs[1]),new JobConf(<Your_Class_Name_here>.class));
FSDataOutputStream fsDataOutputStream = fileSystem.create(new
Path(otherArgs[1]+"//Result.txt"));
PrintWriter writer = new PrintWriter(fsDataOutputStream);
writer.write("\n Average Delay:"+averageDelay);
writer.close();
fsDataOutputStream.close();
This is how I handled the conf variable in the above code block and it worked like charm.
Here's another way to do it in Java by using the AWS S3 putObject directly with a string buffer.
... AmazonS3 s3Client;
public void reduce(Text key, java.lang.Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws Exception {
UUID fileUUID = UUID.randomUUID();
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String fileName = String.format("nightly-dump/%s/%s-%s",sdf.format(new Date()), key, fileUUID);
log.info("Filename = [{}]", fileName);
String content = "";
int count = 0;
for (Text value : values) {
count++;
String s3Line = value.toString();
content += s3Line + "\n";
}
log.info("Count = {}, S3Lines = \n{}", count, content);
PutObjectResult putObjectResult = s3Client.putObject(S3_BUCKETNAME, fileName, content);
log.info("Put versionId = {}", putObjectResult.getVersionId());
reduceWriteContext("1", "1");
context.setStatus("COMPLETED");
}

Display the PDF file stored on the webserver on Browser new window using Spring MVC

I have a requirement to show PDF files in a browser. I use Spring MVC. Is there a way I can do this without using AbstractPdfView? I do not want to render the PDF at runtime. All the PDF files will be stored in my webserver.
This is the code I am using. But this directly downloads the file instead of showing it up in a browser.
#RequestMapping(value = "/download" , method = RequestMethod.GET)
public void doDownload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// get absolute path of the application
ServletContext context = request.getSession().getServletContext();
String appPath = context.getRealPath("");
String filename= request.getParameter("filename");
filePath = getDownloadFilePath(lessonName);
// construct the complete absolute path of the file
String fullPath = appPath + filePath;
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/pdf";
}
System.out.println("MIME type: " + mimeType);
String headerKey = "Content-Disposition";
response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
response.setContentType("application/pdf");
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
Remove the line
response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
This line precisely tells the browser to display a download/save dialog rather than displaying the PDF directly.
Oh, and make sure to close the input sytream in a finally block.

how to upload an image using servlet to an absolute path

I want to upload a file to my project folder. My code is as follows:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File savedFile;
String destination;
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
String userName = (String) session.getAttribute("newUser");
destination = getServletConfig().getServletContext().getContextPath() + "\\" + userName + ".jpeg";
savedFile = new File(destination);
//Check if file exists
if(!savedFile.exists())
savedFile.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
byte[] buffer = new byte[1024];
int len;
//Read from file and write to new file destination
while((len = fileContent.read(buffer)) >= 0) {
bos.write(buffer, 0, len);
}
//Closing the streams
fileContent.close();
bos.close();
}
}
}
When I run the jsp file and browse and select the required image and submit the form, the servlet runs but it throws IOException. The exception is throws by the line where I create a new path using savedFile.createNewFile(). Before I used that code, it threw another FileNotFoundException. I am not sure if the path that I have provided is correct.
Try to use getRealPath() method.
String fileName="/" + userName + ".jpeg";
destination = getServletContext().getRealPath(fileName);
savedFile = new File(destination);

Resources