Notifying user download has finished. - notifications

Hi i have a command button.
I am using jsf 1.12 and tomahwak. I also am using jquery on client side.
<h:commandButton type="submit" value="Download Receipt"
onclick="refresh();"
id="downloadDocument"
actionListener="#{transactionPage.downloadReceipt}"
immediate="true"
/>
My jsf backing bean function
public void downloadReciept(final ActionEvent event) {
try{
DocManager docManager = new DocManager();
docManager.printDocs();
}catch (Exception e) {
log.error("Fail to download document!", e);
}
}
print docs would just create a file and stream it by setting the content-type, response, etc.
File sourceFile = createDoc();
Url url = sourceFile.toURI().toURL();
streamDoc(url);
I want to be able to display a message when downloading is starting and message when it finished

Hi thanks found my solution.
I change to commandLink than
set the cookie in backend and use jquery's file download

Related

custom login module to access httpservletrequest in JBOSS EAP

I am developing a custom login module for jboss' jaas implementation. I would like to be able to access the HttpServletRequest object inside my login module. Does anyone know the best way to do this, if it's possible? I've been researching this, and so far I think I need to use a Callback of some kind, but I'm not sure.I found some WebSphere documentation that shows they have a WSServletRequestCallback that seems to be able to do this. Please suggest a simple example or documentation if jboss' jaas implementation have anything like this.
Update:
#kwart: As per your suggestion, I coded the following. Please suggest if this is the right way:
protected CallbackHandler _callbackHandler;
HttpServletRequest request = null;
ObjectCallback objectCallback = null;
Callback[] callbacks = new Callback[1];
callbacks[0] = objectCallback = new ObjectCallback("HttpServletRequest: ");
try
{
_callbackHandler.handle(callbacks);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error handling callbacks", e);
}
try
{
if (objectCallback != null)
{
request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest");
}
}
catch (PolicyContextException e) {
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error getting request", e);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Exception occured augmenting JbossSubject", e);
}
You can use JACC PolicyContext to retrieve the HttpRequestObject in the LoginModule methods:
HttpServletRequest request = (HttpServletRequest) javax.security.jacc.PolicyContext
.getContext(HttpServletRequest.class.getName());
Update: Find sample usage in LoginModule here.
I got a solution from this site.
Used JSPI authentication. Configured an auth module in security domain in standalone as explained here .
Created a custom authenticator and a custom login module, configured the authenticator in jboss-web.xml and login module in security domain in standalone xml.
I jar'd them in a separate module and added that to jboss-deployment-structure.xml. Stored http request in ThreadLocal in the authenticator and retrieved it in my login module by simply reading the value stored in the Thread Local.

How to solve file upload error in Postman?

