Get file content of a file uploaded using rich:fileUpload - file-upload

So I have an xhtml page that contains the following code:
<rich:fileUpload
id="uploadReportTemplate"
addControlLabel="Add XSLT"
fileUploadListener="#{manageFeedTypeAction.fileUploadListener}"
uploadData="#{manageFeedTypeAction.data}"
listWidth="63px" listHeight="0px" maxFilesQuantity="1"
immediateUpload="true" acceptedTypes="xsl,xslt"
allowFlash="false"
status="eventQueueFileUpload"
ontyperejected="javascript:Richfaces.showModalPanel('wrongSelectionModal');this.disabled=false">
<a4j:support event="onuploadcomplete" reRender="fileUploadPanel"/>
</rich:fileUpload>
I am only allowing the user to upload one file. Once this file has been uploaded, I wish to check if the file contains a certain keyword. How can I check whether the file contains that keyword? Please help.

I was able to solve this by adding the following code to the fileUploadListener method being called at fileUploadListener="#{manageFeedTypeAction.fileUploadListener}" above:
public void fileUploadListener(UploadEvent event) {
UploadItem item = event.getUploadItem();
if(item == null || item.getData() == null) {
LOG.error("Uploaded item is null");
} else {
String value = new String(item.getData());
if(value.toLowerCase().contains("String")) {
LOG.error("Cannot contain 'String'");
} else {
setData(item.getData());
setFileName(item.getFileName());
}
}
}

Related

JavaFX - set programmatically the destination path to print directly a node to pdf file

I want to print a node to a pdf file using "Microsoft Print to PDF" printer. Supposing that the Printer object is already extracted I have the next function which is working perfectly.
public static void printToPDF(Printer printer, Node node) {
PrinterJob job = PrinterJob.createPrinterJob(printer);
if (job != null) {
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
PageLayout pageLayout = job.getPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT,
Printer.MarginType.HARDWARE_MINIMUM);
boolean printed = job.printPage(pageLayout, node);
if (printed) {
job.endJob();
} else {
System.out.println("Printing failed.");
}
} else {
System.out.println("Could not create a printer job.");
}
}
The only issue that I have here, is that a dialog box is popping up and asking for a destination path to save the pdf. I was struggling to find a solution to set the path programmatically, but with no success. Any suggestions? Thank you in advance.
After some more research I came with an ugly hack. I accessed jobImpl private field from PrinterJob, and I took attributes out of it. Therefore I inserted the destination attribute, and apparently it is working as requested. I know it is not nice, but ... is kind of workable. If you have any nicer suggestion, please do not hesitate to post them.
try {
java.lang.reflect.Field field = job.getClass().getDeclaredField("jobImpl");
field.setAccessible(true);
PrinterJobImpl jobImpl = (PrinterJobImpl) field.get(job);
field.setAccessible(false);
field = jobImpl.getClass().getDeclaredField("printReqAttrSet");
field.setAccessible(true);
PrintRequestAttributeSet printReqAttrSet = (PrintRequestAttributeSet) field.get(jobImpl);
field.setAccessible(false);
printReqAttrSet.add(new Destination(new java.net.URI("file:/C:/deleteMe/wtv.pdf")));
} catch (Exception e) {
System.err.println(e);
}

<p:media display pdf from folder dynamically

I have several pdf files saved in ...WebContent/Manuals/filename.pdf that I am trying to display on my page. I am getting "Failed to Load PDF document" message in Chrome.
My Jsf:
<p:media value="#{reviewBean.manual}" player="pdf" height="600px" width="1000px" />
My #SessionScoped Bean:
public StreamedContent getManual() throws IOException {
String type = "application/pdf";
String path = "";
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
path = "C:\\.....\\WebContent\\Manuals\\filename.pdf";
InputStream is = new ByteArrayInputStream(path.getBytes());
return new DefaultStreamedContent(is, type);
}
}
There is additional logic that i have left out for clarity which decides which pdf is displayed.
I have also tried the file path of /Manuals/filename.pdf as path
I tried following the below example:
How to bind dynamic content using <p:media>?
In my case I do not need to retrieve a value using <f:param
Is my file path incorrect to display the image? Or am I building the Stream incorrectly? Any guidance is much appreciated.
I solved this by merely returning the url as a String.
public String getManual() {
return user.getManuals().get(user.getLData().getDepart());
}
Where the returned value is the file path of the pdf: Manuals/filename.pdf

Check if a file exists in the project in WinRT

