I want to validate an uploaded image, that file is an image or not.
For this I am using Tika Parser, it parses it correctly but I get input stream as empty after parsing.
public static FileType checkFileType(InputStream inputStream) throws IOException, SAXException, TikaException,
InvalidArgumentException {
ContentHandler contenthandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
ParseContext context = new ParseContext();
parser.parse(inputStream, contenthandler, metadata, context);
//inputStream.close();
String contentType = metadata.get(Metadata.CONTENT_TYPE);
}
I am getting input stream from org.apache.cxf.jaxrs.ext.multipart.Attachment
InputStream inputStream = attachment.getDataHandler().getInputStream();
Related
I'm trying to use an existing PDF template and iText to fill in the document, then send the file to our database.
However, I cannot figure out how to convert the finished iText PDF into a usable form - I can display it to the user easily enough, but I cannot get it into a File, InputStream, or even byte[] format to upload to our Database.
public ActionForward doIt(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
{
int docid = Integer.parseInt(form.getDocumentTemplateId());
byte[] byteTemplate = TemplateDb.getTemplate(docId);
PdfReader pdfReader = new PdfReader(byteTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, response.getOutputStream());
AcroFields acroFields = pdfStamper.getAcroFields();
acroFields.setField(//And then I set my acro fields, which works fine);
ByteArrayInputStream inByteStream = new ByteArrayInputStream(byteTemplate );
// This is me calling a separate function to upload the Input Stream - but all that the inByteStream object contains is a blank template
DocumentManager.uploadDocument(inByteStream);
pdfStamper.close();
pdfReader.close();
}
I need to return a PDF document from a Spring Boot #Controller along with the password required to open it.
I get the filename as PathParam user/document/{filename}.
How do I achieve this?
There's nothing specific to spring-boot for that, it's handled with a good old Spring MVC's.
This other answer from #Infeligo explains it perflectly:
#RequestMapping(value = "user/document/{filename}", method = RequestMethod.GET)
public void getFile(
#PathParam("filename") String fileName,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}
}
You could set the password in a header field (how much does it need to be secure?):
response.addHeader("pdf_password", "thisIsThePassword");
I want to send mail with attachment in java with the following criteria -
The file which I want to attach is a downloadable URL
(like : http://berkeleycollege.edu/browser_check/samples/excel.xls)
Code is deployed on appengine, so Write to File, Create File, Save File is prohibited by google.
I don't even have the permission to download the file first and attach it as an attachment.
I have tried InputStream input = new URL(url).openStream(); to read the file content pass that to a datahandler. Where url is mentioned above. Sample Code:
Message msg = new MimeMessage(session);
Multipart multiPart = new MimeMultipart();
MimeBodyPart attachment = new MimeBodyPart();
DataHandler handler;
InputStream input = new URL(url).openStream();
handler = new DataHandler(new ByteArrayDataSource(input,"xls");
attachment.setDataHandler(handler);
multiPart.addBodyPart(attachment);
msg.setContent(multiPart);
Transport.send(msg);
Above code is giving Invalid Content error.
Is there anyway, I can read the content of that downloadable link and that content can be send as attachment ?
Please share the code snippet for the reference.
Map model = new HashMap();
String text = null;
Properties properties_mail = new Properties();
InputStream iStream_mail = null;
String propFileName_mail = "properties/mail.properties";
InputStream stream_mail = getClass().getClassLoader().getResourceAsStream(propFileName_mail);
properties_mail.load(stream_mail);
MimeMessage message = this.javamailsenderImpl.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_RELATED, "UTF-8");
mimeMessageHelper.setFrom(properties_mail.getProperty("javaMailSender.username"));
mimeMessageHelper.setTo(user.getUserEmail());
mimeMessageHelper.setSubject("Bpa Qa Product - New Organisation User");
/*String mailBody = "Welcome New User!!! <br /> Your Login Id is : "+user.getUserEmail()+"Your Password is:"+user.getUserPassword();
mimeMessageHelper.setText(mailBody, true);*/
model.put("firstName", user.getFirstName());
model.put("userEmail", user.getUserEmail());
model.put("userPassword", user.getUserPassword());
model.put("organizationName", user.getOrganization().getOrganizationName());
model.put("heading", "Thank You for Registering with us .!! Here is your Login credentials.");
text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "UserDetails.vm", "UTF-8", model);
mimeMessageHelper.setText(new String(text.getBytes(), "UTF-8"), true);
this.javamailsenderImpl.send(message);
i have a form with a FormPanel, a FileUpload and a Button
final FormPanel formPanel = new FormPanel();
formPanel.setAction("uploadServlet");
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setSize("100%", "100%");
setWidget(formPanel);
AbsolutePanel absolutePanel = new AbsolutePanel();
formPanel.setWidget(absolutePanel);
absolutePanel.setSize("249px", "70px");
final FileUpload fileUpload = new FileUpload();
fileUpload.setName("uploadFormElement");
absolutePanel.add(fileUpload, 0, 0);
Button btnOpen = new Button("Open");
absolutePanel.add(btnOpen, 10, 30);
Button btnCancel = new Button("Cancel");
absolutePanel.add(btnCancel, 63, 30);
this.setText("Open...");
this.setTitle(this.getText());
this.setAnimationEnabled(true);
this.setGlassEnabled(true);
btnOpen.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
formPanel.submit();
}
});
the servlet gets called but the request contains a error message "error post".
When i try it on the local server it works, the request contains the file, but on the app engine server only the error
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = null;
String json = null;
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) {
e.printStackTrace();
}
Iterator<?> it = items.iterator();
while (it.hasNext()) {
System.out.println("while (it.hasNext()) {");
FileItem item = (FileItem) it.next();
json = item.getString();
}
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
response.setContentLength(json.length());
out.write(json.getBytes());
out.close();
}
DiskFileItemFactory is the default implementation for the commons-fileupload library, and based in it's javadoc:
This implementation creates FileItem instances which keep their content either in memory, for smaller items, or in a temporary file on disk, for larger items. The size threshold, above which content will be stored on disk, is configurable, as is the directory in which temporary files will be created.
If not otherwise configured, the default configuration values are as follows:
Size threshold is 10KB. Repository is the system default temp directory, as returned by System.getProperty("java.io.tmpdir").
So as you see, this implementation is going to write in filesystem when it does not have enough memory.
In GAE, there are many constrains, like the memory you are allow to use, or the prohibition of writing in the filesystem.
Your code should fail in GAE developing mode, but maybe you have not reached the memory limitation, or whatever since GAE dev tries to emulate the same constrains than production server, but it is not identical.
Said, that I could take a look to gwtupload library, they have a servlet for GAE which can save files in different ways: BlobStore, FileApi and MemCache.
I am developing an web application which can upload/download a file from client to PostgreSQL database server via GWT RPC call.
I managed to create an upload servlet which store desired file(choosed by user via FileUpload widget) to Glassfish "TEMP" directory => then i used SQL command:
INSERT INTO table VALUES ('"+name+"',lo_import('"+f.getCanonicalPath()+"\\TEMP\\"+name+"'),...)
which put that file into database. This works pretty good.
Problem occurs when i want to download file from server to client. First i need to put the file back to TEMP dir with SQL command lo_export(...) -> this didn't work (some ERROR when creating a server file, permission denied), so i put the file manually to TEMP dir.
Question is how can i display that file which is stored on server in TEMP dir?
my path to glassfish server temp dir:C:\Program Files (x86)\glassfish-3.1\glassfish\domains\domain1\TEMP\example.pdf
when deploying app url looks like: http://localhost:8080/AppName/
i tried something like that: Window.open("http://localhost:8080/AppName/TEMP/example.pdf", "_blank", "enabled")
My CODE:
Client side:
String link = GWT.getModuleBaseURL() + "filedownloadservlet";
Window.open(link,event.getSelectedItem().getText(),"enabled");
so i pass to servlet located on server side a link and a file name...am i right ?
Server side:
public class FileDownloadServlet extends HttpServlet {
private String path = "TEMP//"; // Your absolute path
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename = req.getParameter("filename");
System.out.println(filename); // THIS IS NULL value
File userManualFile = new File(path + filename);
// You can fetch a Blob from the database instead.
ServletOutputStream servletOutputStream = resp.getOutputStream();
resp.setContentType("application/pdf");
resp.addHeader("content-disposition", "attachment; filename=skuska.pdf");
FileInputStream fileInputStream = new FileInputStream(userManualFile);
IOUtils.copy(fileInputStream, servletOutputStream);
servletOutputStream.flush();
When i press a file in Tree widget it shows me a new browser window with this error:
java.io.FileNotFoundException: TEMP\null (The system cannot find the file specified)
You cannot download a file with a RPC call. You must use a normal java servlet. You have to write the bytes into the HttpServletResponse. You can get the bytes from the file in the database by doing an SQL query.
This example is done with spring MVC.
#Controller
public class UserManualServlet {
private String path = "..." // Your absolute path
#RequestMapping("/app/usermanual.download")
public void generateInterceptActivationDeactivationReport(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String filename = request.getParameter("filename");
File userManualFile = new File(path + filename);
// You can fetch a Blob from the database instead.
ServletOutputStream servletOutputStream = response.getOutputStream();
response.setContentType("application/pdf");
response.addHeader("content-disposition", "attachment; filename=\"user-manual.pdf\"");
FileInputStream fileInputStream = new FileInputStream(userManualFile);
IOUtils.copy(fileInputStream, servletOutputStream);
servletOutputStream.flush();
}
In this example, you can call the URL : ../app/usermanual.download?filename=usermanual.pdf to download the file.