jQuery validation in JSP - java

For my servlet Java program, I have used JSP and used jQuery client side validation for .xls for uploading a file. It's running successfully for all the user but one of our users is getting problems while uploading a .xls file. The program is showing an alert message and does not allow to upload a file. We also checked browser compatibility.
Questions:
What would be the reason?
Is it adding extra char with extension .xls? If yes, then what would be solution?
Is it a network issue? If yes, then what would be solution?
This is the code:
function dosearch(){
var reportFile = document.form1.reportFile.value;
if(reportFile==null || reportFile==''){
$("#span_filename").show();
if(!window.console)
{
window.console = {log: function(){}};
}else{
console.log("file name is not valid"+reportFile);
}
}else if(reportFile.substring(reportFile.indexOf(".")+1)!="xls"){
alert("Please make sure the uploaded file is an excel file");
if(!window.console)
{
window.console = {log: function(){}};
}else{
console.log("invalid file format or might be its adding extra name or extension name with file , "+reportFile);
}
}else if(confirm('Do you want to upload now?')){
form1.bt1.disabled=true;
$("#pro").show();
document.form1.action='catalog?module=PayrollResultUpload&cmd=doUpload';
document.form1.submit();
}

Well, seems that you are only validating xls extension. To improve this, for example to check xlsx extension, I suggest you to make a regex pattern check.
Change the line:
}else if(reportFile.substring(reportFile.indexOf(".")+1)!="xls"){
with this other version:
}else if(reportFile.substring(reportFile.indexOf(".")+1).match(/^xls.?$/i)){
This will check if there is a character at the end of the extension.
Regarding network issues... You can check the connection with an AJAX worker polling connection regularly and advising the user if there is no connection, but I think its too complicated for this case. Better tell the user to try to upload later ;)

I have done some RND test in browser console there, I have got the exact problem , its getting extra dot(.) before the file but that dot(.) was not in the file it was in the client systems folder structure i.e. C:\ads.test\file\FILE_NAME_HERE.xls . So, I have used lastIndexOf() method instead of indexOf() method . now it running fine without any problem.
#Thiamath , gratitude for your valuable information for me,and be in a part for this question.

Related

Mule originalFilename is null

I am creating a process using Mule 3.4.1 which after processing a file it writes out the file with a specific filename.
The input filename is: MMDDYYYY_sys_newhires.csv
The processed filename is: MMDDYYYY_sys_newhires_NNN.csv
The code that i am using is below:
#[filename = message.inboundProperties.originalFilename;
filename= com.cfa.apps.icims.mule.CounterSingleton.getInstance().getCount()
+ filename.substring(0,filename.length() -1 -4) + ".csv";
filename]
The problem exists in the first line. message.inboundProperties.originalFilename.
I have tried a number of different combinations
message.inboundProperties.originalFilename
message.inboundProperties['originalFilename']
message.inboundProperties.originalFileName
message.inboundProperties['originalFileName']
message.inboundProperties.sourceFilename
message.inboundProperties['sourceFilename']
message.inboundProperties.sourceFileName
message.inboundProperties['sourceFileName']
Now I have also tried nesting the #[header:originalFilename], this works by itself, but you can't nest the expression within the code at least as far as I know.
Any help?
UPDATE: I am using the inbound file transport
Since you don't show the endpoint configuration, I'm going to assume that this is happening with a file inbound endpoint.
For a reason that goes beyond imagination, the file message receiver behind the inbound endpoint puts the originalFilename property in the outbound scope when evaluating the expression to generate the archived file name.
So use: message.outboundProperties.originalFilename
I have tested this mel EXPRESSION in ESB 3.7.1 and it is working fine!!
message.inboundProperties.originalFilename=='firstfile.txt'

Failing for Larger Input Files Only: FileServiceFactory getBlobKey throws IllegalArgumentException

