Alert window after submiting FormPanel - java

I have next problem... when i submit form and my Post method end. Form(or not)throwing empty alert window. how can I delete this throwing window?
ClienSide
....
final FormPanel form = new FormPanel();
form.setAction(GWT.getModuleBaseURL()+"upload");
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
fileButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
});
FileUploadServlet
public class FileUploadServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(req)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(req);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) continue;
String fileName = fileItem.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
File uploadedFile = new File("test.txt");
if (uploadedFile.createNewFile()) {
fileItem.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maybe someone knows the reason of this alert?

If it is a simple Javascript alert window you need to track/search for it in three places
Steps - Search for alert string across client code
1) In javascript - third party .js file . String search for `alert` in such js files
2) In third party gwt jar .
a) String search for Window.alert in the GWT java code
b) String search for wnd.alert in GWT jsni code
3) In Your own source code - repeat steps "a" and "b" from Step 2
It is unlikely but also string search you server side code base if in case they are building a string in response and displaying it via some other mechanism.

Related

Calling a Servelet from Spring Rest Controller and return image from Servlet

I am having a Servlet which I am using to fetch the image from Database and display image to frontend.
Servlet:
#WebServlet("/jsp/DisplayImage")
public class DisplayImage extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
int id = Integer.parseInt(request.getParameter("userId"));
User query = new User();
//fetch user details
.......
//write user photo to response
response.reset();
response.setContentType("image/.*");
OutputStream out = response.getOutputStream();
out.write(user.getPhoto());
out.close();
} catch (Exception e) {
.......
}
}
This servlet is working fine. Now I want to create a rest api which will call this Servlet and return the user photo:
#GetMapping("displayImage")
public void getDisplayImage(#RequestParam("userId") final Integer userId) {
//TODO call DisplayImage servlet and return user photo
}
I solved this by redirecting to my servlet
#GetMapping("displayImage")
public void getDisplayImage(#RequestParam("userId") final Integer userId,
HttpServletResponse response) throws IOException {
String displayImageUrl="https://localhost:8443/app/jsp/DisplayImage?userId="+userId;
response.sendRedirect(displayImageUrl);
}

Java Servlet parse request body multithread

I've implemented a asynchronous Servlet, which needs to parse the body of request and store the parsed result in cache. Should I implement the parseBody() function in Servlet or implement a new class, which will do the parsing? What is the best practice?
Here is my current code snippet:
public class DocFeedServlet extends FeedServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(DocFeedServlet.class);
private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final AsyncContext asyncContext = req.startAsync();
asyncContext.start(new Runnable() {
#Override
public void run() {
String bodyStr = getBody(req);
if (bodyStr.isEmpty()) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
asyncContext.complete();
return;
}
int ignoreTime = Integer.parseInt(req.getParameter(Constant.PARAM_IGNORE_TIME));
List<MockDocCacheKeyVal> mockDocCacheKeyVals = new ArrayList<>();
List<String> docUpdateFields = new ArrayList<>();
List<List<String>> docKeepFields = new ArrayList<List<String>>();
List<String> uuidsToRemove = new ArrayList<>();
int parseRet = parseBody(bodyStr, mockDocCacheKeyVals, docUpdateFields, docKeepFields, uuidsToRemove, ignoreTime);
if (parseRet != 0) {
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
asyncContext.complete();
}
});
}
protected int parseBody(String body, List<MockDocCacheKeyVal> mockDocCacheKeyVals, List<String> docUpdateFields, List<List<String>> docKeepFields, List<String> uuidsToRemove, int ignoreTime) {
try {
ObjectReader reader = OBJECTMAPPER.reader(new TypeReference<List<Document>>() { });
List<Document> documents = reader.readValue(body);
for (Document doc : documents) {
if (doc.getAction() != null && doc.getAction().equalsIgnoreCase(Constant.DOC_FEED_ACTION_DELETE)) {
if (doc.getUuid() != null) {
uuidsToRemove.add(doc.getUuid());
}
continue;
}
if (doc.getA() != null) {
} else if (doc.getB() != null) {
} else {
DocumentUtils.pruneWeightSet(doc.getC(), cPruneSize);
DocumentUtils.pruneWeightSet(doc.getD(), dPruneSize);
DocumentUtils.pruneWeightSet(doc.getE(), ePruneSize);
}
}
return documents.size();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return 0;
}
}
Thanks.
Asynchronous Request Body read is accomplished with the HttpServletRequest.getInputStream().setReadListener(ReadListener) concepts introduced in Servlet 3.1
You will only read based on events from your ReadListener, and you will only read enough to not block. (so no reading multi-megabyte buffers!).
This API is what you are looking for, however there be land mines here, so be sure you fully understand the API before you finish it.

