ParseException when sending an email with zip file attachment? - java

I am getting an Exception when sending an email with a zipped file attachment, any suggestions?
Caused by: javax.mail.internet.ParseException: Expected '/', got null
at javax.mail.internet.ContentType.(ContentType.java:102) at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1322)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
at
javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:13
private MimeBodyPart makeZipAttachment(AttachmentInfo attachmentInfo) throws IOException, MessagingException {
ByteArrayOutputStream bos = null;
ZipOutputStream zip = null;
try
{
bos = new ByteArrayOutputStream();
zip = new ZipOutputStream(bos);
zip.putNextEntry(new ZipEntry(attachmentInfo.getName()));
InputStream inputStream = attachmentInfo.getAttachment().getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
zip.write(buffer, 0, len);
}
zip.closeEntry();
}
finally
{
if (bos != null)
bos.close();
if (zip != null)
zip.close();
}
DataSource dataSource = new ByteArrayDataSource(bos.toByteArray(), "application/zip");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
mimeBodyPart.setFileName(attachmentInfo.getName() + ".zip");
mimeBodyPart.setHeader(CONTENT_TYPE, "application/zip");
return mimeBodyPart;
}

can not say much until i run the program by myself but try with setting content as well like this mimeBodyPart.setContent

Related

ZipInputStream conversion

i have a java service that take a byte array in order to convert it in one or more pdf files or jpg files. i know this service work because it's called from another java system that correctly send files with no problems. now i need to call this services from a angular js system, the byte array, once reached the java application, it's converted first to a ByteArrayInputStream with not problems then the ByteArrayInputStream it's converted to ZipInputStream but fail. i suspect the problem is the type of encoding of the array.
This is my code:
public static Hashtable<String, ByteArrayOutputStream> unzipFile(InputStream inputStream){
logger.info("Unzip del File");
Hashtable<String, ByteArrayOutputStream> fileOutputTable = new Hashtable<String, ByteArrayOutputStream>();
try{
byte[] buf = new byte[1024];
ZipEntry zipentry;
ByteArrayInputStream bis = (ByteArrayInputStream)inputStream;
ZipInputStream zipinputstream = new ZipInputStream(bis); // here conversion fail
while((zipentry = zipinputstream.getNextEntry()) != null){
String entryName = zipentry.getName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = 0;
while((n = zipinputstream.read(buf, 0, 1024)) > -1)
baos.write(buf, 0, n);
baos.close();
fileOutputTable.put(entryName, baos);
zipinputstream.closeEntry();
}
zipinputstream.close();
}catch(Exception e){
logger.error("Errore nel tentativo di unzip del file");
e.printStackTrace();
}
logger.info("RETURN: " + fileOutputTable.toString());
return fileOutputTable;
}
public static Hashtable<String, ByteArrayOutputStream> unzipFile(InputStream inputStream){
logger.info("Unzip del File");
Hashtable<String, ByteArrayOutputStream> fileOutputTable = new Hashtable<String, ByteArrayOutputStream>();
try{
byte[] buf = new byte[1024];
ZipEntry zipentry;
ByteArrayInputStream bis = (ByteArrayInputStream)inputStream;
ZipInputStream zipinputstream = new ZipInputStream(bis); // here conversion fail
while((zipentry = zipinputstream.getNextEntry()) != null){
String entryName = zipentry.getName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = 0;
while((n = zipinputstream.read(buf, 0, 1024)) > -1)
baos.write(buf, 0, n);
baos.close();
fileOutputTable.put(entryName, baos);
zipinputstream.closeEntry();
}
zipinputstream.close();
}catch(Exception e){
logger.error("Errore nel tentativo di unzip del file");
e.printStackTrace();
}
logger.info("RETURN: " + fileOutputTable.toString());
return fileOutputTable;
}

Unzip to internal storage not working completely

My file unzips one folder and one file but does not unzip the rest for some reason. How can I make it so it unzips all of the zip files contents?
public void unzip(String filepath, String filename, String unzip_path) throws IOException {
InputStream is = new FileInputStream(filepath + filename);
Log.d("1st", filepath + filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename_temp = ze.getName();
File fmd = new File(unzip_path + filename_temp);
Log.d("2nd", unzip_path + filename_temp);
if (!fmd.getParentFile().exists()) {
fmd.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(unzip_path + filename_temp);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
//}
}
} finally {
zis.close();
}
}

