A question on downloading file via HtmlUnit - htmlunit

So here's the deal:
I am accessing some webpage(using HtmlUnit) on which there's a button. I programatically click that button,
When I click that button normally through the browser, I am given the chance to save a file on my hard drive.
The thing is, I want to be able to get that file programatically. and save it to a specific folder, if the file size is bigger than a specific number, the downloading should be stopped, Can this be done via HtmlUnit?
Thank you so much!

In my case the file I wanted to download was a text file and below is the code I used. Hope so it gives you an idea about what is to be done.
InputStream inputStream = new HttpWebConnection(client).getResponse(req).getContentAsStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF8");
String theString = writer.toString();
System.out.println(theString);

Short answer... no, this cannot be done.
There is a firefox/profile base way to partially do that.
And the workaround with getPageSource() for plain text files.
Otherwise... I'm looking for similar thing. Let you know if you find a better hack...

Related

How do I write to a file in Swfit2 from the Playground? [duplicate]

Files are not readable in Swift Playground.
How to make files readable?
Same code runs well on Xcode terminal app, but fails on Swift Playground.
Demo code below.
import Foundation
println("Hello, World!")
var fname:String = "/Users/holyfield/Desktop/com.apple.IconComposer.plist"
var fm:NSFileManager = NSFileManager.defaultManager()
if(fm.fileExistsAtPath(fname)){
println("File Exists")
if(fm.isReadableFileAtPath(fname)){
println("File is readable")
var fd:NSData? = NSData(contentsOfFile: fname)
println(fd?.length)
let pl = NSDictionary(contentsOfFile: fname)
println(pl?.count)
println(pl?.allKeys)
}else{
println("File is not readable")
}
}
else{
println("File does not exists")
}
Sample images:
I have to thank Nate Cook for first for his quick response and solid answer.
Just for case I share his answer from another post, which title is misleading.
See Nate's answer here: https://stackoverflow.com/a/26723557/2360439
Playgrounds are sandboxed, so you won't be able to just grab files from anywhere in your user folder. Here's how to add that file to your
playground to make it accessible:
Find your ".playground" file in the Finder Right click and choose "Show Package Contents"
You should see "timeline.xctimeline", "contents.xcplayground", and "section-1.swift"
Make a new folder called "Resources" if it doesn't exists yet.
Copy your files into Resources folder
Seems that there is no way to access files with Swift Playground outside of Playground sandbox. If you know how to access files outside of sandbox, you are welcome to share your solution!!
There are several ways to do load files into a Swift Playground. I'll highlight the Image Literal, File Menu and Context Menu techniques.
Image Literal technique
This is the easiest and COOLEST. You simply drag a file from anywhere on your machine into the code and assign it via a let or var statement. GIF here.
File Menu technique
Choose File -> Add Files to "MyProjectName"
See GIF of this here.
Context Menu technique
You can reveal the current playground in the Xcode (7.3.1) Project Navigator using the right-click menu. Upon revealing the current playground, you'll see a directory entitled Resources. Simply drag the file you want access to into that folder and watch the magic happen (given you've written the file access code).
Example resource loading code
Here's an example of doing this for showing an image:
let url: NSURL! = NSBundle.mainBundle().URLForResource("IMG_4099", withExtension: "JPG")
let imagePath = url.path
let image = UIImage(contentsOfFile: imagePath!)
let imageView = UIImageView.init(image: image)
I've produced an animated GIF that demonstrates this in action. Here's a screengrab from that:
Reading external code
If you want to add auxiliary code in addition to resources, use the Sources folder.
A note regarding the console
The console area of Xcode's Playground interface will show you that the UIImage instance is nil when you load an image file outside the sandbox. If you entered a path you know exists, but the image isn't showing, ensure the UIImage instance isn't printing as nil.
You also can create and use Shared Playground Data folder.
Just like that:
/Users/username/Documents/Shared Playground Data/file.txt
And any file located there becomes readable to any playground!

How to load an image in a QPixmap to display it in a QLabel

