GWT Upload by Manuel Carrasco Moñino Issue - java

I am using this gwt upload system here(http://code.google.com/p/gwtupload/). I am getting some problems with it.
Show to feed it with a path from the client
Get the path on the server where the file was saved
set a path on the server where the file is to be saved
This the servlet to handle the file upload
public class SampleUploadServlet extends UploadAction {
private static final long serialVersionUID = 1L;
Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
/**
* Maintain a list with received files and their content types.
*/
Hashtable<String, File> receivedFiles = new Hashtable<String, File>();
/**
* Override executeAction to save the received files in a custom place
* and delete this items from session.
*/
#Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
int cont = 0;
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
cont ++;
try {
/// Create a new file based on the remote file name in the client
// String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_");
// File file =new File("/tmp/" + saveName);
/// Create a temporary file placed in /tmp (only works in unix)
// File file = File.createTempFile("upload-", ".bin", new File("/tmp"));
/// Create a temporary file placed in the default system temp folder
File file = File.createTempFile("upload-", ".bin");
item.write(file);
/// Save a list with the received files
receivedFiles.put(item.getFieldName(), file);
receivedContentTypes.put(item.getFieldName(), item.getContentType());
/// Compose a xml message with the full file information which can be parsed in client side
response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
response += "<file-" + cont + "-type>" + item.getContentType()+ "</file-" + cont + "type>\n";
} catch (Exception e) {
throw new UploadActionException(e);
}
}
}
/// Remove files from session because we have a copy of them
removeSessionFileItems(request);
/// Send information of the received files to the client.
return "<response>\n" + response + "</response>\n";
}
/**
* Get the content of an uploaded file.
*/
#Override
public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fieldName = request.getParameter(PARAM_SHOW);
File f = receivedFiles.get(fieldName);
if (f != null) {
response.setContentType(receivedContentTypes.get(fieldName));
FileInputStream is = new FileInputStream(f);
copyFromInputStreamToOutputStream(is, response.getOutputStream());
} else {
renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
}
}
/**
* Remove a file when the user sends a delete request.
*/
#Override
public void removeItem(HttpServletRequest request, String fieldName) throws UploadActionException {
File file = receivedFiles.get(fieldName);
receivedFiles.remove(fieldName);
receivedContentTypes.remove(fieldName);
if (file != null) {
file.delete();
}
}
}
Thanks

Try with this:
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
String uploadedFileName = "";
try {
String uploadsDir = "/uploads";
File dirFile = new File(uploadsDir);
dirFile.mkdirs();
String filename = FilenameUtils.getName(item.getName()); // uploaded file filename
File file = new File(uploadsDir, filename);
item.write(file);
uploadedFileName = uploadsDir + "/" + filename;
} catch (Exception e) {
logger.error("ERROR UPLOADING FILE: " + uploadedFileName + ", Exception: " + e);
throw new UploadActionException(e.getMessage());
}
}
removeSessionFileItems(request);
}
return null;
}
Happy coding!
Regards.

Related

Validator for an upload file