Java Download Zip from Webpage

I'm trying to download a zip file from a URL, and I have completed that. The problem is is that it keeps downloading the webpage itself, so I end up with some beautiful HTML, CSS, JS, and PHP. That's nowhere near a zip file.
Please correct me if I'm doing something wrong with my code:
private static String URL = "webpage/myzip.zip";
private static String OUTPUT_PATH = "path/to/extract/to";
private static File OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
public static void create() throws Exception {
if (!OUTPUT_DIRECTORY.exists()) OUTPUT_DIRECTORY.mkdirs();
else return;
System.out.println("Natives not found. Downloading.");
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(URL).openStream());
fout = new FileOutputStream(OUTPUT_PATH + File.separator + "myzip.zip");
final byte[] data = new byte[4096];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) in.close();
if (fout != null) fout.close();
}
OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
File zip = OUTPUT_DIRECTORY.listFiles()[0];
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zip));
ZipEntry ze = zipIn.getNextEntry();
byte[] buffer = new byte[4096];
while (ze != null) {
String fName = ze.getName();
File newFile = new File(OUTPUT_DIRECTORY + File.separator + fName);
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zipIn.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zipIn.getNextEntry();
}
zipIn.closeEntry();
zipIn.close();
// zip.delete();
System.out.println("Natives Downloaded.");
}
Answer provided by: Scary Wombat
I didn't copy the link correctly. I was using a drop box link, and I forgot that I needed to copy the download link from when you hit the download button.

Error while opening the generated PDF file with Servlets

By using the following code a PDF file is getting opened, I simply write the file to the servlet's output stream, but, when i am trying to open that PDF file it showing an error : "Not a pdf or Corrupted"
My code:
public void displayPj() {
String url = ficheToDisplay.getUrl();
String outPutFile = ficheToDisplay.getNom();
HttpServletResponse resp = null;
resp = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
File file = new File(url);
resp.reset();
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ outPutFile + "\"");
resp.setContentType("application/pdf;charset=UTF-8");
resp.setHeader("Content-Length", String.valueOf(file.length()));
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
ServletOutputStream outStream = resp.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(resp.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
outStream.close();
} catch (Exception e) {
System.err
.println("PROBLEM STREAMING DAILY REPORT PDF THROUGH RESPONSE!"
+ e);
e.printStackTrace();
FacesMessage fm = new FacesMessage("Could Not Retrieve PDF.");
FacesContext.getCurrentInstance().addMessage(
"dailyReportArchiveFailure", fm);
}
FacesContext.getCurrentInstance().responseComplete();
}

How to read and calculate hash of file on the internet

I have a url of a file on the Internet. I need to calculate the SHA1 hash, and read this file by each line. I know how to do this, but I read this file twice which probably isn't a very good solution.
How can I do this more effectively?
Here is my code:
URL url = new URL(url);
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
logger.error(urlConnection.getContent() + " ");
InputStream is = urlConnection.getInputStream();
// first reading of file is:
int i;
File file = new File("nameOfFile");
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(file.getName()));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
sha1(file);
// second reading of file is:
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
// do something
}
protected byte[] sha1(final File file) throws Exception {
if (file == null || !file.exists()) {
return null;
}
final MessageDigest messageDigest = MessageDigest.getInstance(SHA1);
InputStream is = new BufferedInputStream(new FileInputStream(file));
try {
final byte[] buffer = new byte[1024];
for (int read = 0; (read = is.read(buffer)) != -1;) {
messageDigest.update(buffer, 0, read);
}
} finally {
IOUtils.closeQuietly(is);
}
return messageDigest.digest();
}
If you pass it through a DigestInputStream, it'll do the MessageDigest and still be usable as an InputStream.
DigestInputStream dis = new DigestInputStream(is,
MessageDigest.getInstance(SHA1));
BufferedInputStream bis = new BufferedInputStream(dis);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.close();
return dis.getMessageDigest().digest();

Categories