show the pdf url to authenticated people on the application - url

I'm trying to opening the URL that has the pdf document in the new tab. If I click on 1000 anchor tags then it will display the url in new tab like http://sivls100.eskom.co.za:8080/finalnewnrs/Document.do?method=dt&fn=1000.pdf. But if any person has this URL in the network can see the pdf file. I would like to show the pdf file to authenticated users.I did some investigation and found that we can achieve this by setting authenticated user in attribute like setAttribute and get Attribute. I did some code and it works as long as session valid. My session timeout is 30 min.It will not work after 30 min.
Code:
public ActionForward dt(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object obj = request.getSession().getAttribute("userDetail");
String target = new String(SUCCESS);
if (obj == null) {
target = new String(FAILURE);
} else {
String filename = request.getParameter("fn");
request.setAttribute("filename", "upload/dt/" + filename);
}
return mapping.findForward(target);
}
Thank you for any help or atleast for the better design.

Related

How to download a file with Vaadin 10?

I want to let user to download a file from server.
I looked up for the solution and when trying to make an example - ended up with this:
#Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
Which is giving java.lang.IllegalArgumentException: Resource file name parameter contains '/' when I go to the page in browser.
How do I make a download button (or anchor) knowing file location on disk?
Have a look at the documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log". The content of the download is provided by the InputStream parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);

The constructor URL(Elements) is undefined

i m using jsoup Application and trying to get url of web pages. i got urls of web page. i m trying to get only image urls via url parsing
but when sending request to url i got this error
" The constructor URL(Elements) is undefined "
my question is how can i pass urls that i got from jsoup library
here is my code
' public static void main(String[] args) throws IOException {
Validate.isTrue(args.length == 1, "usage: supply url to fetch");
String url = args[0];
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
Elements media = doc.select("[src]");
Elements imports = doc.select("link[href]");
'
and using
'Elements imagepath = doc.select("[src]");'
and passing this Lement into url parsing function
URL url = new URL(imagepath);
can anyone help me to figure it out how to get url parsing function works
thanks in advance
The reason you get that exception is because you pass Elements to the URL constructor - the Elements is just the specialization of List<Element>. This means you probably have more than one image assigned to imagepath variable. If you would like to construct the URL objects from the scraped images, consider this code sample:
Elements images = document.select("img");
for (Element element : images) {
System.out.println(element.attr("abs:src"));
}
This should help you making progress with your application. I would love to answer any further question you might have.

MvcRazorToPdf save as MemoryStream or Byte[]

I'm using MvcRazorToPdf in a Azure website and create my PDF's and output them in the browser.
Now i'm creating a new function to directly email the PDF as attachment (without output them in the browser).
Does anybody know if it is possible to save the PDF (with MvcRazorToPdf) as a MemoryStream or Byte[]?
I think you can handle this in ResultFilter, I used below code to allow user to download file and prompt for download popup, in this way you can grab all your memory stream and store somewhere to send email afterwords.
public class ActionDownloadAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
base.OnResultExecuted(filterContext);
}
}
[ActionDownload]
public ActionResult GeneratePdf()
{
List<Comment> comments = null;
using (var db = new CandidateEntities())
{
comments = db.Comments.ToList();
}
return new PdfActionResult("GeneratePdf", comments);
}
I have implemented something like that. So basically I have not been changing my method to output PDF. What I have done is used restsharp to make request at URL where I get PDF then what you have is in lines of (this is partial code only so you can get idea )
var client = new RestClient(IAPIurl);
var request = new RestRequest(String.Format(IAPIurl_generatePDF, targetID), Method.GET);
RestResponse response = (RestResponse) client.Execute(request);
// Here is your byte array
response.RawBytes
Otherwise you can use my answer from here where I discussed directly returning a file.
Hope this helps!

asp.net mvc application down

