How to automate basic authentication chrome alert - java

Have tried several approached to handle it but none worked.
https://user:password#pageaddress.com - doesn't work, chrome launches controlled bu automates test software and authentication pop-up appears anyway.
Adding --disable-blink-features=BlockCredentialedSubresources to Chrome arg and repeat 1'st point - doesn't work, reason the same as in 1'st point.
driver.switchTo().alert.authenticateUsing(new UserAndPassword(user, password)) - here seems like driver doesn't see an alert, have impelented method that checks it and returns false:
private Alert alert;
public boolean isAlertPresent() {
try {
waitForTimeout(10, TimeUnit.SECONDS);
alert = driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}}
Triggering keyboard or mouse event via selenium Action() doesn't work too.
chromedriver 2.31
Google Chrome Version 61
Any other ideas ? Maybe some js script ?

I had something similar here.
you may not need the full Native Messaging API, though ...
This will all be JavaScript and will work for any browser-generated auth request (at least, it looks that way).
webRequest - chrome and firefox - has an anAuthRequired event.
You can hook into this with a listener then just pass in the credentials you need per some examples.
If you're wanting to just pass in user credentials that won't change, you'll want to use the synchronous method - it's much easier. This question may, indeed, be all you need.
If you're needing to pass in different credentials, you may well want to look into the asynchronous method, that's the one I had to use.
If you're using chrome, forget promises ... but Firefox should work with them.
Hope this helped!