I've read multiple article on it and it still does'nt work!!
I know I'm doing it right, but for some reason it does'nt work.
Here's my code :
myIcon = new QLabel();
QPixmap myPixmapForNow;
if(!myPixmapForNow.load(":/img/Interrogation.png")){
qWarning("Failed to load");
}
myIcon->setPixmap(myPixmapForNow);
It tells me that the file failed to load each time.
What i want to do with this is to display an image that will have a tooltip and explain what the button next to it does. Basicaly, I'm looking for a way to display an image that have a tooltip programmed in it.
I'm a beginner and honestly the concept of looking in folders is a bit abstract for me. If you have a blog or something to propose, i'll be willing to read it. I've been looking for one and I have'nt found any good one that explain the concept and how to do it.
If you have a solution for my problem please explain it. Nothing better than explanation :)
Thanks
Two things to do:
Check if QFile can open that resource and read it. Dump it out to a file on disk.
QFile fi(":/img/Interrogation.png");
QFile fo(QDir::homePath() + QDir::separator() + "Interrogation.png");
if (!fi.open(QIODevice::ReadOnly)) {
qWarning() << "Can't open the resource" << fi.fileName();
return;
}
if (!fo.open(QIODevice::WriteOnly)) {
qWarning() << "Can't open the output" << fo.fileName();
return;
}
fo.write(fi.readAll());
Check the format of whatever is dumped out to disk to ensure that it's a valid png file. You can open it in an image editor, for example - just be sure to verify that the extension agrees with the contents. A valid JPEG file with .png extension will fail to load.
Seems, I've reproduced your error. Probably, you are missed default prefix of resources that QtCreator usually sets up into "/new/prefix1/". This string prefix must exist due to access resources. Try to modify your code within following way:
if(!myPixmapForNow.load(":/new/prefix1/img/Interrogation.png")){
Or, you need to discover your resource file to find out proper prefix string. If you had already modified prefix string then modify your code correspondently.

How to create a generic file selection dialog in QT4 for Windows

I have been searching for clues on this issue for some time now, with no results. So, here goes...
I have an application that I want to have a simple button to open a file dialog window. There are other buttons on the main window that will read or create/write the file (after doing the appropriate checks for the function selected). I used to use the QFileDialog::getSaveFileName() function without issues, but with Windows 7, this fails if the file exists AND is read-only. I switched to the getOpenFileName() to get around this issue, but now the file dialog fails if the user tries to select a non-existent file (irrelevant on a save operation).
Is there a way to add a "Create New File" icon to the file dialog, or add it to the right-click menu within the file dialog window? I would really hate to have to rewrite the app just because of (yet another) Windows behavior change.
QFileDialog::getOpenFileName() should only be used for opening existing files. If you type in a name of a file that doesn't exist and the system complains, this is proper behaviour. It's correctly telling you that you can't open a file that doesn't exist.
If you want to write to an existing file or create a new file, you should be using QFileDialog::getSaveFileName()
If you're trying to write to an existing file that is marked as Read-Only in the operating system and you get an error saying that the file is Read-Only, then the error is correct. You should not be allowed to write to a read-only file, that's just what Read-Only means.
From what you've explained, there are no errors here. Everything's happening as it should be. If you're trying to force the system to do something different, don't. You should rather try and think of doing things a different way.
Ok, since this was never really answered here, and I have since figured out a solution, I thought I would update this with the code snippet I am using.
void MainWindow::on_tbBrowse_clicked()
{
// Use the location of already entered file
QString fileLocation = leFile->text();
QFileInfo fileinfo(fileLocation);
// See if there is a user-defined file extension.
QString fileType = qgetenv("DiskImagerFiles");
if (fileType.length() && !fileType.endsWith(";;"))
{
fileType.append(";;");
}
fileType.append(tr("Disk Images (*.img *.IMG);;*.*"));
// create a generic FileDialog
QFileDialog dialog(this, tr("Select a disk image"));
dialog.setNameFilter(fileType);
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setViewMode(QFileDialog::Detail);
dialog.setConfirmOverwrite(false);
if (fileinfo.exists())
{
dialog.selectFile(fileLocation);
}
else
{
dialog.setDirectory(myHomeDir);
}
if (dialog.exec())
{
// selectedFiles returns a QStringList - we just want 1 filename,
// so use the zero'th element from that list as the filename
fileLocation = (dialog.selectedFiles())[0];
if (!fileLocation.isNull())
{
leFile->setText(fileLocation);
QFileInfo newFileInfo(fileLocation);
myHomeDir = newFileInfo.absolutePath();
}
setReadWriteButtonState();
updateHashControls();
}
}
setReadWriteButtonState() will enable the buttons according to the file state:
if file is read-only, only Read button is enabled
if file doesn't exist, only Write button is enabled
The entire code is available for others to review at https://sourceforge.net/projects/win32diskimager/. I hope this helps the next person that is looking for a solution to this. Just please include attribution if you use our code.

How can you detect that a user dragged a folder (not a file) into their browser?

I know very well that you are not allowed to upload a whole folder via drag and drop. The problem is, how can I tell if someone tries to do it? If you drag a folder into the browser, it behaves exactly as if you dragged a file with some extension webkit doesn't know about, like '.sh'. How can you tell the difference?
I have tested this in Chrome and Safari and Firefox on Mac OS X and Windows. Depending on the browser and OS, I get slightly different results. Sometimes it succeeds in uploading a zero-byte file. Sometimes it uploads a picture of a folder. Sometimes it fails to upload anything.
event.dataTransfer.types and event.dataTransfer.items both lie and say the type is "File" or "file" respectively.
Firefox gives this list of types:
{"0":"application/x-moz-file","1":"text/x-moz-url","2":"text/plain","3":"Files"}
I found a way to do it. The information can be found in dataTransfer.items via getAsEntry, though it's a little different in different browsers. Also, this doesn't have a pointer back to the file you wanted, though you can figure it out based on the file name assuming you're not uploading two files with the same name at the same time. There's not really much to work with here, so this is the best I could do.
just_the_files = (dataTransfer) ->
real_files_set = {}
for item in dataTransfer.items
entry = item.getAsEntry?() or item.webkitGetAsEntry?() or item
if entry.isFile
real_files_set[entry.name] = true
(file for file in dataTransfer.files when file.name of real_files_set)
In FF there is a method for dataTransfer: mozGetDataAt(type, index), when I use type 'text/x-moz-url', it returns the file's path like 'files:///D:/abc/fileName'. And its funny that a folder/directive has a path with '/' at the end like 'files:///D:/abc/folder1/'. I wonder if it works in this situation?
actually when you drag a folder on to a browser, all of folders and files thats in the folder that you drag will be showed..
for example in chrome
it will show "Index of D:\my documents\Downloads\" and the name, size and the date you modifies the file...

How do I let the user copy arbitrary text?

I have an app, where I generate text (about 500 characters), and I would like the user to have some means of copying that text for use outside of the application.
I don't want to use any capabilities for this app (like web, or contacts).
Here's what I've tried (and why it's failed)
TextBox. IsReadOnly = true; SelectAll();
Can't SelectAll a read only text box
Turn off read only, hide the SIP
Can't hide the SIP on a (non-read-only) TextBox that the user is interacting with (I want to enable the user to copy, so needs to interact with the control)
allow edits, show sip, SelectAll()
The "copy" icon doesn't appear unless the user chose to select text
On selection changed (actually changed), SelectAll()
The "copy" icon doesn't appear unless the user selected the text? The copy icon appears erratically, nothing I would call an acceptable user experience.
So at this point, I'm quite far from what I want in a user experience, and I still don't have anything that works. Any suggestions?
Some other possible ways to answer my question include:
"How do I force the copy button to appear above text I programatically selected?"
"How do I change the selection behavior of a tap in a text box?"
Afaik there are some limitations to the Windows Phone 7 Clipboard:
Works only in TextBox and can only copy text upon users wish
Text is only kept until device gets locked. If your device gets locked, the clipboard will be wiped clean
Even if you try Clipboard.SetText Method, you will notice the SecurityException if you call this method without the users interaction. This is to keep the users data under control so that no rogue app can copy unrecognized Text.
But you could try Matt Laceys WP7Clipboard. It saves the clipboard content inside an image and can even copy bitmaps.
Try restyling the textbox as per http://mobileworld.appamundi.com/blogs/peterfoot/archive/2011/02/08/copyable-textblock-for-windows-phone.aspx
Here's what I eventually got mostly working
private void Export(StackPanel stacker)
{
var exportHeader = new TextBlock();
exportHeader.Text = "Export";
stacker.Children.Add(exportHeader);
var exportBox = new TextBox();
stacker.Children.Add(exportBox);
//exportBox.IsReadOnly = true; // hides SIP, but causes an exception with SelectAll() (pre-Mango, I haven't tried on Mango yet)
exportBox.FontSize = 1;
exportBox.Text = textToExport;
exportBox.GotFocus += new System.Windows.RoutedEventHandler((send, ev) =>
{
((TextBox)send).SelectAll();
});
exportBox.Focus();
}
Apparently, making the font size 1 makes the difference here, maybe because all of the text can appear on the screen at once? Who knows.
I accepted this answer, because no one else posted a better solution. I would appreciate a better solution. If you can get the SIP to go away, that would be awesome.

Resources