How do I write the Java logger Servlet?

I want to do some log in my system, like user action,
and I know in the servelet I can get the request with all the session,parameter..etc
So I want to write the Servlet
public class UserActionCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Map map = request.getParameterMap();
Set keSet = map.entrySet();
for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
Map.Entry me = (Map.Entry) itr.next();
Object ok = me.getKey();
Object ov = me.getValue();
String[] value = new String[1];
if (ov instanceof String[]) {
value = (String[]) ov;
} else {
value[0] = ov.toString();
}
for (int k = 0; k < value.length; k++) {
System.out.println(ok + "=" + value[k]);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//HttpSession session = request.getSession();
}
}
then I can see the parameter output in the tomcat console..but I get the blank page..
It seems the page is stop after doGet method..
so how should I make it continue?
use that RequestDispatcher?
also how to handle in the doPost?
For your purpose, the best way would be to use a Filter.
Example :
#WebFilter(filterName = "monitoringFilter", urlPatterns = { "/*" })
public class MonitoringFilter implements Filter
{
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
// Right here do your stuff pretty much like in a servlet
request // ... get information you need
// Process request as normal
chain.doFilter(request,response);
}
#Override
public void init(FilterConfig config) throws ServletException
{
}
#Override
public void destroy()
{
}
}
More info :
Filter
You should use log4j and FileAppender to implement logging in your application.
Something like this :::
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class A{
static Log log = LogFactory.getLog(A.class);
void methodA(){
try{
log.info("I am inside A");
} catch(Exception e) {
log.error("error" , e);
}
}
}

Non-ASCII Characters Not Displayed When Reading From GridFS

I am uploading files (of different content types) using Apache fileupload API as follows:
FileItemFactory factory = getFileItemFactory(request.getContentLength());
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(maxSize);
uploader.setProgressListener(listener);
List<FileItem> uploadedItems = uploader.parseRequest(request);
... saving files to GridFS using the following method:
public String saveFile(InputStream is, String contentType) throws UnknownHostException, MongoException {
GridFSInputFile in = getFileService().createFile(is);
in.setContentType(contentType);
in.save();
ObjectId key = (ObjectId) in.getId();
return key.toStringMongod();
}
... calling saveFile() as follows:
saveFile(fileItem.getInputStream(), fileItem.getContentType())
and reading from GridFS using the following method:
public void writeFileTo(String key, HttpServletResponse resp) throws IOException {
GridFSDBFile out = getFileService().findOne(new ObjectId(key));
if (out == null) {
throw new FileNotFoundException(key);
}
resp.setContentType(out.getContentType());
out.writeTo(resp.getOutputStream());
}
My servlet code to download the file:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
String[] uriParts = uri.split("/"); // expecting "/content/[key]"
// third part should be the key
if (uriParts.length == 3) {
try {
resp.setDateHeader("Expires", System.currentTimeMillis() + (CACHE_AGE * 1000L));
resp.setHeader("Cache-Control", "max-age=" + CACHE_AGE);
resp.setCharacterEncoding("UTF-8");
fileStorageService.writeFileTo(uriParts[2], resp);
}
catch (FileNotFoundException fnfe) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch (IOException ioe) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
}
However; all non-ASCII characters are displayed as '?' on a web page with encoding set to UTF-8 using:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
Any help would be greatly appreciated!
Apologies for taking your time! This was my mistake. There is nothing wrong with the code or GridFS. My test file's encoding was wrong.
resp.setContentType("text/html; charset=UTF-8");
Reason: only content type, together with a binary InputStream are passed on.
public void writeFileTo(String key, HttpServletResponse resp) throws IOException {
GridFSDBFile out = getFileService().findOne(new ObjectId(key));
if (out == null) {
throw new FileNotFoundException(key);
}
resp.setContentType(out.getContentType()); // This might be a conflict
out.writeTo(resp.getOutputStream());
}