I use file upload with webapi in my project. I am testing with Postman. However, Request.Content.IsMimeMultipartContent() always returns false.
Postman screenshot:
FileUploadController Code:
public async Task<HttpResponseMessage> UserImageUpload()
{
try
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var userImageUploadPath = HttpContext.Current.Server.MapPath(CommonParameters.UserProfileImageServerPath);
var streamProvider = new CustomMultipartFormDataStreamProvider(userImageUploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
var files = new List<string>();
foreach (MultipartFileData file in streamProvider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (Exception exception)
{
logger.ErrorFormat("An error occured in UserImageUpload() Method - Class:FileUploadController - Message:{0}", exception);
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
This is Postman bug. Try removing the Content-Type header. When sending the actual Post, the browser will automatically add the proper header and create the boundary.
There is no need to mention Content-Type in headers in Postman, I tried sending attachments without Content-Type it works fine for me.
When i used Content-Type: multipart/formdata it throws an error saying "Could not get any response". Postman sends your file attachments also with Content-Type →text/plain; charset=utf-8.
There are few things to consider:
1) Don't send any Content Type Header if you are using Postman
2) Specify the Key for your choosen file in Body (PFB Screenshot for your reference)
You need to uncheck Content-Type if you have it checked, and let Postman add it for you, like in this picture:
Might by a bit late. I encountered the same error in ARC and resolved by providing a name for the file field (after the blue check mark on your second screenshot)

Primefaces fileupload mode="Simple" with commandbutton ajax="true" throws nullpointer exception

This is in reference to the following thread
[File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data
The problem I experience is Nullpointer on clicking the command button.
Starting from the web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
xhtml
<p:fileUpload id="file" value="#{userBean.uploadedFile}"
mode="simple" required="true" allowTypes="*.xls,*.xlsx"
requiredMessage="#{msg.vrUserUpload}"
invalidFileMessage="#{msg.vrUserUploadInvalidFile}"
multiple="false" fileUploadListener="userBean.fileUploadListener" />
<p:commandButton id="btnUpload" value="#{displayText.btUpload}"
styleClass="button_lite" actionListener="#{userBean.insert}"
ajax="true" update="userMassUploadForm"
process="userMassUploadForm">
</p:commandButton>
UserBean.java
public void fileUploadListener(FileUploadEvent event)
{
uploadedFile = event.getFile();
}
public void insert(){
if(uploadedFile!=null){
System.out.println(uploadedFile.getFileName());
}
else{
System.out.println("The file object is null.");
}
}
Console prints out "The file object is null." whenever ajax="true" and when set to false, works. I could not find a solution for this in the above referred thread.
Please advise.Also please let me know if you want any further information.
From PrimeFaces user guide:
Simple File Upload
Simple file upload mode works in legacy mode with a file input whose value should be an UploadedFile instance. Ajax uploads are not supported in simple upload.

Exception error in google doc api

I am new to google api. I am trying to create a simple web application (Java EE) to read DocumentListFeed from google doc. My code in the servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DocsService service = new DocsService("Document List Demo");
service.setUserCredentials(NAME, PASSWORD);
response.getWriter().println("helloooooo");
//URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
URL documentListFeedUrl = new URL("https://docs.google.com/feeds/default/private/full?v=3");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries())
{
response.getWriter().println(entry.getTitle().getPlainText());
}
}
catch (Exception e)
{
response.getWriter().println(e);
}
}
But it is showing me the error: java.lang.NoClassDefFoundError: com/google/gdata/client/docs/DocsService
I am using Glassfish server and Ecllipse. And added external jar file: activation.jar, guava-r07.jar, mail.jar, servlet.jar, gdata-client-1.0.jar, gdata-client-meta-1.0.jar, gdata-core-1.0.jar, gdata-media-1.0.jar, gdata-docs-3.0.jar, gdata-docs-meta-3.0.jar.
I have copied this same code to java standard edition and it is working fine. Could please tell me why this thing is not working in Java EE? Is it a problem in GlassFish server?
It just means that the jars are not present in your Glassfish server classpath.
Add all the jars you listed to yuor glassfish server classpath. Since am not an Glassfish expert i cannot help you in adding the jars to your server.
In case of weblogic, you just need to package all the jars in your project APP-INF directory.
Hope it helps.

Unable to listen to events using Apache Commons Email

I'm sending emails using Apache commons email lib.
However, I'm unable to listen to Connection and Transport events. I have added event listeners using:
email.getMailSession().getTransport().addConnectionListener(this);
email.getMailSession().getTransport().addTransportListener(this);
...but don't receive any events.
My code is as follows:
public class MailSendTest implements ConnectionListener, TransportListener{
final Email email = new SimpleEmail();
public void sendEmail(){
try {
email.setHostName("smtp.host.com");
email.setFrom("from#host.com");
email.addTo("to#host.com");
email.setBounceAddress("from#host.com");
email.setSubject("Testing");
email.setMsg("Test Message");
email.setDebug(true);
email.setAuthentication("from#host.com", "pass");
email.setSslSmtpPort("465");
email.setSocketTimeout(60000);
email.getMailSession().getTransport().addConnectionListener(this);
email.getMailSession().getTransport().addTransportListener(this);
email.send();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Err : "+ex.getMessage());
}
}
#Override
public void opened(ConnectionEvent e) {
System.out.println("####Connected to "+ email.getHostName());
}
#Override
public void disconnected(ConnectionEvent e) {
System.out.println("####Disconnected from "+ email.getHostName());
}
#Override...
}
Any help would be appreciated.
I'm also found it unable to do so, but after do some digging ... I found out that commons mail is dependent to java mail API (mail.jar), so apache commons mail is just abstracting what should be done discreetly if you are using java mail API.
What I suggest is to follow what this tutorial here do, which is creating Session object, then retrieves the Transport object from it ... then you can attach your TransportListener.
I am still doing the above way currently (while writing this), I hope its work!
By the way, use this to define properties for SMTP.
Good luck