I need a validator for an upload file, for the moment I can upload all the files but I need a check that file is less than 10 MB and only text format such as ms word, txt, ppt, excel (not executable, might be harmful).
Do I have to use and libraries of java for that, or I don't know what, cause I am a junior. If anyone has any ideas that will be very nice.
I have seen some other similar question and i try out but none that can help me.
Ps: I am working on java spring.
Here is my code is compiled but not working is possible edit and also to check for the length.
class FileUploader implements Receiver, SucceededListener, FailedListener, ProgressListener {
private static final long serialVersionUID = 1L;
public File file;
public String filename;
#Override
public void updateProgress(long readBytes, long contentLength) {
UI ui = UI.getCurrent();
ui.access(() -> {
progressBar.setCaption("Uploaded: " + (float) readBytes / (float) contentLength * 100 + "%");
progressBar.setValue((float) readBytes / (float) contentLength);
progressBar.setVisible(true);
});
}
#Override
public void uploadFailed(FailedEvent event) {
UIHelper.showErrorNotification("File could not be uploaded");
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
String savePath = "/var/ccpt_work_files/";
Path filePath = Paths.get(savePath);
if (Files.exists(filePath)) {
copyFiles("/tmp/" + event.getFilename(), savePath + event.getFilename(), savePath + event.getFilename());
} else {
File targetFile = new File(savePath);
if (!targetFile.mkdirs()) {
UIHelper.showErrorNotification("Couldn't create dir: " + targetFile);
} else {
copyFiles("/tmp/" + event.getFilename(), savePath + event.getFilename(), savePath + event.getFilename());
}
}
} catch (IOException e) {
UIHelper.showErrorNotification("File could not be uploaded");
}
UIHelper.showInformationNotification("File successfully uploaded");
}
private void copyFiles(String from, String to, String finalPath) throws IOException {
com.google.common.io.Files.copy(new File(from), new File(to));
uploadedFilePath = finalPath;
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
this.filename = filename;
FileOutputStream fos = null;
try {
file = new File("/tmp/" + filename);
fos = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
} catch (final IOException e) {
UIHelper.showErrorNotification("File could not be stored in server");
return null;
}
return fos;
}
};
If you already have the File object of type java.io.File, you can just check for file size and mime type
boolean hasValidFileSize(File file, double maxFileSize) {
double bytes = file.length();
double megabytes = (kilobytes / 1024) / 1024;
if (megabytes > maxFileSize) {
return false;
}
return true;
}
For non harmful files, you can just check for the mime type. Look for ways on how to get the mime types for the files that you needed to be allowed and compare it with your file's mime type.
You can use this method to get the fileSize of a file.
static String getFileSizeMegaBytes(File file) {
return (double) file.length() / (1024 * 1024) + " mb";
}
Refer the post to get the file type.
File tyle extension

Aws S3 access denied issue

