Wher to keep files to make it accessible in apache tomcat? - apache

I have a file named index.jsp that contains a form, form action is a .java file named getAttr.java . Inside getAttr.java servlet I am writing code that will download a .jar file located in same directory as WEB-INF.
getJar.java code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/jar");
ServletContext context=getServletContext();
InputStream inputStream=context.getResourceAsStream("eee.jar");
int read=0;
byte bytes[]=new byte[1024];
OutputStream outputStream=response.getOutputStream();
while((read=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,read);
}
outputStream.flush();
RequestDispatcher dispatcher=request.getRequestDispatcher("getJar.jsp");
dispatcher.forward(request, response);
outputStream.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
getJar.jsp code:
<!-- necessary html code here !>
<body>
<%
// contains no code.
//I don't know what to write here
%>
</body>
<!-- necessary html code here !>
I am coding J2EE in eclipse neon. My directory structure
Now my problem is:
User clicks a button in index.jsp which sends him to getAttr.java servlet.
getAttr servlet shows this error:
perhaps eee.jar is not accessible. Where to keep this .jar file?
Ask me if more information is needed.

Related

How can i add response header to a pdf in CQ5

I am trying add canonical tags to PDF and for that i have to update response header when PDF is loaded. I was able to add header for cq:page very easily:
#SlingServlet(
resourceTypes = "cq:Page",
extensions = "html",
methods = "GET")
#Properties({
#Property(name = "service.description", value = "Servlet to handle all incoming widget modification")
})
public class canocalizePDF extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.addHeader(“canonical", “test");
}
#Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
}
}
But when i try to same for PDF, it is not working. I have tried dam:Asset, dam:AssetContent as resourceTypes, but nothing seems to be working.
Any help would be great.
Thanks,
Vishal
The servlet that you've written is not handling your asset requests. If you want to handle this in AEM, you will need to override the OOTB AEM's AssetDownloadServlet with your own servlet implementation. You can then add the canonical link header in your servlet response.
How to override this is explained in detail in this blog post. They've also included a link to sample code for this customization.
However, if you have a webserver (e.g. Apache) in your setup, you should really handle this there. This is shown in this Moz blog post. Moz is the pinnacle of SEO best practices. I will recommend that.

JAXRS: No message body reader in a simple example?

I do not understand why this happens: when I declare explicitly the filename of the input in my annotated java class named "process", everything works perfect:
#GET
public static void process() throws IOException {
File file = new File("a.pdf");
FileUtils.writeStringToFile(new File("a.pdf" + ".exported"), menu.parseToString(file));
}
However, when I try to pass the file name as an argument, and configure also eclipse through run configurations to give the appropriate argument (path to the "a.pdf"):
#GET
public static void process(String[] args) throws IOException {
File file = new File(args[0]);
FileUtils.writeStringToFile(new File(args[0] + ".exported"), menu.parseToString(file));
}
when I call the service it fails with an error:
Oct 09, 2014 9:44:55 AM org.apache.cxf.jaxrs.utils.JAXRSUtils readFromMessageBody
WARNING: No message body reader has been found for request class String[], ContentType :
application/octet-stream.
I am new to jax rs. Do I miss any annotation? Thank you very much...
Invalid Java syntax
This
public static void process("a.pdf") throws IOException {
// ...
}
is not valid Java syntax. Every IDE and javacwill complain about it. Eclipse says:
Syntax error on token ""a.pdf"", delete this token
application/octet-stream as body
It looks like you try to make a GET request with Content-Type: application/octet-stream (the file you somehow 'clicked'). This has two problems:
A GET request normally as no body, it just has headers.
A body of bytes encoded as application/octet-stream can not be mapped to a String[] because JAX-RS has no way to know how to intepret the bytes.
What you probably want
It looks like you want to make a GET request with a file name as a request parameter (that is not the sames as a file in the body of the request). You could do this:
GET http://example.com/service?filename=foo.pdf
Then a JAX-RS like the following could be used to service this request:
#GET
public Response service(#QueryParam("filename") String filename) {
// use filename to open a File and do something with it
}
Note the use of #QueryParam which allows service to extract filename=foo.pdf from the request URL.

Notifying user download has finished.

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

Glassfish 4, JSF 2.2 and PrimeFaces FileUploadEvent not working together

