dynamically generated zip downloading results corrupted files - java

what i m try to achieve is, creating dynamically zip file and write it to ServletOutput stream. I can manage to download a zip file through my code. But downloaded zip content is unusable.
Thanks for your answer.
package mainpackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.coyote.Response;
public class DownloadZipServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DownloadZipServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment;filename=download.zip");
ServletOutputStream sos;
ZipOutputStream zos;
InputStream fis;
List<File> filesToDownload = new ArrayList<File>();
filesToDownload.add(new File(getDirectory(), "download.png"));
filesToDownload.add(new File(getDirectory(), "download2.png"));
sos = response.getOutputStream();
zos = new ZipOutputStream(sos);
for (File fileToSend : filesToDownload) {
ZipEntry ze = new ZipEntry(fileToSend.getName());
zos.putNextEntry(ze);
fis = new FileInputStream(fileToSend);
byte[] buffer = new byte[4096];
int readBytesCount = 0;
while ((readBytesCount = fis.read(buffer)) >= 0) {
sos.write(buffer, 0, readBytesCount);
}
fis.close();
sos.flush();
zos.flush();
zos.closeEntry();
}
zos.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
public String getDirectory() {
Properties prop;
String home;
String fileSeparator;
String directoryName;
prop = System.getProperties();
home = prop.getProperty("user.dir").toString();
fileSeparator = prop.getProperty("file.separator").toString();
directoryName = "FileToDownload";
return home + fileSeparator + directoryName;
}
}

You're writing the file contents to your ServletOutputStream instead of yourZipOutputStream.
sos = response.getOutputStream();
zos = new ZipOutputStream(sos);
// ...
while ((readBytesCount = fis.read(buffer)) >= 0) {
sos.write(buffer, 0, readBytesCount); // <-- should be zos instead of sos
}

Related

how to reconstruct an org.archive.io.warc.WARCRecordInfo from an org.archive.io.ArchiveRecord?

Using java, I need to read a warc archive file, filter it depending on the content of the html page, and write a new archive file.
the following code reads the archive. how to reconstruct an org.archive.io.warc.WARCRecordInfo from an org.archive.io.ArchiveRecord?
import org.apache.commons.io.IOUtils;
import org.archive.io.ArchiveRecord;
import org.archive.io.warc.*;
import org.archive.wayback.resourcestore.resourcefile.WarcResource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;
public class Test126b {
public static void main() throws Exception {
File out = new java.io.File("out.warc.gz");
OutputStream bos = new BufferedOutputStream(new FileOutputStream(out));
WARCWriterPoolSettings settings = ...
WARCWriter writer = new WARCWriter(new AtomicInteger(), bos, out, settings);
File in = new java.io.File("in.warc.gz");
WARCReader reader = WARCReaderFactory.get(in);
Iterator<ArchiveRecord> it = reader.iterator();
while (it.hasNext()) {
ArchiveRecord archiveRecord = it.next();
if (archiveRecord.getHeader().getHeaderValue("WARC-Type") == "response") {
WARCRecord warcRecord = (WARCRecord) archiveRecord;
WarcResource warcResource = new WarcResource(warcRecord, reader);
warcResource.parseHeaders();
String url = warcResource.getWarcHeaders().getUrl();
System.out.println("+++ url: " + url);
byte[] content = IOUtils.toByteArray(warcResource);
String htmlPage = new String(content);
if (htmlPage.contains("hello world")) {
writer.writeRecord(warcRecordInfo) // how to reconstruct the WARCRecordInfo
}
}
}
reader.close();
writer.close();
}
}

How fast do you upload large file with commons-fileupload

I'm a beginner in Java, and I use the Apache's commons-fileupload and conmmons-io to upload large file.It took me 20 seconds to copy a file size of 40m using this code. Is this normal?I have found a lot of places without an answer,and I would be grateful for any help,Thanks.
This is an example of copying official code:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.commons.io.FileUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet2 extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(req);
System.out.println("start....");
long startTime = System.currentTimeMillis();
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
} else {
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
System.out.println(fileName);
FileUtils.copyInputStreamToFile(stream, new File("C:/dest.exe"));
long endTime = System.currentTimeMillis();
System.out.println("total seconds:" + (endTime - startTime) / 1000);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}

C# file upload to Java EE server

My problem is, that after uploading the content of file is [object Object].
How can I upload a file properly?
Server:
package com.turbulence6th.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/saveFile")
#MultipartConfig
public class SaveFile extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String webAppPath = getServletContext().getRealPath("/");
Part file = request.getPart("file");
String filename = getFileName(file);
InputStream is = file.getInputStream();
String directoryPath = webAppPath + File.separator + "files";
File directory = new File(directoryPath);
if(!directory.exists()){
directory.mkdir();
}
String filePath = directoryPath + File.separator + filename;
FileOutputStream fos = new FileOutputStream(filePath);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.close();
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
Client:
using (var wb = new WebClient())
{
wb.UploadFile("http://" + host + ":8080/saveFile", "POST", path);
}
I don't see any manipulations with response. Inside doPost you copy file content to the request. Is it what you want?
By the way - I don't see any reason to not use copy().

Http 500 error when trying to logout with tomcat

I have a problem with the servlet that I'm making. You have to log into a system and you also need to log out, I use a file register the users. Login works fine, it reads the user from the file, but for some reason logout doesn't. I get an error when I press the logout-button:
Here is the code for the class LogoutServlet
package nl.hu.sp.lesson1.dynamicexample;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher rd = null;
try {
String data = null;
File file = new File(
"C:/apache-tomcat-8.0.5/webapps/LoginAssignment/loggedusers.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
String[] de = data.split(" ");
if (de[0].equals("vimal")) {
data.trim();
rd = req.getRequestDispatcher("testpage.html");
}
}
rd.forward(req, resp);
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are reading a text file and searching for "vimal", if it is found you are initializing rd; if it is not found rd is null. It cannot find "vimal" in text file and rd becomes null so it throws null pointer exception.
Add null check
if (rd != null) {
rd.forward(req, resp);
}

How to display images from database in JSF

I have images that are stored in the database as a BLOB. Now I can display them in my jsf pages using Richfaces mediaOutput tag.
Is it possible for images to have path like "/images/image.jpg" while images are stored in the database.
While searching for an answer I came around something like this:
#GET
#Path("/files/{filename}")
#Produces(MediaType.WILDCARD)
Best regards,
Ilya Sidorovich
You could write a servlet picking up every request to /image/* or something that suits you.
And in your servlet you retrieve the correct data from your database via request parameters.
And you write out the data via
response.getOutputStream().write(content);
(content being the bytearray of you image)
Thank you roel and BalusC!
If anyone comes around this issue, here is what you can do.
package org.gicm.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.inject.Inject;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import org.gicm.cms.CMSDao;
import org.gicm.model.UploadedImage;
#WebServlet("/images/*")
public class TestServlet extends HttpServlet {
#Inject
private CMSDao cms;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String imageId = String.valueOf(request.getPathInfo().substring(1)); // Gets string that goes after "/images/".
UploadedImage image = cms.findImage(imageId); // Get Image from DB.
response.setHeader("Content-Type", getServletContext().getMimeType(image.getName()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(image.getData()); // Creates buffered input stream.
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}
}

Categories