I am trying to access s3 bucket. I am able to do so using my local machine(i.e. from my local machine to S3 bucket), but getting access denied issue while trying to access it from EC2 instance running tomcat 8 and java 8.
Also when i upload the file the permissions are set for root user and if I keep my bucket as public and upload the file from EC2 the permissions are not set for the root user.
public class AmazonS3UtilService {
public static final String NAME = "amazonS3Util";
private static String S3_SECRET = "S3_SECRET";
private static String S3_ID = "S3_ID";
private static String BUCKET_NAME = "S3_BUCKET";
private static final String SUFFIX = "/";
private static final String DEFAULT_FOLDER_PATH = "PHR/Reports/";
#Autowired
protected Environment props;
private AWSCredentials awsCredentials = null;
private AmazonS3 s3Client = null;
private String bucketName = null;
private static final Logger log = Logger.getLogger(AmazonS3UtilService.class);
private void prepareAWSCredentials() {
if (awsCredentials == null) {
log.info("Preparing AWS Credentials");
awsCredentials = new AWSCredentials() {
#SuppressWarnings("unused")
Map<String, String> env = System.getenv();
public String getAWSSecretKey() {
String S3_SECRET = System.getProperty(AmazonS3UtilService.S3_SECRET);
if (S3_SECRET == null) {
S3_SECRET = System.getenv(AmazonS3UtilService.S3_SECRET);
if (S3_SECRET == null) {
S3_SECRET = props.getProperty(AmazonS3UtilService.S3_SECRET);
}
}
log.info("S3_SECRET ---->" + S3_SECRET);
return S3_SECRET;
}
public String getAWSAccessKeyId() {
String S3_ID = System.getProperty(AmazonS3UtilService.S3_ID);
if (S3_ID == null) {
S3_ID = System.getenv(AmazonS3UtilService.S3_ID);
if (S3_ID == null) {
S3_ID = props.getProperty(AmazonS3UtilService.S3_ID);
}
}
log.info("S3_ID ---->" + S3_ID);
return S3_ID;
}
};
}
}
private void prepareAmazonS3Client() {
if (s3Client == null) {
log.info("Preparing S3 Client");
ClientConfiguration clientCfg = new ClientConfiguration();
clientCfg.setProtocol(Protocol.HTTP);
s3Client = new AmazonS3Client(awsCredentials, clientCfg);
Region region = Region.getRegion(Regions.fromName(props.getProperty("s3client.region")));
log.info("Region ----->" + props.getProperty("s3client.region"));
s3Client.setRegion(region);
}
}
private void prepareBucketName() {
bucketName = System.getenv(AmazonS3UtilService.BUCKET_NAME);
log.info("bucketName ------>" + bucketName);
}
}
private void prepare() {
try {
awsCredentials = null;
prepareAWSCredentials();
prepareAmazonS3Client();
prepareBucketName();
} catch (AmazonServiceException ase) {
log.error("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
log.error("Error Message: " + ase.getMessage() + " HTTP Status Code: " + ase.getStatusCode()
+ " AWS Error Code: " + ase.getErrorCode() + " Error Type: " + ase.getErrorType()
+ " Request ID: " + ase.getRequestId());
new AmazonS3ClientException(ase, ase.getMessage());
} catch (AmazonClientException ace) {
log.error(ace);
new AmazonS3ClientException(ace, ace.getMessage());
}
}
#SuppressWarnings("unused")
public String uploadDocument(UploadDocumentDetailDTO uploadDocumentDetail) {
prepare();
String tempFileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date());
String fileURL = null;
try {
File uploadFileContent = readBase64File(uploadDocumentDetail.getFileContent(), tempFileName);
uploadDocumentDetail.setContentType(FileContentTypeEnum.PDF);
String uploadFileName = getUploadFileName(uploadDocumentDetail);
PutObjectRequest request = new PutObjectRequest(bucketName, uploadFileName, uploadFileContent);
request.putCustomRequestHeader("Content-Type", "application/pdf");
request.putCustomRequestHeader("Content-Disposition", "inline");
PutObjectResult putObjectResult = s3Client.putObject(request);
URL url = generatePresignedUrlRequest(uploadFileName);
fileURL = url.toString();
} catch (Exception e) {
log.info(LoggerException.printException(e));
fileURL = "";
}
return fileURL;
}
public URL generatePresignedUrlRequest(String fileURL) {
log.info("Inside generatePresignedUrlRequest");
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // 1 hour.
expiration.setTime(msec);
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, fileURL);
generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
generatePresignedUrlRequest.setExpiration(expiration);
URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
log.info("Url --->" + s);
return s;
}
private String getUploadFileName(UploadDocumentDetailDTO uploadDocumentDetail) {
StringBuffer uploadFileName = new StringBuffer();
uploadFileName.append(DEFAULT_FOLDER_PATH);
if (uploadDocumentDetail.getBeneficiaryId() != null)
uploadFileName.append(uploadDocumentDetail.getBeneficiaryId() + SUFFIX);
if (uploadDocumentDetail.getDocumentType() != null)
uploadFileName.append(uploadDocumentDetail.getDocumentType().getName() + SUFFIX);
// Check and create Folder
validateAndCreateFolder(uploadFileName.toString());
if (uploadDocumentDetail.getAssesmentId() != null)
uploadFileName.append(
uploadDocumentDetail.getAssesmentId() + "." + uploadDocumentDetail.getContentType().getName());
else
uploadFileName.append(
uploadDocumentDetail.getDefaultFileName() + "." + uploadDocumentDetail.getContentType().getName());
return uploadFileName.toString();
}
private static File readBase64File(String content, String fileName) throws Exception {
File file = File.createTempFile(fileName, ".tmp");
file.deleteOnExit();
FileOutputStream fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(Base64.decodeBase64(content));
fileOuputStream.close();
return file;
}
public void validateAndCreateFolder(String folderName) {
List<S3ObjectSummary> fileList = null;
try {
fileList = s3Client.listObjects(bucketName, folderName).getObjectSummaries();
} catch (AmazonServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmazonClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (fileList == null || fileList.isEmpty()) {
// create meta-data for your folder and set content-length to 0
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
// create empty content
InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
// create a PutObjectRequest passing the folder name suffixed by /
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folderName, emptyContent, metadata);
// send request to S3 to create folder
s3Client.putObject(putObjectRequest);
}
}
/**
* This method first deletes all the files in given folder and than the
* folder itself
*/
}
Following is the exception while access S3 from EC2 instance.
INFO com.medscheme.common.util.AmazonS3UtilService - com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: 926E1213366626B9), S3 Extended Request ID: zQbb4JCalYExHZtDSv0GmWxoHrQZJUV3M+jlUiaVJY/sDxW/qoNFC8hizfangVCjweWZtOqC7/A=
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1275)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:873)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:576)
at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:362)
at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:328)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:307)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3649)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3602)
at com.amazonaws.services.s3.AmazonS3Client.listObjects(AmazonS3Client.java:679)
at com.amazonaws.services.s3.AmazonS3Client.listObjects(AmazonS3Client.java:664)
at com.medscheme.common.util.AmazonS3UtilService.validateAndCreateFolder(AmazonS3UtilService.java:222)
at com.medscheme.common.util.AmazonS3UtilService.getUploadFileName(AmazonS3UtilService.java:200)
at com.medscheme.common.util.AmazonS3UtilService.uploadDocument(AmazonS3UtilService.java:166)
at com.medscheme.service.impl.ReportsServiceImpl.getReport(ReportsServiceImpl.java:133)
at com.medscheme.service.impl.ReportsServiceImpl.getReport(ReportsServiceImpl.java:1)
at com.medscheme.controller.ReportsController.getWellnessReportDetails(ReportsController.java:69)
I was able to resolve the issue by using BasicAWSCredentials class instead of AWSCredentials while creating the amazon client.
The problem was only with EC2 instance.
Does anybody know what was going wrong on EC2.