Finally - I was able to do it by Robot Framework which is not a solution that I am proud of, but didn't have any other idea.
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
private Robot robot;
public void login(String login, String password) {
copyValueFromClipboardToInput(login);
getRobot().keyPress(KeyEvent.VK_TAB);
getRobot().keyRelease(KeyEvent.VK_TAB);
copyValueFromClipboardToInput(password);
getRobot().keyPress(KeyEvent.VK_ENTER);
getRobot().keyRelease(KeyEvent.VK_ENTER);
}
private void copyValueFromClipboardToInput(String value) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(value), null);
getRobot().keyPress(KeyEvent.VK_CONTROL);
getRobot().keyPress(KeyEvent.VK_V);
getRobot().keyRelease(KeyEvent.VK_V);
getRobot().keyRelease(KeyEvent.VK_CONTROL);
}
private Robot getRobot() {
if (robot == null) {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
return robot;
}

Related

When will the java.awt.Robot fail to click?

I use java.awt.Robot to perform some mouse behaviors on my PC. The code is simple like below:
import java.awt.Robot;
import java.awt.event.InputEvent;
public class RobotProxy {
public static void main(String[] args) {
// TODO Auto-generated method stub
RobotProxy robotProxy = new RobotProxy();
try {
robotProxy.foo();
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception there...");
}
}
public void foo() throws Exception{
Thread.sleep(3000);
Robot robot = new Robot();
robot.mouseMove(501, 296);
leftClick(robot);
robot.mouseMove(505, 296);
leftClick(robot);
robot.mouseMove(509, 296);
leftClick(robot);
}
public void leftClick(Robot robot) throws Exception{
Thread.sleep(1000);
System.out.println("before Click...");
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
System.out.println("after Click...");
}
}
You can find that I use the combination of java.awt.Robot.mousePress(InputEvent.Button1_MASK) and java.awt.Robot.mouseRelease(InputEvent.Button1_MASK) to perform the mouse left click behavior.
It works fine at most time but fails sometimes. For example, the left click behavior for a kind of software's check box will fail. I can make sure I send the click command to java.awt.Robot but just nothing happens. What's more incredible is that java.awt.Robot.mouseMove(int x, int y) still works in that situation.
PC's OS is Windows8.1
The software is not market available and it's just a Windows native app written by cpp. The button on the software can be clicked but not for check box.
If the situation makes you confused, pls just tell me when will the java.awt.Robot fail to click. Thanks for your help in advance.
The problem is there is no delay between the robot.mousePress and robot.mouseRelease commands.
Here is an example of what you could add in between the two to fix the issue
Thread.sleep(100); a delay for 100ms. about as fast as you can hear, click click

Java SystemTray icon does not always work

I need your help please: I'm working on a little Java application (Java version 7) which has to be minimized into the system tray.
I'm using Class SystemTray, with SystemTray.isSupported(), then
SystemTray systemTray = SystemTray.getSystemTray();
ImageIcon icon = new javax.swing.ImageIcon(getClass().getResource("icon.png"));
[...]
systemTray.add(trayIcon);
(With popup of course)
On Windows, it's working great. On XFCE, Xubuntu, no problem, icon is working with popup. However on KDE and Gnome shell... it doesn't work.
KDE (4.14.1)
(Qt: 4.8.6 Tools Plasma: 4.11.12)
SystemTray.isSupported() = true and when the program arrived at the line:
systemTray.add(trayIcon); An exception is caught:
Error during Tray process:
java.awt.AWTException: TrayIcon couldn't be displayed.
Thereby the icon is white, and doesn't work when user clicks on it, no popup.
Gnome Shell (3.12.2)
SystemTray.isSupported() = true, the icon is located on notification area at the bottom, but mouse events don't work...
To fix these problem, I thought SWT could be a good idea. But when I implemented it (last version), I've got this warning:
WARNING **: Couldn't connect to accessibility bus: Failed to connect
to socket /tmp/[...]
And it doesn't work...
Edit: not anymore, I can fix the problem of SWT with an external class. The warning is not caused by SWT, but environment system probably (I had the same warning with other applications in the terminal).
So now, what can I do?
I think to check environment system with System.getenv("XDG_CURRENT_DESKTOP") & System.getenv("GDMSESSION") and then enable or disable system tray if it is KDE or Gnome 3... but this solution is not really good because of it is a local solution for multi-platform (in function of OS I mean), and not a global solution (one method for all OS)...
So, other idea? I don't know... is there a way to define an embedded JWindow into the system tray?
I have run up against this problem myself, and as I recall I ran up against a brick wall in sorting it out with a legitimate solution. I traced the problem to a call to the TrayIcon.addNotify() method randomly failing. I seem to recall this was because of a race condition in the internals where a call to the X11 system was taking too long to complete so the java side was giving up.
But if you have a ninja PC with a decent graphics card you would probably never meet this situation, which is probably why it hasn't been fixed yet. My dev machine is on the slow side so it was happening to me about 50% of the time.
I did hack a quick and dirty solution together, which involves trying to call addNotify repeatedly (with a pause inbetween each attempt) until it succeeds (or has failed a maximum number of times). Unfortunately the only way to do this was via reflection as the addNotify method is package-private.
Code follows:
public class HackyLinuxTrayIconInitialiser extends SwingWorker<Void, TrayIcon> {
private static final int MAX_ADD_ATTEMPTS = 4;
private static final long ADD_ICON_DELAY = 200;
private static final long ADD_FAILED_DELAY = 1000;
private TrayIcon[] icons;
public HackyLinuxTrayIconInitialiser(TrayIcon... ic) {
icons = ic;
}
#Override
protected Void doInBackground() {
try {
Method addNotify = TrayIcon.class.getDeclaredMethod("addNotify", (Class<?>[]) null);
addNotify.setAccessible(true);
for (TrayIcon icon : icons) {
for (int attempt = 1; attempt < MAX_ADD_ATTEMPTS; attempt++) {
try {
addNotify.invoke(icon, (Object[]) null);
publish(icon);
pause(ADD_ICON_DELAY);
break;
} catch (NullPointerException | IllegalAccessException | IllegalArgumentException e) {
System.err.println("Failed to add icon. Giving up.");
e.printStackTrace();
break;
} catch (InvocationTargetException e) {
System.err.println("Failed to add icon, attempt " + attempt);
pause(ADD_FAILED_DELAY);
}
}
}
} catch (NoSuchMethodException | SecurityException | NoSuchFieldException e1) {
Log.err(e1);
}
return null;
}
private void pause(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e1) {
Log.err(e1);
}
}
#Override
protected void process(List<TrayIcon> icons) {
for (TrayIcon icon : icons) {
try {
tray.add(icon);
} catch (AWTException e) {
Log.err(e);
}
}
}
}
To use it, just call:
if (<OS is Linux>) {
new HackyLinuxTrayIconInitialiser(ticon, micon, licon).execute();
} else {
try {
tray.add(ticon);
tray.add(micon);
tray.add(licon);
} catch (AWTException e) {
Log.err(e);
}
}
I seem to recall at the time I couldn't just keep calling SystemTray.add(icon) as it this would leave "ghost" trayicons behind on the system tray if I did.
Hope this helps.