Record Request and Response with Servlet Filter

i'm study to devolop a servlet/filter to use in a web application, the filter have to record every request on the site by all user of the web application.
in my head the filter have to work in this way
filter -> request -> save request -> do.chain
public class ServletFilter implements Filter {
private Application fApp;
StringWriter ResponseRECORDER;
StringWriter RequestRECORDER;
#Override
public void init(FilterConfig config) throws ServletException {
fApp = (Application)config.getServletContext().getAttribute("application");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(request,response);
// Ignore non-http requests.
if (!(request instanceof HttpServletRequest))
{
chain.doFilter(request,response);
return;
}
((HttpServletRequest)request).getSession();
// Write the request out to the recording file.
recordReqResHTTP((HttpServletRequest) request,
(HttpServletResponse) response);
StringBuilder Fixed = new StringBuilder();
Fixed.append("[Message]");
Fixed.append("[time]");
Fixed.append(System.currentTimeMillis());
Fixed.append("[/time]");
Fixed.append("[Request]");
Fixed.append(RequestRECORDER);
Fixed.append("[/Request]");
Fixed.append("[Response]");
Fixed.append(ResponseRECORDER);
Fixed.append("[/Response]");
Fixed.append("[/Message]");
MessagingService s = (MessagingService)fApp
.getService("it.interprise.core.workflow.MessagingService");
try {
s.send("recorder", Fixed.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void destroy() {
}
public void recordReqResHTTP(HttpServletRequest request,
HttpServletResponse response)
{
//HttpSession session = request.getSession();
//costruisco una stringa per la raccolta dati
StringWriter ResponseRECORDER = new StringWriter();
StringWriter RequestRECORDER = new StringWriter();
try
{
//Registro la Request
PrintWriter out = new PrintWriter(RequestRECORDER);
out.println("<request>");
out.print("<uri>");
out.print(request.getRequestURI());
out.println("</uri>");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String paramName = (String) e.nextElement();
String[] values = request.getParameterValues(paramName);
for (int i=0; i < values.length; i++)
{
out.print("<param><name>");
out.print(paramName);
out.print("</name><value>");
out.print(values[i]);
out.println("</value></param>");
}
}
out.println("</request>");
out.close();
//Registro la Response
PrintWriter res = new PrintWriter(ResponseRECORDER);
res.println("<request>");
res.print("<uri>");
res.print(request.getRequestURI());
res.println("</uri>");
Enumeration f = request.getParameterNames();
while (f.hasMoreElements())
{
String paramName = (String) f.nextElement();
String[] values = request.getParameterValues(paramName);
for (int i=0; i < values.length; i++)
{
res.print("<param><name>");
res.print(paramName);
res.print("</name><value>");
res.print(values[i]);
res.println("</value></param>");
}
}
out.println("</request>");
out.close();
}
catch (Exception exc)
{
}
}
}
and the same for the response, have you any idea how i could solve the problem?
With this filter the web application stop response...
thank you
The first thing you should do is to log the Exception at the bottom of your example, at least. Maybe there is an Exception raised that cannot be identified by inspecting the code.
A few lines before you close the PrintWriter twice, which could lead to IOException.
Second: You declare instance variables ResponseRECORDER and RequestRECORDER, but later you declare two local variables with same name. Remove the instance variables - the filter must be implemented thread safe.
Once done, I'll guess we will see a hidden NullPointer.

Categories

Resources