File Upload in fire fox - java

Iam not able to upload files in FireFox and safari but iam able to do it successfully in explorer.
When i tried to debug i found out that in case of IE the upload browser is giving the entire file as eg C:\Documents and Settings\jjayashree\My Documents\price.csv
but where as in FF and safari the upload widget is just giving the file name with no extension.
previously code was like this
if (fileName.contains("\")) {
index = fileName.lastIndexOf("\");
}
if (this.fileName != null && this.fileName.trim().length() > 0 && index >= 0) {
this.fileName = this.fileName.substring(index + 1, this.fileName.length());
int dotPosition = fileName.lastIndexOf('.');
String extension = fileName.substring(dotPosition + 1, fileName.length());
try {
if (profileType.equalsIgnoreCase("sampleProfile")) {
if (extension.equalsIgnoreCase("csv")) {
//fileNameTextBox.setText(this.fileName);
this.form.submit();
} else {
new CustomDialogBox(Nexus.INFO_MESSAGE, MessageConstants.SPECIFY_FILE_NAME_MSG).show();
}
}
} catch (Exception e) {
Window.alert("SPECIFY_VALID_FILE_NAME_MSG");
}
} else {
Window.alert("SPECIFY_A_FILE_MSG");
}
i changed it as
if (this.fileName != null && this.fileName.trim().length() > 0) {
this.fileName = this.fileName.substring(this.fileName.lastIndexOf("\") + 1, this.fileName.length());
}
i found it working but when the same is deployed in linux iam getting an error
I also hav a doubt becos in the doPost of servlet iam using fileName.replace("\", "/");
is this the problem. . How wil mozilla encounter this fileName.replace() wil it just see and find nothing can be replced and go or wil it throw any kind of Exception

Maybe try gwtupload? It simplifies file loading to one function call, and handles all the backend for you. It's a little complicated to get working but there's a tutorial on the site on how to do it.
http://code.google.com/p/gwtupload/

Related

getting an java/tomcat exception only on 1 or 4 servers

i have this java web application running on 4 servers.
The newest server ( just setting up ) is failing with the error
"java.lang.NoSuchMethodError: org.htmlparser.lexer.Lexer.parseCDATA()Lorg/htmlparser/Node"
when running the code below.
I have 1 server is running locally on my mac.
2 servers are running Centos 6.10 / java 1.8.0_242 / tomcat-8.5.54
The newest server (the one that is failing ) is running Centos 6.10 / java 1.8.0_242 / tomcat-8.5.54
i have copied all the jars from the working Centos server to the broke one
I am at a loss. Would love to hear some ideas on how to debug/resolve this....
The Code running is pretty simple
Another part that also confuses me, is if the jar was not found wouldnt Parser.createParser blow up and i have added debug code to make sure parser_c is not null
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.ParserException;
public class SignatureTools {
public static String getURLFromSignature(String signature) throws ParserException {
System.out.println("[getURLFromSignature]");
if ( signature == null ){ return null;}
Parser parser_c = Parser.createParser(signature, null);
Node nodes_c[] = parser_c.extractAllNodesThatAre(LinkTag.class);
String mkURL = null;
for (Node node : nodes_c) {
if (node != null && node instanceof LinkTag && ((LinkTag) node).getAttribute("href") != null) {
String href = ((LinkTag) node).getAttribute("href");
if ( href.contains("https://www.thedomain.com") ){
mkURL = href;
}
}
}
return URL;
}
}
found the problem..
i used this bit of code and found that Lexer was being loaded from a different jar instead of htmllexer.jar
Lexer lexer = new Lexer();
try {
System.out.println( "Lexer---->" + new File(Lexer.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath());
} catch (URISyntaxException e) {
e.printStackTrace();
}

Getting PhantomJS to work with a java application

I am testing around with PhantomJS a bit.
But I am not sure how to make it work with a java application, th examples I have found are mostly just against files or sites.
So this is what I have now.
var page = require('webpage').create();
address = "http://localhost:8080/logon.do";
page.open(address, function(status) {
wait(5000);
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementsByTagName('html')[0].outerHTML;
});
console.log(ua);
}
phantom.exit();
});
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
Now I know this wait is ugly but it is not important right now.
The server is running and if I go to the url I get a log in page.
I was expecting this log in page to be the output of console.log(ua);
Instead I get the output:
<-html><-head><-/head><-body><-/body><-/html>
What am I missing?
OK this turned out to be very secific for our application so lets close this.
Sascha, yes it is the script called by phantomjs which in turn

Cannot find a image file that exists in java

I have written a function which takes in a BufferedImage and compares it to a pre-existing image in my hard drive checking if they are same or not.
public boolean checkIfSimilarImages(BufferedImage imgA, File B) {
DataBuffer imgAdata = imgA.getData().getDataBuffer();
int sizeA = imgAdata.getSize();
BufferedImage imgB = null;
try {
imgB = ImageIO.read(B);
} catch (IOException ex) {
Logger.getLogger(SupportClass.class.getName()).log(Level.SEVERE, null, ex);
}
DataBuffer imgBdata = imgB.getData().getDataBuffer();
int sizeB = imgBdata.getSize();
if(sizeA == sizeB) {
for(int i = 0; i < sizeA; i++) {
if (imgAdata.getElem(i) != imgBdata.getElem(i)) {
return false;
}
}
}
return true;
}
This throws IOException "Cant read input file". Idk why this is happening. I am calling the function like this...
while(support.checkIfSimilarImages(currentDisplay, new File(pathToOriginalImage)) == false) {
System.out.println("Executing while-loop!");
bot.delay(3000);
currentDisplay = bot.createScreenCapture(captureArea);
}
where,
String pathToOriginalImage = "‪‪‪‪C:\\Users\\Chandrachur\\Desktop\\Home.jpg";
I can see that the path is valid. But as I am testing it for File.exists() or File.canRead() or File.absoluteFile().exists() inside the checkIfSimilarImages function and everything is returning false.
I have researched my question here and tried out these suggestions:
It is not only for this location, I have tried a variety of other locations but in vain. Also it is not a problem where I have hidden file extensions and the actual file might be Home.jpg.jpg .
The only thing that might be is that permissions might be different. I dont really know how to verify this, but there is no reason it should have some permission which is not readable by java. It is just another normal jpg file.
Can it be because I am passing the file object reference into a function so in this process somehow the reference is getting modified or something. I just dont know. I am running out of possibilities to test for...
The whole stack trace is as follows:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at battlesbot.SupportClass.checkIfSimilarImages(SupportClass.java:77)
at battlesbot.AutomatedActions.reachHomeScreen(AutomatedActions.java:72)
at battlesbot.BattlesBot.main(BattlesBot.java:22)
Exception in thread "main" java.lang.NullPointerException
at battlesbot.SupportClass.checkIfSimilarImages(SupportClass.java:81)
at battlesbot.AutomatedActions.reachHomeScreen(AutomatedActions.java:72)
at battlesbot.BattlesBot.main(BattlesBot.java:22)
C:\Users\Chandrachur\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 11 seconds)
I am on Windows 10, IDE is NetBeans.
UPDATE:
Huge thanks to #k5_ . He told me to paste this in path and it worked.
"C:/Users/Chandrachur/Desktop/Home.jpg";
It seems some invisible characters were in the path. But I still don't understand what that means.
Usually this kind of problem lies with access problem or typos in the filename.
In this case there were some invisible unicode characters x202A in the filename. The windows dialog box, the file path was copied from, uses them for direction of writing (left to right).
One way of displaying them would be this loop, it has 4 invisible characters at the start of the String. You would also see them in a debugger.
String x = "‪‪‪‪C:\\Users\\Chandrachur\\Desktop\\Home.jpg";
for(char c : x.toCharArray()) {
System.out.println( c + " " + (int) c);
}

Error in using usb4java

followed the instruction as stated here . Added the properties file in my root project and libraries on the project class path. When i run the project, it returns.
Exception in thread "main" javax.usb.UsbPlatformException: Class org.usb4java.javax.Services does not have the needed constructor
at javax.usb.UsbHostManager.initialize(UsbHostManager.java:46)
at javax.usb.UsbHostManager.getUsbServices(UsbHostManager.java:24)
at usbfinderdemo.UsbFinderDemo.main(UsbFinderDemo.java:30)
Don't know what might be wrong. Thinking i might not be using the right .jar file of usb4java, but i'm not certain yet as the code does not show any error at all.
Code Snippet
UsbServices services = UsbHostManager.getUsbServices();//the line that throws the error.
UsbHub rootHub = services.getRootUsbHub();
List<UsbDevice> devices = rootHub.getAttachedUsbDevices();
if (devices.size() > 0) {
System.out.println("USB devices found.");
} else {
System.out.println("No USB devices found.");
}
for (UsbDevice device : devices) {
System.out.println("\tProduct String " + device.getProductString());
System.out.println("\tManufacturer String " + device.getManufacturerString());
System.out.println("\tSerial Number " + device.getSerialNumberString());
}

File.createNewFile() randomly fails

I've build a simple test which creates and deletes a file (name does not change) in an infinite loop. The test does run for a couple of seconds (sometimes over 77,000 iterations!) and then fails with this exception:
Exception in thread "main" java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at DeleteTest.main(DeleteTest.java:11)
Here's the test logic:
final File f = new File(pathname);
while (true) {
final boolean create = f.createNewFile();
if (!create) {
System.out.println("crate failed");
} else {
final boolean delete = f.delete();
if (!delete) {
System.out.println("delete failed");
}
}
}
How is this possible? The delete call does not fail. It would tell. So delete always succeeds but createNewFile fails. This is what MSDN says about win32 api function DeleteFile:
The DeleteFile function marks a file for deletion on close. Therefore,
the file deletion does not occur until the last handle to the file is
closed. Subsequent calls to CreateFile to open the file fail with
ERROR_ACCESS_DENIED.
So createNewFile does not close the file? The openjdk source tells us that the file is closed:
JNIEXPORT jboolean JNICALL
Java_java_io_Win32FileSystem_createFileExclusively(JNIEnv *env, jclass cls,
jstring pathname)
{
jboolean rv = JNI_FALSE;
DWORD a;
WITH_PLATFORM_STRING(env, pathname, path) {
int orv;
int error;
JVM_NativePath((char *)path);
orv = JVM_Open(path, JVM_O_RDWR | JVM_O_CREAT | JVM_O_EXCL, 0666);
if (orv < 0) {
if (orv != JVM_EEXIST) {
error = GetLastError();
// If a directory by the named path already exists,
// return false (behavior of solaris and linux) instead of
// throwing an exception
a = GetFileAttributes(path);
if ((a == INVALID_FILE_ATTRIBUTES) ||
!(a & FILE_ATTRIBUTE_DIRECTORY)) {
SetLastError(error);
JNU_ThrowIOExceptionWithLastError(env, path);
}
}
} else {
JVM_Close(orv);
rv = JNI_TRUE;
}
} END_PLATFORM_STRING(env, path);
return rv;
}
Can anyone explain this behaviour?
I've found an explanation while writing the question. I still posted the question because I wanted to share what I learned.
My application is not the only process on the system accessing files. The Windows Search Index Service for example could open this file because it wants to add it to it's index. Or the windows Explorer if it is updating the view.
This issue reminds me a problem I experienced recently with the File.renameTo() method. It is (was?) due to this bug in the jvm :
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298
A weird workaround is to call System.gc() and to retry renaming the file again (and it works...).
Not sure it has a link with your issue, but it may be worth exploring...
Try this:
final File f = new File("file");
while (true) {
final boolean create = f.createNewFile();
if (!create) {
System.out.println("crate failed");
} else {
final boolean delete = f.delete();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("...");
}
if (!delete) {
System.out.println("delete failed");
}
}
}
In this way we ensure that the file is released by the delete before invoking createNewFile.

Categories

Resources