How do I remove the 'Applet Started' message in the status bar of Firefox/Chrome on Ubuntu?

This is for a kiosk application where this message is not desired. It's odd because Mac doesn't display this message in either browser -- seems to only happen on Ubuntu.
Using this example applet on Ubuntu 10, Firefox 12, I was able to reproduce the message "Applet initialized," illustrated below. It doesn't appear to be from an overridden init(), and the super implementation is empty; I presume it's a feature of either the plug-in or the browser itself. Oddly, the message actually moves from one lower corner of the browser window to the other, as the mouse cursor approaches it.
For embedded use, consider starting the applet (or hybrid application) via java-web-start as shown in the example.
Addendum: Andrew's example produces the message "Applet started."
Seems like futzing to me, but if by 'status bar' you mean the little bar at the bottom of older browsers, try using Applet.showStatus("") at the end of init() or start().
Edit: Using the following command produces the expected result in appletviwer.
$ appletviewer NoMessageApplet.java
Code:
// intended only to show attributes - view in browser
// <applet code='NoMessageApplet' width=400 height=400></applet>
import java.awt.BorderLayout;
import javax.swing.*;
public class NoMessageApplet extends JApplet {
String noMessage = " Nobody Here But Us Chickens..";
JTextArea output;
#Override
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
initGui();
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
public void initGui() {
JPanel gui = new JPanel(new BorderLayout(5,5));
output = new JTextArea(5,20);
gui.add(new JScrollPane(output));
setContentPane(gui);
setMessage("initGui()" + noMessage);
}
#Override
public void start() {
setMessage("start()" + noMessage);
}
/** Both sets the message as the 'status' message &
appends it to the output control */
public void setMessage(final String message) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
output.append(message + "\n");
}
});
showStatus(message);
}
}
This is not a direct answer to your question but definitely a possible solution to your problem (Was a comment. Added as an answer as suggested by #Andrew Thompson):
If it is a kiosk application then why is there a status bar at all?
If you have control over the system where the application is used from (or where the browser is installed), you can either deactivate the status bar in the browser or make the browser to be displayed always in full screen mode.
Most kiosk applications operate this way.
FF13 fixed it (so does the most recent version of Chrome). Both now currently do not enable status bar's by default (they did when I made this initial post). Not quite an answer, but an answer that worked for me.

How to get screenshot of any Linux/Windows application running outside of the JVM

Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?
Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.
Here is the answer for Windows (not sure if alt+printScr works on linux :P)
I guess one way to achieve this
1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)
2. read the clipboard!
Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.
Code to Fire commands to get active window on clipboard
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class ActiveWindowScreenShot
{
/**
* Main method
*
* #param args (not used)
*/
public static void main(String[] args)
{
Robot robot;
try {
robot = new Robot();
} catch (AWTException e) {
throw new IllegalArgumentException("No robot");
}
// Press Alt + PrintScreen
// (Windows shortcut to take a screen shot of the active window)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
System.out.println("Image copied.");
}
}
Code to read image on clipboard
// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!
You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.

Yes/No dialog in Java ME

I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.
if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
You need an Alert:
An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.
With 2 commands ("Yes"/"No" in your case):
If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.
These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing CommandListener, and prepare your code for asynchronous execution.
Here is an (untested!) example class based on Alert:
public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
To use it (again, untested and on top of my head):
MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
This code will make the prompt the current displayed form in your app, but it won't block your thread like in the example you posted. You need to continue running and wait for a commandAction invocation.
I dont have programed in Java ME, but i found in it's reference for optional packages the
Advanced Graphics and User Interface API, and it's used like the Java SE API to create these dialogs with the JOptionPane Class
int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)
Return could be
JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION...

Categories

Resources