I have a Google App Engine App that converts CSV to XML files. It works fine for small XML inputs, but refuses to finalize the file for larger inputed XML. The XML is read from, and the resulting csv files are written to, many times before finalization, over a long-running (multi-day duration) task. My problem is different than this FileServiceFactory getBlobKey throws IllegalArgumentException , since my code works fine both in production and development with small input files. So it's not that I'm neglecting to write to the file before closing/finalizing. However, when I attempt to read from a larger XML file. The input XML file is ~150MB, and the resulting set of 5 CSV files is each much smaller (perhaps 10MB each). I persisted the file urls for the new csv files, and even tried to close them with some static code, but I just reproduce the same error, which is
java.lang.IllegalArgumentException: creation_handle: String properties must be 500 characters or less. Instead, use com.google.appengine.api.datastore.Text, which can store strings of any length.
at com.google.appengine.api.datastore.DataTypeUtils.checkSupportedSingleValue(DataTypeUtils.java:242)
at com.google.appengine.api.datastore.DataTypeUtils.checkSupportedValue(DataTypeUtils.java:207)
at com.google.appengine.api.datastore.DataTypeUtils.checkSupportedValue(DataTypeUtils.java:173)
at com.google.appengine.api.datastore.Query$FilterPredicate.<init>(Query.java:900)
at com.google.appengine.api.datastore.Query$FilterOperator.of(Query.java:75)
at com.google.appengine.api.datastore.Query.addFilter(Query.java:351)
at com.google.appengine.api.files.FileServiceImpl.getBlobKey(FileServiceImpl.java:329)
But I know that it's not a String/Text data type issue, since I am already using similar length file service urls for the previous successful attempts with smaller files. It also wasn't an issue for the other stackoverflow post I linked above. I also tried putting one last meaningless write before finalizing, just in case it would help as it did for the other post, but it made no difference. So there's really no way for me to debug this... Here is my file closing code that is not working. It's pretty similar to the Google how-to example at http://developers.google.com/appengine/docs/java/blobstore/overview#Writing_Files_to_the_Blobstore .
log.info("closing out file 1");
try {
//locked set to true
FileWriteChannel fwc1 = fileService.openWriteChannel(csvFile1, true);
fwc1.closeFinally();
} catch (IOException ioe) {ioe.printStackTrace();}
// You can't get the blob key until the file is finalized
BlobKey blobKeyCSV1 = fileService.getBlobKey(csvFile1);
log.info("csv blob storage key is:" + blobKeyCSV1.getKeyString());
csvUrls[i-1] = blobKeyCSV1.getKeyString();
break;
At this point, I just want to finalize my new blob files for which I have the urls, but cannot. How can I get around this issue, and also, what may be the cause? Again, my code works for small files (~60 kB), but the input file of ~150MB fails). Thank you for any advice on what is causing this or how to get around it! Also, how long will my unfinalized files stick around for, before being deleted?
This issue was a bug in the Java MapReduce and Files API, which was recently fixed by Google. Read announcement here: groups.google.com/forum/#!topic/google-appengine/NmjYYLuSizo

Handling missing file download links without request on the same page

What's the best practice to handle clicks on file download links when the respective files are missing?
The specific situation is that attachment entities exist in the DB, pointing to file names only and the file storage path can be configured individually/separately. This is for a legacy app and has to be supported.
Is this possible? How does such code look like? I tried
if ( file.canRead() )
{
byte[] data = FileUtils.readFileToByteArray( file );
// goes to code like here: http://balusc.blogspot.de/2006/05/pdf-handling.html
downloadFile( attachment.getFileName(), data );
}
else
{
this.log.errorv( "Attachment {0} not found in configured storage path {1}", file, this.storagePath );
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage( null,
new FacesMessage( FacesMessage.SEVERITY_ERROR, "Failed.",
"Downlosding file " + file + " failed! File doesn't exist in the configured storage path " + this.storagePath ) );
// ???
facesContext.responseComplete();
}
but this results in
XML-Verarbeitungsfehler: Kein Element gefunden
Adresse: https://localhost:8181/cmc-compliance/view/prototype/collisionManager.xhtml
Zeile Nr. 1, Spalte 1:
(<rant>OMG, I HATE... eh DISLIKE int18ned error messages... someone should get rid of the person who thought this is a good idea... </rant>)
OK, the above means something like "XML processing error: no element found + Line 1, Column 1"
My code is obviously not the right way to do it...
I'm using the JSF code in a datatable:
<h:commandLink action="#{attachmentManager.downloadAttachment(att)}">
<h:graphicImage library="images/icons" name="page_white.png" />
<h:outputText value="#{att.fileName}" />
</h:commandLink>
What I'd ideally want is to display a JSF message (or PrimeFaces growl) and then leave the page as is, that is without issuing a full request on the same page again.
How do you do this?
With facesContext.responseComplete(); you're basically preventing JSF from rendering the response. Hence the client retrieves a completely empty response. The webbrowser is trying to make its best out of it. All the webbrowser knows is that the requested resource has a .xhtml file extension. So the webbrowser presumes that it's some XML content. Then the webbrowser tries to parse the empty response as XML. But it failed miserably with the given error as there are no XML elements at all. A XML well formed document is namely required to have at least one root XML element.
Remove the facesContext.responseComplete(); line and just return from the method the usual way. You should only use facesContext.responseComplete(); when you've already written to the response yourself, such as providing a file download in this particular case.
OMG, I HATE int18ned error messages... someone should get rid of the person who thought this is a good idea...
Just change the operating system platform default locale accordingly in platform specific settings. In case of Windows, a related answer with a screenshot can be found here: Getting OS language in java. If the program itself (e.g. Firefox/Chrome) has also some locale-related settings as well, you might want to change it in the program itself as well.

