I'm working in a project that I didn't originally start, so there are a lot of artifacts and conventions that I cannot change without considerable effort. Anyway, here's the problem. I need to do multiple file uploads (that are "children" to the entity that is being edited on the "main" parent page) that get cached on the server so that they can be sent somewhere else if/when the user submits. The files uploaded also include metadata that the user enters. The best way I have figured to do this is to render a "dialog" that has an iframe that does the uploading and has the input for the metadata. Then I created an override (using install precedence) of Seam's multipart filter that uses the Apache file upload jar and a custom request wrapper that carries my information into the action call on the server. All goes well unless I throw an exception out of the filter, for example, if the request size is too big. The exception is caught and handled by a pages.xml declaration.
<exception class="org.jboss.seam.web.FileUploadException">
<redirect view-id="#{facesContext.externalContext.requestServletPath}">
<message severity='ERROR'>#{org.jboss.seam.handledException.message}</message>
</redirect>
</exception>
When I normally submit the form in my dialog frame, the conversation in the frame remains (as I want), when the exception is caught, I get a new one (as I don't want). I want the error messages passed by the exception shown in the global messages area of the frame, but I need to remain in the same conversation as before since the "children" that are being added in the dialog are children to the "parent" entity in the main page. Here is the form inside the frame code. I have tried s:button (does not submit the form), tried parameters, and tried hidden inputs with the conversation id.
<h:form id="attachmentModalForm" enctype="multipart/form-data" autocomplete="off" style="background-color: #FFFFFF;">
<ui:include src="layout/messages.xhtml" />
<div id="attachmentModalMain" class="modalMain">
<s:decorate id="attachmentDescriptionDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.description']}<s:span styleClass="required">*</s:span></ui:define>
<h:inputText id="attachmentDescription" value="#{attachmentAction.description}" styleClass="textbox" />
</s:decorate>
<s:decorate id="attachmentFileDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.file']}<s:span styleClass="required">*</s:span></ui:define>
<input id="attachmentFile" name="attachmentFile" type="file" />
</s:decorate>
</div>
<div id="attachmentModalSubmit" class="modalSubmit">
<h:commandButton id="attachmentSubmitButton" value="#{messages['action.text.submit']}" action="#{attachmentAction.addAttachment()}" onclick="attachmentSubmit();" />
<button id="attachmentCancelButton" type="button" value="#{messages['action.text.cancel']}" onclick="window.parent.hideAttachmentModal();">#{messages['action.text.cancel']}</button>
</div>
<input type="hidden" name="cid" value="#{conversation.id}" />
</h:form>
Here is the filter that overrides Seam's multipart filter.
package XXXXXXXXXXXXX.attachment;
import java.io.File;
import java.io.IOException;
import java.rmi.server.UID;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.annotations.web.Filter;
import org.jboss.seam.web.AbstractFilter;
/**
* This filter is used to override Seam's multipart filter so that we
* can have multiple temporary files on the server cued and ready to
* go to XXXXXXXXX. It uses the Apache Commons FileUpload objects to
* handle the parsing of the request and the temporary files.
*
*/
#Scope(ScopeType.APPLICATION)
#Name("org.jboss.seam.web.multipartFilter")
#Install(precedence = Install.APPLICATION)
#BypassInterceptors
#Filter(within={"org.jboss.seam.web.ajax4jsfFilter", "org.jboss.seam.web.exceptionFilter"})
public class MEDWareMultipartFilter extends AbstractFilter {
// This is unused, we always want temp files since we are caching before upload to XXXXXXXXX.
// Leaving it in to mirror Seam's multipart filter, in case it gets set from the components.xml.
#SuppressWarnings("unused") private boolean createTempFiles = true;
private int maxRequestSize = -1;
private String acceptedFileExtensions = "txt,pdf,doc,docx,xls,xlsx";
public void setCreateTempFiles(boolean createTempFiles) { }
public void setMaxRequestSize(int maxFileSize) {
this.maxRequestSize = maxFileSize;
}
public String getAcceptedFileExtensions() {
return acceptedFileExtensions;
}
public void setAcceptedFileExtensions(String acceptedFileExtensions) {
this.acceptedFileExtensions = acceptedFileExtensions;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(response instanceof HttpServletResponse)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (ServletFileUpload.isMultipartContent(httpRequest)) {
File repository = (File) this.getServletContext().getAttribute("javax.servlet.context.tempdir");
DiskFileItemFactory factory = new DiskFileItemFactory(0, repository);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxRequestSize);
List<FileItem> formItems = null;
try {
formItems = upload.parseRequest(httpRequest);
} catch (SizeLimitExceededException slee) {
throw new org.jboss.seam.web.FileUploadException("File size excededs maximum allowed.", slee);
} catch (FileUploadException fue) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file.", fue);
}
Map<String, String> parameters = new HashMap<String, String>();
Map<String, File> fileParameters = new HashMap<String, File>();
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (item.isFormField()) {
parameters.put(item.getFieldName(), item.getString());
} else {
String fileName = item.getName();
// This is for IE7 (and Safari?) which sends the whole path.
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
if (!MyMultipartRequestUtils.isValidFileType(acceptedFileExtensions, fileName)) {
throw new org.jboss.seam.web.FileUploadException("The file type is not an accepted file type.");
}
File tempFile = null;
try {
tempFile = File.createTempFile(new UID().toString().replace(":", "-"), ".upload");
tempFile.deleteOnExit();
item.write(tempFile);
} catch (Exception e) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file. Could not write file to server.");
}
fileParameters.put(fileName, tempFile);
}
}
}
MyMultipartRequestWrapper requestWrapper = new MyMultipartRequestWrapper(httpRequest, parameters, fileParameters);
chain.doFilter(requestWrapper, response);
} else {
chain.doFilter(request, response);
}
}
}
So, to reiterate, if I use the frame to upload files, everything works and the frame continues on the same conversation adding each child to the parent, if I upload a file that is too big, I get the correct message in the global message area of the frame, but the conversation get incremented and then the children are obviously being added to a new parent entity in the new conversation. Any help would be greatly appreciated.
I just ended up adding a field to my custom request wrapper to carry any exceptions I wanted to handle and then handled them in the
#{attachmentAction.addAttachment()}
action call further up the request chain. All works now, I just add my faces messages from there and the conversation does not get incremented the same as if I had a successful upload.
Related
Good day,
When a user hit specific url with an extension on html, I want to validate if user has logged in. If the user is not logged in, I want to redirect them to my custom login page (this part is done). Else, I want to do nothing - meaning the current page that they are on, should continue being displayed.
I want this to meet client requirements (the default AEM login page should stay as is.
Scenario
The page is /content/mysite/page.html
If I am not logged in, I should be redirected to /content/mysite/login.html
If I am logged in, I should still see this page : /content/mysite/page.html
Now, my problem comes when I am logged in. Instead of seeing content of the page : /content/mysite/page.html, there page is simply blank. There are no contents to be displayed.
Maybe I do not get the concepts of servlets or I do not know how to handle this kind of problem.
Please help resolve this or suggest another route to handle this
Here is my the code I have so far:
package com.company.patientsportal.core.auth;
import java.io.IOException;
import java.util.Map;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.engine.SlingRequestProcessor;
#Service
#SlingServlet(resourceTypes={"patientsportal/components/structure/page"}, selectors="html", methods = "GET", metatype=true, description="My Authentication Verifier")
#Properties
(
{
#Property(name="login.form", description="The form on which the user to enter authentication credentials.", value="")
}
)
public class CheckAuthentication extends SlingAllMethodsServlet
{
/**
*
*/
private static final long serialVersionUID = 8552708551560032677L;
private Map<String, Object> redirects;
#Reference
private Repository repository;
#Reference
private SlingRequestProcessor requestProcessor;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
ResourceResolver resolver = request.getResourceResolver();
Session session = resolver.adaptTo(Session.class);
String userId = session.getUserID();
String url = request.getRequestPathInfo().getResourcePath();
url = url.substring(0, url.lastIndexOf("/")) + ".html";
if (String.valueOf(userId) == null || (String.valueOf(userId) != null ? String.valueOf(userId).equals("anonymous") : false))
{
String loginForm = getLoginForm("login.form");
if (loginForm != null)
{
response.sendRedirect(loginForm + "?url=" + url);
}
else
{
response.sendRedirect("/content/patientsportal/login.html?url=" + url);
}
}
else
{
//Do nothing or something in the else
//So far, do nothing does not work. It returns blank page even if I do not include the else part
}
}
private String getLoginForm(String loginForm)
{
if (redirects != null)
{
loginForm = (String) redirects.get(loginForm);
return loginForm;
}
return null;
}
#Activate
protected void activate(Map<String, Object> properties)
{
redirects = properties;
}
}
The ideal way of implementing login functionality is to either use the OOTB AEM authentication handler or implement Sling AuthenticationHandler and extending DefaultAuthenticationFeedbackHandler. You can find the code references to implement in lot of blogs -
acs-aem-samples
How to Create Custom Authentication Handler in CQ
After you have implemented this and have created/configured your own login page /form, you need to setup CUG on the pages that are to be exposed only to a logged in user. The details around it are available in AEM documentation here
I am developing a web application using Java. From my index page I need to upload a file with some other fields such as some texts and numbers using input tags.
this is my jsp file.
<select name="category">
<option value="">-Select-</option>
<option value="Mobile Phones">Mobile Phones</option>
<option value="Automobile">Automobile</option>
<option value="Computers">Computers</option>
</select><br/><br/>
<label>Title: </label><input type="text" name="Title"/><br/><br/>
<label>Photo: </label><input type="file" name="photo"/><br/><br/>
<label>Description: </label><input type="text" name="description"/><br/><br/>
<label>Price: </label><input type="text" name="price"/><br/><br/>
<input type="submit" value="Post">
I found some articles which use Apache commons, but in all of that, I can get only the image. All the other values get set to null. The article I followed is this.
I need to know how to get other values as well. (In this case category, title, photo etc.)
How can I do that?
Thank you!
EDIT:
This is my servlet.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.im.dao.PostAdDao;
import com.im.dao.PostAdDaoImpl;
import com.im.entities.Advertiesment;
#WebServlet("/postAd")
#MultipartConfig
public class PostAdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "C:/uploadss";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Advertiesment ad = new Advertiesment();
PostAdDao pad = new PostAdDaoImpl();
PrintWriter out = response.getWriter();
String name = null;
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(item.isFormField()){
String cat = request.getParameter("category");
System.out.println("INFO: Category : "+cat);
if( cat != null ){
ad.setCategory(cat);
}
String title = request.getParameter("adTitle");
if( title != null ){
ad.setTitle(title);
System.out.println("INFO: Title : "+title);
}
String des = request.getParameter("description");
if(des != null){
ad.setDescription(des);
System.out.println("INFO: Description : "+des);
}
try{
Double price = Double.parseDouble(request.getParameter("price"));
if(price != null){
ad.setPrice(price);
System.out.println("INFO: Price : "+price);
}
}catch(Exception e){
System.out.println("ERROR: Occured while setting price in servlet");
}
}else{
name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
request.setAttribute("message", "Advertiesment Posted Successfully");
System.out.println("INFO: Advertiesment Posted Successfully");
System.out.println("INFO: File name : "+name);
ad.setPhoto(name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
System.out.println("\nERROR: Occured while posting the advertiesment! "+ex );
}
}else{
//request.setAttribute("message","Sorry this Servlet only handles file upload request");
}
//request.getRequestDispatcher("/result.jsp").forward(request, response);
String msg = pad.postAd(ad);
}
}
I found some articles which use Apache commons, but in all of that, I
can get only the image
No . you can get other items also from the request .
DiskFileUpload upload = new DiskFileUpload();
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
//get form fields here
}
else {
//process file upload here
}}
Read the documentation here to understand more on this and also a nice thread here values of input text fields in a html multipart form
Update:
String cat = item.getFieldName("category") instead of request.getParameter("category");
Because you are parsing the request object . so you need to get it from FileItem object . similarly for other fields too.
From the Servlet I am generating JPEG image and writing in the outputstream of that servlet.By jsp i am calling this Servlet URL and displaying the image as similar to user profile with photo.
Here the problem is,When first time login it will generate the image dynamically and display but next time if I login with out closing the browser first it will display the privies picture and then it will display the current picture.
JSP:
<div class="sortable">
<div class="box span5" style="margin-left: 50px;">
<div class="box-header well">
<h2><i class="icon-th"></i>Employee Attendance</h2>
<div class="box-icon">
<i class="icon-chevron-up"></i>
</div>
</div>
<div class="box-content" style="height:230px;" >
<img border="0" src="admissionenquirylist.do?method=image" alt="Pulpit rock" width="370" height="240"/>
</div>
</div>
</div>
Servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.admission.process;
import com.google.gson.Gson;
import com.treamis.entity.Academicyearmaster;
import com.treamis.entity.AdmissionenquiryStudentdetails;
import com.treamis.entity.EmployeeEntity;
import com.treamis.hr.employee.PaginationClass;
import com.treamis.hr.employee.SetPaginationRecords;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.ServletOutputStream;
/**
*
* #author ranjeeth.g
*/
public class AdmissionEnquiry extends LookupDispatchAction {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
/**
* Provides the mapping from resource key to method name.
*
* #return Resource key / method name map.
*/
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("button.admissionEnqiryList", "admissionEnqiryList");
map.put("button.image", "image");
map.put("button.delete", "delete");
return map;
}
/**
* Action called on Add button click
*/
public void admissionEnqiryList(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
// TODO: implement add method
try {
String stdutendserch = request.getParameter("admissionenquirysearch");
System.out.println("stdutendserch = " + stdutendserch);
Admissionservices as = new Admissionservices();
List<Enquirylistbean> stdserc = as.getStudentEnquirySerch(stdutendserch);
if (stdserc != null) {
response.setContentType("application/json");
String json = new Gson().toJson(stdserc);
System.out.println("json = " + json);
response.getWriter().print(json);
} else {
response.setContentType("application/json");
String json = new Gson().toJson(null);
response.getWriter().print(json);
}
} catch (Exception e) {
e.printStackTrace();
}
// return mapping.findForward(SUCCESS);
// return null;
}
/**
* Action called on Edit button click
*/
public void image(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
try {
System.out.println("Inside the image responce action");
response.setContentType("image/jpeg");
Academicyearmaster academicyearmaster = (Academicyearmaster) request.getSession().getAttribute("academicyear");
// String ss = getServlet().getServletContext().getRealPath("\\");
// String filePath = ss + "img\\paichart.png";
ServletOutputStream out = response.getOutputStream();
// System.out.println("out = " + out);
// String filePath2 = ss + "img\\paichart1.png";
// ExecutorService executor = Executors.newFixedThreadPool(2);
com.treamis.hr.employee.Sendded sendded = new com.treamis.hr.employee.Sendded(out, academicyearmaster);
sendded.image();
// executor.execute(sendded);
} catch (Exception e) {
e.printStackTrace();
}
// TODO: implement edit method
// return mapping.findForward(SUCCESS);
}
/**
* Action called on Delete button click
*/
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws java.lang.Exception {
// TODO:implement delete method
return mapping.findForward(SUCCESS);
}
/* And your JSP would have the following format for submit buttons:
<html:form action="/test">
<html:submit property="method">
<bean:message key="button.add"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.edit"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.delete"/>
</html:submit>
</html:form>
*/
}
Java code to generate image:
try{
ChartUtilities.writeChartAsJPEG(out, chart, 600, 400, info);
// System.out.println("file2 = " + file1);
} catch (Exception e) {
e.printStackTrace();
return "success";
} finally {
out.close();
}
The answer lies in the Life cycle of Servlet. Even though multiple request comes to a servlet only one instance of the Servlet class will be created.
Check if you have any resources that is global and fix it.
Or post full servlet class for better response.
Hope it helps!
I think if you use differents files names to each file save in disk you will not have this problem again.
My project has been created by GAE Plugin for Eclipse (without Maven) and i'm goint to post my code composed by:
home.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload Test</title>
</head>
<body>
<form action="/upload" method="post" name="putFile" id="putFile"
enctype="multipart/form-data">
<input type="file" name="myFile" id="fileName">
<input type="submit" value="Upload">
</form>
</body>
</html>
UploadServlet.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.channels.Channels;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsOutputChannel;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.cloudstorage.RetryParams;
public class UploadServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(UploadServlet.class.getName());
private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());
private String bucketName = "myBucketNameOnGoogleCloudStorage";
/**Used below to determine the size of chucks to read in. Should be > 1kb and < 10MB */
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
#SuppressWarnings("unchecked")
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String sctype = null, sfieldname, sname = null;
ServletFileUpload upload;
FileItemIterator iterator;
FileItemStream item;
InputStream stream = null;
try {
upload = new ServletFileUpload();
res.setContentType("text/plain");
iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
item = iterator.next();
stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
sfieldname = item.getFieldName();
sname = item.getName();
sctype = item.getContentType();
GcsFilename gcsfileName = new GcsFilename(bucketName, sname);
GcsFileOptions options = new GcsFileOptions.Builder()
.acl("public-read").mimeType(sctype).build();
GcsOutputChannel outputChannel =
gcsService.createOrReplace(gcsfileName, options);
copy(stream, Channels.newOutputStream(outputChannel));
res.sendRedirect("/");
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}
}
I tried also to set the maximumSize of the Upload using upload.setMaxSize(-1); or changing the BUFFER_SIZE from 2*1024*1024 into 200*1024*1024, but the issue stil occur. To be more specific, when the uploading reach the 100% I receive this message on the webpage:
Error: Request Entity Too Large Your client issued a request that was too large.
How can i fix that using JAVA and Google Cloud Storage Client Library for Java? (I'm not going to change drastically the Project with other Programming Languages)
Could you please help me to find a solution? Thank you so much!
App Engine request limit is 32Mb. That's why your uploads are failing when you send a file > 32Mb. Checkout Quotas and Limits section.
You have two options for uploading files > 32Mb:
Blobstore API.
You can specify a GCS bucket instead of using Blobstore storage space.
To do that use createUploadUrl(java.lang.String successPath, UploadOptions uploadOptions) method of BlobstoreService.
Here's a sample app: https://github.com/crhym3/java-blobstore-gcs-sample
Signed URLs feature of GCS
Or you could just use Google Drive and store only doc IDs in the datastore :)
I will suggest you to take a look at this great and sample example: http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
A good idea will be to monitor the data stream to the server.
Hope it helps
i want to show online users using this servlet ......
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.chatapp.useroperation.Client;
#WebServlet(name = "onlineUsersServlet", urlPatterns = { "/getOnlineUsersList" })
public class ListOfOnlineUsers extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String commaSepeparatedStr ="";
ServletContext appScope = request.getServletContext();
String channel = request.getParameter("channel");
final Map<String, List<Client>> clients = (Map<String, List<Client>>) appScope.getAttribute(LoginServlet.CLIENTS);
System.out.println(clients);
if(clients.size()> 0){
final List<Client> onlineClients = clients.get(channel);
if(onlineClients !=null){
for (Client client : onlineClients) {
if(commaSepeparatedStr.equals("") ){
commaSepeparatedStr = client.getUserName();
}else{
commaSepeparatedStr =commaSepeparatedStr+","+ client.getUserName();
}
}
}
}
response.getWriter().write(commaSepeparatedStr);
response.flushBuffer();
}
}
how can i pass value to this servlet from a jsp so that it store the username in its list......is it possible to put value in that servlet from session.
in your jsp do something like this:
<form action="/YOURWEBAPPNAME/onlineUsersServlet/getOnlineUsersList" method="get">
<input type="text" name="test" value="Hello World">
<input type="submit" value="Send">
</form>
in you doGet method do this:
String userInput = request.getParameter("test");
and feel free using that stuff.
put that stuff in the session with:
request.getSession(false).setAttribute("input",userInput);
and read it with:
String lInput = (String) request.getSession(false).getAttribute("input");
If you want to Store a Value from a session to a servlet, just attach an attribute to the Session;
During Login, get the username and store the value into the Session;
HttpSession sess = request.getSession();//Create new Session
//Get the username from login input
String username = request.getParameter("name");
//Attach the name to the Session.
sess.setAttribute("username", username);
Get the value anytime as long as the session is active.
HttpSession sess = request.getSession(false);//Use the current Session
//Get the value fron the Session
String username = (String) sess.getAttribute("username");//get the Attribute Username
You need to have Attached the Attribute to the Session before you can get it this way.
There are variables with a different scope that you can, or not, access from different places in your code. In JavaEE there are variables with request, session and application scope.
The request scope means that you can set it and use it in all your classes for the current request and that's what you seem to need right now.
I'm sorry I can't help you more right now but with this info Google or the SO search box should be your friend. I'll add details later.
Edit -
Stefan beike's answer has these details I'm talking about.