I have a Live website called API Web, build with ASP.NET MVC 4.
This application is to provide a JavaScript files for other websites.
I have 20 websites requesting a JavaScript to it.
But, sometimes this API Web is going down and I have a trouble to make the application live again.
I don't know why this happen, and how can I solve this issue?
EDIT
This is the controller, if the website requesting a path say http://api.example.com/get/js/folderA?js=jquery.js
the application will return a javascript content.
but, the requesting website will load slower. and I think if the API Web had too much request, it will going down (bottleneck issue).
public ActionResult js(string id, string js) {
string fileLocation = Server.MapPath("~/content/" + id + "/js/" + CryptKeys.Decrypt(js) + "");
string contentType = "text/javascript";
var file = System.IO.File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var stream = (Stream)(file);
return new FileStreamResult(stream, contentType);
}
There is a chance that you are not closing the filestream opened by System.IO.File.Open class which may be leading to next call to return the same file in throwing an exception. And because the exception is not handled, this may eventually be leading to site being shutting down.
Did you check for error logs in event viewer?
Based on your inputs below, could you try this piece of code? Notice the using block that I have added
public ActionResult js(string id, string js) {
string fileLocation = Server.MapPath("~/content/" + id + "/js/" + CryptKeys.Decrypt(js) + "");
string contentType = "text/javascript";
using(var file = System.IO.File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var stream = (Stream)(file);
return new FileStreamResult(stream, contentType);
}
}

Serving an iCalendar file in ASPNET MVC with authentication

I'm trying to serve an iCalendar file (.ics) in my MVC application.
So far it's working fine. I have an iPhone subscribing to the URL for the calendar but now I need to serve a personalised calendar to each user.
When subscribing to the calendar on the iPhone I can enter a username and password, but I don't know how to access these in my MVC app.
Where can I find details of how the authentication works, and how to implement it?
It turns out that Basic Authentication is what is required. I half had it working but my IIS configuration got in the way. So, simply returning a 401 response when there is no Authorization header causes the client (e.g. iPhone) to require a username/password to subscribe to the calendar.
On the authorization of the request where there is an Authorization request header, the basic authentication can be processed, retrieving the username and password from the base 64 encoded string.
Here's some useful code for MVC:
public class BasicAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var auth = filterContext.HttpContext.Request.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", ""));
var value = Encoding.ASCII.GetString(encodedDataAsBytes);
var username = value.Substring(0, value.IndexOf(':'));
var password = value.Substring(value.IndexOf(':') + 1);
if (MembershipService.ValidateUser(username, password))
{
filterContext.HttpContext.User = new GenericPrincipal(new GenericIdentity(username), null);
}
else
{
filterContext.Result = new HttpStatusCodeResult(401);
}
}
else
{
if (AuthorizeCore(filterContext.HttpContext))
{
var cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null);
}
else
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusDescription = "Unauthorized";
filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", "Basic realm=\"Secure Calendar\"");
filterContext.HttpContext.Response.Write("401, please authenticate");
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new EmptyResult();
filterContext.HttpContext.Response.End();
}
}
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}
Then, my controller action looks like this:
[BasicAuthorize]
public ActionResult Calendar()
{
var userName = HttpContext.User.Identity.Name;
var appointments = GetAppointments(userName);
return new CalendarResult(appointments, "Appointments.ics");
}
I found this really helpful, but i hit a few problems during the development and i thought i would share some of them to help save other people some time.
I was looking to get data from my web application into the calendar for an android device and i was using discountasp as a hosting service.
The first problem i hit was that the validation did not work when uploaded to the server, stangely enough it was accepting my control panel login for discountasp but not my forms login.
The answer to this was to turn off Basic Authentication in IIS manager. This resolved the issue.
Secondly, the app i used to sync the calendar to the android device was called iCalSync2 - its a nice app and works well. But i found that it only worked properly when the file was delivered as a .ics (duh for some reason i put it as a .ical.. it must have been late) and i also had to choose the webcal option
Lastly i found i had to add webcal:// to the start of my url instead of http://
Also be careful as the code posted above ignores the roles input variable and always passes nothing so you might need to do some role based checks inside your calendar routine or modify the code above to process the roles variable.

Resources