I have a WinRT Metro project which displays images based on a selected item. However, some of the images selected will not exist. What I want to be able to do is trap the case where they don't exist and display an alternative.
Here is my code so far:
internal string GetMyImage(string imageDescription)
{
string myImage = string.Format("Assets/MyImages/{0}.jpg", imageDescription.Replace(" ", ""));
// Need to check here if the above asset actually exists
return myImage;
}
Example calls:
GetMyImage("First Picture");
GetMyImage("Second Picture");
So Assets/MyImages/SecondPicture.jpg exists, but Assets/MyImages/FirstPicture.jpg does not.
At first I thought of using the WinRT equivalent of File.Exists(), but there doesn't appear to be one. Without having to go to the extent of trying to open the file and catching an error, can I simply check if either the file exists, or the file exists in the project?
You could use GetFilesAsync from here to enumerate the existing files. This seems to make sense considering you have multiple files which might not exist.
Gets a list of all files in the current folder and its sub-folders. Files are filtered and sorted based on the specified CommonFileQuery.
var folder = await StorageFolder.GetFolderFromPathAsync("Assets/MyImages/");
var files = await folder.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == "fileName");
if (file != null)
{
//do stuff
}
Edit:
As #Filip Skakun pointed out, the resource manager has a resource mapping on which you can call ContainsKey which has the benefit of checking for qualified resources as well (i.e. localized, scaled etc).
Edit 2:
Windows 8.1 introduced a new method for getting files and folders:
var result = await ApplicationData.Current.LocalFolder.TryGetItemAsync("fileName") as IStorageFile;
if (result != null)
//file exists
else
//file doesn't exist
There's two ways you can handle it.
1) Catch the FileNotFoundException when trying to get the file:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
try
{
// Don't forget to decorate your method or event with async when using await
var file = await installedLocation.GetFileAsync(fileName);
// Exception wasn't raised, therefore the file exists
System.Diagnostics.Debug.WriteLine("We have the file!");
}
catch (System.IO.FileNotFoundException fileNotFoundEx)
{
System.Diagnostics.Debug.WriteLine("File doesn't exist. Use default.");
}
catch (Exception ex)
{
// Handle unknown error
}
2) as mydogisbox recommends, using LINQ. Although the method I tested is slightly different:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
var files = await installedLocation.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == fileName);
if (file != null)
{
System.Diagnostics.Debug.WriteLine("We have the file!");
}
else
{
System.Diagnostics.Debug.WriteLine("No File. Use default.");
}
BitmapImage has an ImageFailed event that fires if the image can't be loaded. This would let you try to load the original image, and then react if it's not there.
Of course, this requires that you instantiate the BitmapImage yourself, rather than just build the Uri.
Sample checking for resource availability for c++ /cx (tested with Windows Phone 8.1):
std::wstring resPath = L"Img/my.bmp";
std::wstring resKey = L"Files/" + resPath;
bool exists = Windows::ApplicationModel::Resources::Core::ResourceManager::Current->MainResourceMap->HasKey(ref new Platform::String(resKey.c_str()));

Content type not working in struts

This is written in my validate method. The check for size and empty upload is working but content type is not, am i missing something ?
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if(file1.getFileSize()==0)
{
errors.add("file1", new ActionMessage("error.file.required"));
}
else if(!file1.getContentType().equals("audio/mpeg"));
{
errors.add("file1",new ActionMessage("error.file.type"));
}
if(file1.getFileSize()>51200)
{
errors.add("file1",new ActionMessage("error.file.size"));
}
return errors;
I think your else if condition statement is missing because of ";" sign as the following :
else if(!file1.getContentType().equals("audio/mpeg"));
It should be as the following :
else if(!file1.getContentType().equals("audio/mpeg"))
done with:
else if(!file1.getContentType().equals("audio/mp3")) { ---- }
I checked the type of the the fileuploaded by: String ctype = file1.getContentType(); without puting any validation (i.e upload any file) and printed it on the jsp page. From there i came to know that its audio/mp3. Now all validations are working. /

add custom 404 pages in umbraco 4.7