Java/ImageIO Validate format before reading the entire file?

I'm developing a Web application that will let users upload images.
My concern is the file´s size, specially if they are invalid formats.
I'm wondering if there´s a way in java (or a third party library) to check the allowed files formats (jpg, gif and png) before reading the entire file.
If you wish to support only a few types of images you can start by (up)loading the image and at some point use the first few bytes to check wether you wish to continue the upload.
Quite a lot of image formats can be recognized by the first few bytes, the magic number. If the number matches you don't know whether the file is valid of course, but it may be used to match extension and magic number to prevent is really does not correspond at all.
Have a look at this page to check out some Java which checks mime-types. Do read the docs or source to check whether any given method requires the entire file, or can operate on the first few bytes. I've not used those libraries :)
Also check out this page which also lists some java libraries, and some papers on which detection is based.
Don't forget to put in some feedback if you managed to find something you like!
You don't need 3rd party libraries. The code you have to write is simple.
At the point you are handling your uploads, filter the files by their extension. This isn't perfect, but will account for most of the cases.
However, this would mean files are already uploaded to the server. You can use a bit of javascript on the client-side to perform the same operation - check whether the value of the file-upload component contains an allowed file type - .jpg, .png, etc.
function extensionsOkay(fval) {
var extension = new Array();
extension[0] = ".png";
extension[1] = ".gif";
extension[2] = ".jpg";
extension[3] = ".jpeg";
extension[4] = ".bmp";
// No other customization needed.
var thisext = fval.substr(fval.lastIndexOf('.')).toLowerCase();
for(var i = 0; i < extension.length; i++) {
if(thisext == extension[i]) {
$('#support-documents').hide();
return true; }
}
// show client side error message
$('#span.failed').show();
return false;
}

Running a JavaScript command from MATLAB to fetch a PDF file

I'm currently writing some MATLAB code to interact with my company's internal reports database. So far I can access the HTML abstract page using code which looks like this:
import com.mathworks.mde.desk.*;
wb=com.mathworks.mde.webbrowser.WebBrowser.createBrowser;
wb.setCurrentLocation(ReportURL(8:end));
pause(1);
s={};
while isempty(s)
s=char(wb.getHtmlText);
pause(.1);
end
desk=MLDesktop.getInstance;
desk.removeClient(wb);
I can extract out various bits of information from the HTML text which ends up in the variable s, however the PDF of the report is accessed via what I believe is a JavaScript command (onClick="gotoFulltext('','[Report Number]')").
Any ideas as to how I execute this JavaScript command and get the contents of the PDF file into a MATLAB variable?
(MATLAB sits on top of Java, so I believe a Java solution would work...)
I think you should take a look at the JavaScript that is being called and see what the final request to the webserver looks like.
You can do this quite easily in Firefox using the FireBug plugin.
https://addons.mozilla.org/en-US/firefox/addon/1843
Once you have found the real server request then you can just request this URL or post to this URL instead of trying to run the JavaScript.
Once you have gotten the correct URL (a la the answer from pjp), your next problem is to "get the contents of the PDF file into a MATLAB variable". Whether or not this is possible may depend on what you mean by "contents"...
If you want to get the raw data in the PDF file, I don't think there is a way currently to do this in MATLAB. The URLREAD function was the first thing I thought of to read content from a URL into a string, but it has this note in the documentation:
s = urlread('url') reads the content
at a URL into the string s. If the
server returns binary data, s will
be unreadable.
Indeed, if you try to read a PDF as in the following example, s contains some text intermingled with mostly garbage:
s = urlread('http://samplepdf.com/sample.pdf');
If you want to get the text from the PDF file, you have some options. First, you can use URLWRITE to save the contents of the URL to a file:
urlwrite('http://samplepdf.com/sample.pdf','temp.pdf');
Then you should be able to use one of two submissions on The MathWorks File Exchange to extract the text from the PDF:
Extract text from a PDF document by Dimitri Shvorob
PDF Reader by Tom Gaudette
If you simply want to view the PDF, you can just open it in Adobe Acrobat with the OPEN function:
open('temp.pdf');
wb=com.mathworks.mde.webbrowser.WebBrowser.createBrowser;
wb.executeScript('javascript:alert(''Some code from a link'')');
desk=com.mathworks.mde.desk.MLDesktop.getInstance;
desk.removeClient(wb);

Categories

Resources