After upgrading to GlassFish 4 and JSF 2.2 Primefaces FileUploadEvent stop working. With JSF 2.1 it was working with no problem. Everything is working fine except file uploading. Is there something that I am missing?
GlassFish 4
JSF 2.2
PrimeFaces 3.4.2 and 3.5
Commons io version: 2.4
Commons fileupload version: 1.3
Controller side
public void handleFileUpload(FileUploadEvent event) {
System.out.println("HandleFileUpload");
byte[] file = event.getFile().getContents();
newFieldset.setData(file);
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
View
<h:form enctype="multipart/form-data">
<p:fieldset legend="Create new feed" toggleable="true" collapsed="true" >
<p:fileUpload fileUploadListener="#{adminHomeController.handleFileUpload}" style="margin-top: 20px;"
mode="advanced"
update="messages"
sizeLimit="1000000"
multiple="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:inputText label="Baslik" style="margin-top: 20px;" required="true" value="#{adminHomeController.newFieldset.legend}" />
<p:editor style="margin-top: 20px;"
value="#{adminHomeController.newFieldset.content}" />
<p:commandButton style="margin-top: 20px;" value="#{msg['common.save']}" update="messages" icon="ui-icon-disk" actionListener="#{adminHomeController.saveFieldset()}"/>
</p:fieldset>
<p:growl id="messages" showDetail="true"/>
</h:form>
I was finally able to figure it out. Commons-fileuploads method parseRequest(httpServletRequest) tries to read the request's inputStream. Since the container already read it, it is empty. So what can be done to solve this? The answer is a bit more complicated than I initially thought it would be. First you will need your own FileUploadFilter which could look like this:
public class FileUploadFilter implements Filter
{
private final static Logger LOGGER = LoggerFactory.getLogger(FileUploadFilter.class);
/*
* (non-Javadoc)
*
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
/*
* (non-Javadoc)
*
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
boolean isMultipart = (httpServletRequest.getContentType() == null) ? false : httpServletRequest.getContentType().toLowerCase().startsWith("multipart/");
if (isMultipart)
{
MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest);
LOGGER.info("File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");
filterChain.doFilter(multipartRequest, response);
}
else
{
filterChain.doFilter(request, response);
}
}
/*
* (non-Javadoc)
*
* #see javax.servlet.Filter#destroy()
*/
#Override
public void destroy()
{
LOGGER.info("Destroying UploadFilter");
}
Next: Register this filter in your web.xml and remove/replace the Primefaces filter. This should look something like this:
<filter>
<filter-name>FileUpload Filter</filter-name>
<filter-class><YourPackage>.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
Unfortunately thats not it. You will need your own MultipartRequest since you have to assemble the list of FileItems by yourself. But Stop. We have to work with the javax.servlet.Part classes which are not compatible with the FileItem. So i wrote a new class which bridges these two. You can find this class here: http://pastebin.com/JcfAYjey
The last piece of the puzzle is the mentioned MultipartRequest which links the PartItem and the FileUploadFilter. I took this class from the Primefaces-Repository and changed it according to out needs (see http://pastebin.com/Vc5h2rmJ). The difference is between lines 47 and 57.
So what do you have to do:
1. Create the three classes FileUploadFilter, MultipartRequest and PartItem
2. Register the FileUploadFilter in your web.xml
3. Enjoy!
PLEASE NOTE: This is not intended as a solve-all-problems solution but a merely a direction you may take in further implementations. The MultipartRequest for example will only work for parts with content-type image/*. You may need to change this.
Feel free to change the code ;) Hope it helps!
EDIT: I forgot to mention one important step. You will additionally need your Own FileIUploadRenderer. The one Primefaces implemented uses an instanceof check to find the MultipartRequest. Since you are now using a different one the import has to be changed. The rest of the class can stay the same (http://pastebin.com/rDUkPqf6). Don't forget to register it inside of your faces-config.xml :
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.FileUploadRenderer</renderer-type>
<renderer-class><YourPackage>.FileUploadRenderer</renderer-class>
</renderer>
</render-kit>
Answer lies in UploadFile getInputstream() method. Don't rely on getContents() method.
This is my simple solution which worked with the below dependencies in glassfish 4
Primefaces 4.0.RC1
jsf 2.2
commons-fileupload 1.3
private byte[] getFileContents(InputStream in) {
byte[] bytes = null;
try {
// write the inputStream to a FileOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
bos.write(bytes, 0, read);
}
bytes = bos.toByteArray();
in.close();
in = null;
bos.flush();
bos.close();
bos = null;
logger.debug("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
return bytes;
}
getFileContents(getFile().getInputstream());
Try to delete beans.xml (CDI configuration file) and use JSF beans.
I saw on PrimeFaces blog that full JSF 2.2 support will be as of version 4.0.
See 3.5 is missing dependency - so won't launch
I think it's a commons-fileupload issue. When I debug through the code, the PrimeFaces' UploadFilter triggers correctly the commons-fileupload's FileUploadBase.parseRequest method (identically flow when I use GlassFish 3.1.22 or GlassFish 4), but the check on FileItemIterator.hasNext returns false.

Permission denied in jnlp trying call showDocument with a pdf file

I need some help with this showDocument in my jnlp aplication.
I trying to show a pdf file in another tab from browser, but the java plugin denied.
My JNLP file has a
<security>
<all-permissions/>
</security>
and my code is:
AccessController.doPrivileged(new PrivilegedAction()
{
#Override
public Object run()
{
try
{
applet.getAppletContext().showDocument(new URL("file:///C:/Contrato.PDF"), "_blank");
}
catch(Exception e)
{
e.printStackTrace();
showException("Erro ao exibir arquivo:" + e.getMessage());
}
return null;
}
});
but I receive the exception
java.lang.SecurityException: showDocument url permission denied
If I try to do showDocument(google.com, _blank) that works...but when I try to show any file, it does not work.
The showDocument(URL) method of AppletContext was never intended for launching files off the local file-system (even when specified as a file protocol URL).
There are at least two alternatives:
The JNLP snippet indicates this is a trusted app., so for a 1.6+ app., Desktop.browse(URI) can be invoked.
The BasicService of the JNLP API offers the showDocument(URL) method.