Apache Commons FileUpload only save a part of the file - apache-commons-fileupload

I'm using a gwt widget gwtupload.client.Uploader, and i'm trying to save the file into a blob column in a database using fileupload streaming api.
The problem is that if the file is bigger than 3k only saves 3k (well 3.25K).
Thanks for the help.
Here is the code:
try {
ServletFileUpload upload = new ServletFileUpload();
upload.setProgressListener(listener);
FileItemIterator iter = upload.getItemIterator(request);
InputStream stream = null;
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
stream = item.openStream();
Object o = getThreadLocalRequest().getSession().getAttribute(PortailServiceIMPL.FICHIER_SESSION_STORE_KEY);
if (o != null && o instanceof Fichier) {
uploadService.sauvegarder((Fichier) o, stream);
listener.update(listener.getContentLength(),
listener.getContentLength(), 0);
} else {
throw new RuntimeException(
"Impossible de recuperer le fichier de la session.");
}
}
if (stream != null) {
stream.close();
}
} catch (SizeLimitExceededException e) {
RuntimeException ex = new UploadSizeLimitException(
e.getPermittedSize(), e.getActualSize());
listener.setException(ex);
throw ex;
} catch (UploadSizeLimitException e) {
listener.setException(e);
throw e;
} catch (UploadCanceledException e) {
listener.setException(e);
throw e;
} catch (UploadTimeoutException e) {
listener.setException(e);
throw e;
} catch (Exception e) {
logger.error("UPLOAD-SERVLET (" + request.getSession().getId()
+ ") Unexpected Exception -> " + e.getMessage() + "\n"
+ stackTraceToString(e));
e.printStackTrace();
RuntimeException ex = new UploadException(e);
listener.setException(ex);
throw ex;
}
The lina that saves the file is :
uploadService.sauvegarder((Fichier) o, stream);
And there are like 4 methods after until reach the the code to save the InputStream (the InputStream is not touched):
public void storeBlob(long id, InputStream pInputStream) throws Exception {
try {
java.sql.Connection conn = //get the connection;
PreparedStatement ps = conn.prepareStatement(SQL_STORE);
ps.setBinaryStream(1, pInputStream, pInputStream.available());
ps.setLong(2, id);
ps.executeUpdate();
ps.close();
em.getTransaction().commit();
} catch (Throwable t) {
em.getTransaction().rollback();
throw new Exception(t);
}
}
If I use the FileItemFactory it worked, but that's not what I want:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> uploadedItems = upload.parseRequest(request);
for (FileItem item : uploadedItems) {
InputStream stream = item.getInputStream();
Thank you for your help.

After some work around, I solved it.
in the storeBlob method i can't use the pInputStream.available(). So, this is the line i used:
ps.setBinaryStream(1, pInputStream);

Related

Apache commons net FTP clients hangs unpredictably

We tried all the solutions provided in this post (FTP client hangs) but none of them is working. We are using version 3.6 of commons net. Sometimes it hangs while uploading a file, sometimes will checking existence of a directory. Max. file size is around 400 MB. But sometime it hangs even for a small file size < 1KB. Below is the fragment of code:
public boolean uploadData(String inputFilePath, String destinationFolderName) {
if (StringUtil.isNullOrBlank(inputFilePath) || StringUtil.isNullOrBlank(destinationFolderName)) {
LOGGER.error("Invalid parameters to uploadData. Aborting...");
return false;
}
boolean result = false;
FTPSClient ftpClient = getFTPSClient();
if (ftpClient == null) {
logFTPConnectionError();
return false;
}
try {
loginToFTPServer(ftpClient);
result = uploadFileToFTPServer(ftpClient, inputFilePath, destinationFolderName);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
return false;
} finally {
try {
logoutFromFTPServer(ftpClient);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
result = false;
}
}
return result;
}
private FTPSClient getFTPSClient() {
FTPSClient ftpClient = null;
try {
ftpClient = new FTPSClient();
LOGGER.debug("Connecting to FTP server...");
ftpClient.setConnectTimeout(connectTimeOut);
ftpClient.connect(server);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
LOGGER.error("Could not connect to FTP server. Aborting.");
return null;
}
} catch (Exception e) {
LOGGER.error("Could not connect to FTP server.", e);
return null;
}
return ftpClient;
}
private void loginToFTPServer(FTPSClient ftpClient) throws Exception {
ftpClient.setDataTimeout(DATA_TIMEOUT);
ftpClient.login(ftpUserName, ftpPassword);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
LOGGER.debug("FTP Client Buffer Size Before:" + ftpClient.getBufferSize());
ftpClient.setBufferSize(BUFFER_SIZE);
LOGGER.debug("FTP Client Buffer Size After:" + ftpClient.getBufferSize());
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.setControlKeepAliveTimeout(300);
LOGGER.debug("Logged into FTP server.");
}
private void logoutFromFTPServer(FTPSClient ftpClient) throws Exception {
LOGGER.debug("Logging out from FTP server.");
ftpClient.logout();
ftpClient.disconnect();
LOGGER.debug("FTP server connection closed.");
}
private boolean uploadFileToFTPServer(FTPSClient ftpClient, String inputFilePath, String destinationFolderName) {
boolean result = false;
String remoteLocationFile;
File ftpFile = new File(inputFilePath);
try (InputStream inputStream = new FileInputStream(ftpFile)) {
String fileName = ftpFile.getName();
remoteLocationFile = (destinationFolderName == null || destinationFolderName.isEmpty())
? ftpFile.getName()
: destinationFolderName + File.separator + fileName;
LOGGER.info("Storing file " + ftpFile.getName() + " of size "
+ ftpFile.length() + " in folder " + remoteLocationFile);
result = ftpClient.storeFile(remoteLocationFile, inputStream);
if(result) {
LOGGER.info("Successfully stored file " + ftpFile.getName() + " in folder " + remoteLocationFile);
} else {
LOGGER.error("Unable to store file " + ftpFile.getName() + " in folder " + remoteLocationFile);
}
return result;
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
}
return result;
}
The application is hosted in apache tomcat 8. What could be other causes of this issue and how should we fix them? This is crucial functionality of our application and we may even consider to use alternate API if that is stable. Please suggest.
Adding ftpClient.setSoTimeout(20000); has fixed the issue.
Adding a enterLocalPassiveMode right before the retreiveFile should solve this issue.
You also need to add
ftpClient.setControlKeepAliveTimeout(300);
or Check this code which will resolve the hanging issue