I'm trying to add custom 404 pages into umbraco
even though I got them working in several projects, in this umbraco 4.7 it does not work.
so, what do I have,
multi site each with a few languages.
my umbracoSettings contains this:
<errors>
<error404>
<errorPage culture="default">1842</errorPage>
<errorPage culture="en-GB">1842</errorPage>
<errorPage culture="nl-BE">1843</errorPage>
<errorPage culture="fr-BE">1844</errorPage>
</error404>
</errors>
just as it is in other projects
though i keep getting the IIS 404 page.
so, i tried the solution in this topic
both the passThrough and the custom solution don't seem to work
the passThrough gives this:
Page not found No umbraco document matches the url
'http://www.mysite.be/en/facebook'
umbraco tried this to match it using this xpath
query'/domainprefixes-are-used-so-i-do-not-work')
This page can be replaced with a custom 404 page by adding the id of
the umbraco document to show as 404 page in the
/config/umbracoSettings.config file. Just add the id to the
'/settings/content/errors/error404' element.
For more information, visit information about custom 404 on the
umbraco website.
and custom gives this result:
Page not found No umbraco document matches the url
'http://solex.d01-win-dev.be/non-existing-page.aspx?404;http://solex.d01-win-dev.be:80/en/facebook'
umbraco tried this to match it using this xpath
query'/domainprefixes-are-used-so-i-do-not-work')
This page can be replaced with a custom 404 page by adding the id of
the umbraco document to show as 404 page in the
/config/umbracoSettings.config file. Just add the id to the
'/settings/content/errors/error404' element.
For more information, visit information about custom 404 on the umbraco website.
it looks to me as if he does not go towards the umbracoSettings to fetch my error404 mappings.
did something change in 4.7 that you need to activate custom error pages trough a web.config key?
for those people interested, or who might ever have the same issues
it was solved without any of those web.config changes.
but by using a custom 404 handler we added to the 404handlers.config
like this
<notFound assembly="ProjectLibrary" type="Custom404"/>
and still adding the error pages in the umbracoSettings.config
like this
<errors>
<error404>
<errorPage culture="default">1842</errorPage>
<errorPage culture="en-GB">1842</errorPage>
<errorPage culture="nl-BE">1843</errorPage>
<errorPage culture="fr-BE">1844</errorPage>
</error404>
</errors>
the custom handler looks like this:
public class Custom404 : INotFoundHandler
{
#region INotFoundHandler Members
private int _redirectID = -1;
public bool CacheUrl
{
get { return false; }
}
public bool Execute(string url)
{
//Variable for keeping track whether the handling of the request was successful
bool _success = false;
XmlNode error404Node = umbraco.UmbracoSettings.GetKeyAsNode("/settings/content/errors/error404");
// _redirectID =;
XmlNode cultureErrorNode;
try
{
HttpContext.Current.Trace.Write("test", HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/" + url);
string sDomein = findDomein(HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/" + url);
HttpContext.Current.Trace.Write("test", sDomein);
if (Domain.Exists(sDomein))
{
Domain d = Domain.GetDomain(sDomein);
// test if a 404 page exists with current culture
HttpContext.Current.Trace.Write("test", d.Language.CultureAlias);
cultureErrorNode = error404Node.SelectSingleNode(String.Format("errorPage [#culture = '{0}']", d.Language.CultureAlias));
if (cultureErrorNode != null && cultureErrorNode.FirstChild != null)
{
_redirectID = int.Parse(cultureErrorNode.FirstChild.Value);
}
else
{
cultureErrorNode = error404Node.SelectSingleNode("errorPage [#culture = 'default']");
if (cultureErrorNode != null && cultureErrorNode.FirstChild != null)
_redirectID = int.Parse(cultureErrorNode.FirstChild.Value);
}
}
else
{
cultureErrorNode = error404Node.SelectSingleNode("errorPage [#culture = 'default']");
if (cultureErrorNode != null && cultureErrorNode.FirstChild != null)
_redirectID = int.Parse(cultureErrorNode.FirstChild.Value);
}
}
catch
{
cultureErrorNode = error404Node.SelectSingleNode("errorPage [#culture = 'default']");
if (cultureErrorNode != null && cultureErrorNode.FirstChild != null)
_redirectID = int.Parse(cultureErrorNode.FirstChild.Value);
}
_success = true;
return _success;
}
public string findDomein(string sUrl)
{
if (sUrl.Contains("/"))
{
if (Domain.Exists(sUrl))
{
return sUrl;
}
else
{
sUrl = sUrl.Substring(0, sUrl.LastIndexOf("/"));
return findDomein(sUrl);
}
}
else
{
return sUrl;
}
}
public int redirectID
{
get
{ return _redirectID; }
}
#endregion
}
hope any of you can use it whenever you find yourself in the same situation.