JasperReports generated in a Servlet (GWT) does not appear

I am developing an application in GWT, I am using the api to generate JasperReports reports, initially tried to make the generation via RPC, which returned to the client a string with the path of the pdf created, but that did not work, now I'm trying to generate report by a normal servlet, but the report is generated, nothing appears on the screen, and no error is found in the browser console.
Details:
dev mode works perfectly.
on localhost: 8080 works perfectly.
The error is when the application is published in an external Tomcat
Here are my code
Servlet:
public class RelatorioPacienteServiceImpl extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletContext sc;
public void init(ServletConfig config) throws ServletException {
super.init(config);
sc = config.getServletContext();
}
#SuppressWarnings({ "unused", "unchecked", "rawtypes" })
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
Map m = req.getParameterMap();
Paciente paciente = new Paciente();
File reportFile = null;
String dir = sc.getRealPath(sc.getContextPath().replaceAll("\\\\", "/"));
Map parameters = new LinkedHashMap();
String path = dir + "/../reports/";// tomcat
path = path.replaceAll("\\\\", "/");
try {
paciente = PacienteDAO.getPacientePorId(Integer.parseInt(id));
List<Paciente> list = new ArrayList<>();
list.add(paciente);
HashMap parametros = new HashMap<String, Boolean>();
parametros.put("cpf", NumberMask.formatCpf(paciente.getCpf()));
parametros.put("telefone1",NumberMask.formatPhone(paciente.getTelefone1()));
parametros.put("telefone2",NumberMask.formatPhone(paciente.getTelefone2()));
parametros.put("telefoneResponsavel",NumberMask.formatPhone(paciente.getTelefoneResponsavel()));
parametros.put("dataNascimento",StringUtil.formatDate(paciente.getDataNascimento()));
switch (paciente.getEtnia()) {
case EtniaProps.BRANCA:
parametros.put("etnia","Branco");
break;
case EtniaProps.INDIGENA:
parametros.put("etnia","Indigena");
break;
case EtniaProps.PARDA:
parametros.put("etnia","Parda");
break;
case EtniaProps.PRETA:
parametros.put("etnia","Preta");
break;
default:
break;
}
reportFile = new File(path + "report_paciente.jasper");
byte[] bytes = null;
JRDataSource jrds = new JRBeanCollectionDataSource(list);
try {
bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parametros, jrds);
} catch (JRException ex) {
ex.printStackTrace();
System.out.println("Erro ao gerar o relatório " + ex.getMessage());
}
if (!list.isEmpty()) {
if (bytes != null && bytes.length > 0) {
resp.setContentType("application/pdf");
resp.setContentLength(bytes.length);
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
outputStream.close();
}
} else {
resp.setContentType("text/html");
ServletOutputStream outputStream = resp.getOutputStream();
String mensagem = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" charset=\"UTF-8\" content=\"text/html\">"
+ "<title>Incor lages</title>" + "</head>" + "<body>"
+ "<br><br><br><br><h1>Documento sem paginas" + "</body>" + "</html>";
outputStream.write(mensagem.getBytes(), 0, mensagem.getBytes().length);
resp.setContentLength(mensagem.getBytes().length);
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erro ao execura a query " + e.getMessage());
}
}
Calling servlet:
String url = GWT.getModuleBaseURL() + "relatorioPacienteService?id=" + paciente.getId();
Window.open(url, "_blank", "");
Any help would be appreciated
Can u print reportFile.getPath(). I doubt the path of .jasper file is incorrect.
First of all it would be even better If you can post your .jrxml file.
Based on the info available (report is generated, but blank), I think following is the area of concern:
paciente = PacienteDAO.getPacientePorId(Integer.parseInt(id));
List<Paciente> list = new ArrayList<>();
list.add(paciente);
Make sure PacienteDAO.getPacientePorId(Integer.parseInt(id)); is actually returning a bean. Beacuse If it does not return anything or returns null, the data source you use i.e. JRBeanCollectionDataSource, will have no data and hence nothing would be displayed.