How do i return a powerpoint (.pptx) file from REST response in springMVC

I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat
Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.

Applet: SocketException Unknown proxy type : HTTP

I have no problems running my applet in Eclipse, but if I sign and run it in browser this happend
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: I/O exception (java.net.SocketException) caught when connecting to the target host: Unknown proxy type : HTTP
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: Retrying connect
…
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
Here im trying to upload some files using org.apache.http.client.HttpClient
public static String executeMultiPartRequest(String urlString, File file,
String fileName, String fileDescription) {
System.out.println("SET URI " + urlString);
HttpPost postRequest = new HttpPost(urlString);
try {
MultipartEntity multiPartEntity = new MultipartEntity();
// The usual form parameters can be added this way
multiPartEntity.addPart("fileDescription", new StringBody(
fileDescription != null ? fileDescription : ""));
multiPartEntity.addPart("fileName", new StringBody(
fileName != null ? fileName : file.getName()));
/*
* Need to construct a FileBody with the file that needs to be
* attached and specify the mime type of the file. Add the fileBody
* to the request as an another part. This part will be considered
* as file part and the rest of them as usual form-data parts
*/
FileBody fileBody = new FileBody(file, "application/octect-stream");
multiPartEntity.addPart("attachment", fileBody);
// multiPartEntity.addPart("path", Charset.forName("UTF-8"));
postRequest.setEntity(multiPartEntity);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return executeRequest(postRequest);
}
private static String executeRequest(HttpRequestBase requestBase) {
String responseString = "";
InputStream responseStream = null;
HttpClient client = new DefaultHttpClient();
try {
System.out.println("LISTO PARA ENVIAR A" + requestBase.getURI());
HttpResponse response = client.execute(requestBase);
if (response != null) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseStream = responseEntity.getContent();
if (responseStream != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(responseStream));
String responseLine = br.readLine();
String tempResponseString = "";
while (responseLine != null) {
tempResponseString = tempResponseString
+ responseLine
+ System.getProperty("line.separator");
responseLine = br.readLine();
}
br.close();
if (tempResponseString.length() > 0) {
responseString = tempResponseString;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (responseStream != null) {
try {
responseStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown();
return responseString;
}
What its wrong?
Applet is signed and compiled with java 1.6, httpclient-4.1.3.jar
For those with this problem, the solution was here http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e571 getting the JRE Proxy.
DefaultHttpClient client = new DefaultHttpClient () ;
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
client.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
client.setRoutePlanner(routePlanner);
HttpResponse response = client.execute(requestBase) ;
Then i signed all libraries httpcore-4.2.3.jar, httpmime-4.2.3.jar and httpclient-4.2.3.jar.

How can i attach multiple images with email in Blackberry?

I want to attach multiple images with email in BB. How can I do this? Does any body have an idea? please help me.Below is my code which works fine when i send only one image with email. so what modification should I make in my code for attaching multiple images.
public static void SendMailAttachment(Bitmap screenshot)
{
String htmlContent = "String" ;
try
{
Multipart mp = new Multipart();
Message msg = new Message();
Address[] addresses = {new Address("","")};
for (int i = 0; i<2 ; i++)
{
PNGEncodedImage img = PNGEncodedImage.encode(screenshot);
SupportedAttachmentPart pt = new SupportedAttachmentPart(mp, img.getMIMEType(),
"Weed.png", img.getData());
mp.addBodyPart(pt);
}
msg.setContent(mp);
msg.setContent(htmlContent);
msg.addRecipients(RecipientType.TO, addresses);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
}
catch (AddressException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
}
Thanx in advance.
following code can be used to attach multiple images or files.
public void upload()
{
Multipart mp = new Multipart();
String fileName = null;
for (int i = 0; i<2 ; i++)
{
// Dialog.alert(image.);
byte[] stream = readStream("file:///SDCard/IMG00001-20110404-1119.JPEG");
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, MIMETypeAssociations.getMIMEType("IMG00001-20110404-1119.JPEG"),"IMG00001-20110404-1119.JPEG", stream);
mp.addBodyPart(sap);
}
TextBodyPart tbp = new TextBodyPart(mp,"test bodyString");
mp.addBodyPart(tbp);
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
Address[] toAdds = new Address[1];
try {
toAdds[0] = new Address("testmailid", null);
message.addRecipients(Message.RecipientType.TO,toAdds);
// message.setFrom(new InternetAddress(_from));
// message.addRecipients(Message.RecipientType.FROM,toAdds);
message.setContent(mp);
message.setSubject("test subject");
Transport.send(message);
Dialog.alert("message send successfully.");
} catch (AddressException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
private byte[] readStream(String path)
{
InputStream in = null;
FileConnection fc = null;
byte[] bytes = null;
try
{
fc = (FileConnection) Connector.open(path);
if (fc !=null && fc.exists())
{
in = fc.openInputStream();
if (in !=null)
{
bytes = IOUtilities.streamToBytes(in);
}
}
}
catch(IOException e)
{
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch(IOException e)
{
}
try
{
if (fc !=null)
{
fc.close();
}
}
catch(IOException e)
{
}
}
return bytes;
}
i have used this code. it works fine.
Just create a new SupportedAttachmentPart for each image and add them to the message with the addBodyPart method.
Once the multipart is populated with the body part and the attachment parts, call msg.setContent(mp).

How can I marshal Objects from a Socket without closing it? (JAXB Marshaling from Inputstream via Socket)

I have tried in many different ways to send my xml document over a socket connection between a server and a client without closing the socket after sending (keep the outputstream open, for sending another document). I have found several sites who claimed that it should work, so I tried it in all the ways they sugested, but I did not found a way which works.
(that describes the same what I would like to do: http://jaxb.java.net/guide/Designing_a_client_server_protocol_in_XML.html)
The follwing code works perfectly if I am closing the socket after sending (#code marsh.marshal(element, xsw);), but it stucks on unmarshaling on the server side, if I try to keep the socket open.
Client Side....
public void sendMessage(String message){
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library");
Marshaller marsh = jaxbContext.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.org/WizardShema WizardsSchema.xsd");
ObjectFactory of = new ObjectFactory();
// the Dataset is the root element of the xml document
Dataset set = new Dataset("CONN01", "CONTR", "MCL01#localhost", "SV01#localhost:32000");
CommandSet cmdSet = new CommandSet();
Command cmd = new Command();
cmd.setFunctionName("RegisterAs");
Param p = new Param();
p.setString("RemoteClient");
cmd.addParameter(p);
cmdSet.addCommand(cmd);
set.setInstruction(cmdSet);
// creates a valid xml dataset, with startDocument, startElement...
JAXBElement<Dataset> element = of.createData(set);
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(mOOS);
marsh.marshal(element, xsw);
xsw.flush();
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
SERVER Side....
private void handleMessage() {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library") ;
Unmarshaller um = jaxbContext.createUnmarshaller();
XMLInputFactory xmlif = XMLInputFactory.newInstance();
// XMLEventReader xmlr = xmlif.createXMLEventReader(mOIS);
XMLStreamReader xmlr = xmlif.createXMLStreamReader(mOIS, "UTF8");
// move to the root element and check its name.
xmlr.nextTag();
System.out.println("TagName:" + xmlr.getLocalName());
xmlr.require(START_ELEMENT, null, "Data");
JAXBElement<Dataset> obj = um.unmarshal(xmlr, Dataset.class);
Dataset set = obj.getValue();
System.out.println("ID:"+ set.getID());
} catch (JAXBException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}