Scale image after upload JSP

I need to know how i can scale the uploaded images and save it on the server in the Upload folder.
I have this to process the the form where people can upload there files.
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
} catch (java.io.IOException ioe) {
resp = ioe.getMessage();
}
request.setAttribute("message", resp);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
For example i need to rezise all the image to 100x100
First save it, then load it, then scale, then resave it.
try
{
BufferedImage img = ImageIO.read(new File(in_path));
Image scaled = img.getScaledInstance(100, 100, Image.SCALE_FAST);
ImageIO.write(scaled, "png", out_path);
}
catch (Exception ex)
{
System.out.println(ex.getMessage();
}
See http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html for list of scaling methods that can be used in the third parameter of getScaledInstance

use commons-net ftp api. i want download file but this file size 0

I make simple application using commons-net-3.1 library
I want download file from FTP server, but downloaded file's size is 0
This file name is mixed english, symbol(like "-", "_", etc...), other language(like korean, japanese, etc...).
How to solve this problum? T.T
Here is code
/**
* download file. it works thread
*
* #param source
* file path witch is remote path
* #param destination
* file path witch is saving local memory
*/
public void downloadFile(String source, String destination) {
DownloadTempFile download = new DownloadTempFile(source, destination);
download.setDaemon(true);
download.start();
}
class DownloadTempFile extends Thread {
String source, destination;
public DownloadTempFile(String source, String destination) {
this.source = source;
this.destination = destination;
}
public void run() {
OutputStream output = null;
try {
File local = new File(destination);
output = new FileOutputStream(local);
ftpClient.retrieveFile(source, output);
} catch (Exception e) {
// TODO: handle exception
}
}
}
and, this code is call upper method
String tempPath = mSDpath + "/mgtec/temp";
File d = new File(tempPath);
if (d.isDirectory()) {
String tempFile = tempPath + "/tmp" + position + ".mp3";
NativeMusicAppActivity.mConnector.downloadFile(mAdapter
.getItem(position).toString(), tempFile);
} else {
if (d.mkdirs()) {
String tempFile = tempPath + "/tmp" + position + ".mp3";
NativeMusicAppActivity.mConnector.downloadFile(mAdapter
.getItem(position).toString(), tempFile);
}
}

Categories

Resources