I am trying to type all the possible keys from Keyboard, irrespective of languages or layout using Java Robot.
We have written a super class which has common methods to print characters KeyEvent.VK_A to KeyEvent.VK_Z, number KeyEvent.VK_0 to KeyEvent.VK_9 along with SHIFT key combination.
Now coming to specific part that is if we are having Italy or Turkish Keyboard which are having Unicode present or if any other special character. How can I stimulate the same keypress or keyrelease ? (as there is no valid KeyCode present for such characters)
Say we have ò,à,ù or *,§, etc
I am trying this on JDK 1.6. Here is Code snippet
protected void keyPressRelease(int keyCode){
try{
this.robot.keyPress(keyCode);
this.robot.keyRelease(keyCode);
}catch(java.lang.IllegalArgumentException e){
logger.error("keyPressRelease() No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode);
logger.error("Error in typing ",e);
this.errorBuilder.append("IllegalArgumentException keyPressRelease(), No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode+"<br\\>");
}catch(Exception e){
logger.error("keyPressRelease() No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode);
logger.error("Error in typing ",e);
this.errorBuilder.append("Exception keyPressRelease(), No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode+"<br\\>");
}
}//End of keyPressRelease()
protected void shiftKeyPress(int keyCode){
this.robot.keyPress(KeyEvent.VK_SHIFT);
try{
this.robot.keyPress(keyCode);
this.robot.keyRelease(keyCode);
}catch(java.lang.IllegalArgumentException e){
logger.error("shiftKeyPress() No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode);
this.errorBuilder.append("Exception shiftKeyPress(), No key present "+KeyEvent.getKeyText(keyCode)+ " for Key Code :"+keyCode+"<br\\>");
}
this.robot.keyRelease(KeyEvent.VK_SHIFT);
}//End of shiftKeyPress()
protected void typeLableName(int keyCode){
String labelName = KeyEvent.getKeyText(keyCode);
type(labelName+" ");
labelName = null;
}//End of typeLableName
//Windows 7 , normal keyboard, from Control panel changed the layout to Italy
private void checkSplCharacters(){
this.keyPressRelease(KeyEvent.VK_ENTER);
/*Start of --> § Cedilla Small*/
this.typeLableName(KeyEvent.VK_BACK_SLASH);
this.keyPressRelease(KeyEvent.VK_BACK_SLASH);
this.keyPressRelease(KeyEvent.VK_ENTER);
this.typeLableName(KeyEvent.VK_BACK_SLASH);
this.shiftKeyPress(KeyEvent.VK_BACK_SLASH);
this.keyPressRelease(KeyEvent.VK_ENTER);
/*End of --> § Cedilla Small*/
/*Start of --> ì Grave Small*/
this.typeLableName(KeyEvent.VK_PLUS);
this.keyPressRelease(KeyEvent.VK_PLUS);
this.keyPressRelease(KeyEvent.VK_ENTER);
this.typeLableName(KeyEvent.VK_PLUS);
this.shiftKeyPress(KeyEvent.VK_PLUS);
this.keyPressRelease(KeyEvent.VK_ENTER);
/*End of --> ì Grave Small*/
}//End of checkSplCharacters
some of the points running in mind
A dummy point, is it possible to know the position of the Keys say mapping in the format of rows & columns? If so which API will return the keyboards rows? & then I will try to run in loop for that row & that key.
Read some places with Numpad + ALT key, also it seems this works on Windows & what if Numpad is not there ?
Took a refernce from here
Can we create our own customized mapping for same & is there a possible way to overwrite ?(any snippet for it)
Or any other possible way to type/ perform java robot for unicode/special characters.
Am trying some what below thing
Basically want to type ò,à,ù or *,§, using java Robot. So String a = "ò,à,ù or *,§"; //Unicode charactres
try{
Robot robot = new Robot();
for(int i=0;i
robot.keyPress(?);//What would be the equivalent key code for above Unicodes
}
}catch(Exception e){
}
Related
I have an unexpected issue with the sendKeys() method:
A long time before it all worked fine, but unexpectedly the (certain(!)) values are replaced when the code tries to set data into the input field:
For example, if I set value USER_NAME into the field, value replaced with /tmp/7d7b7...../upload123...file/USER_NAME. As we can see - some path was added into the USER_NAME value.
I added logs to the method and we can see a moment when the value was replaced:
clearInputFld(inputFld);
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value after clearing: " + inputElement.getAttribute("value"));
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value to set: " + value);
inputElement.sendKeys(value);
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value after set: " + inputElement.getAttribute("value"));
Output:
INSIDE clearAndTypeIntoInputField() ---------> value after clearing:
INSIDE clearAndTypeIntoInputField() ---------> value to set: USER_NAME
INSIDE clearAndTypeIntoInputField() ---------> value after set: /tmp/7d7b7...../upload123...file/USER_NAME
So we can be sure - value sets exactly at the moment when value sets into the field.
Important to know, and conclusions:
Not all users replaced - Only several certain users! So I suppose a part of users is cached. But I do not understand the process with which this happens, why this happens, and where these users might be cached.
I also restarted the docker, so it seems the problem is not in the automatic side.
Is it possible that this issue occurs via the backend or UI part?
It looks like there is a script running on the page that changes the input you type, as this is a password field.
What I suggest is that you use the Robot object to mimic keyboard strokes.
First click on the text field using Selenium, then launch the Robot code (use package Java.awt):
Robot robot = null;
try {
robot = new Robot();
for (char c : textToType.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
logger.error("Key code not found for character '" + c + "'");
} else {
try {
robot.keyPress(keyCode);
robot.delay(10);
robot.keyRelease(keyCode);
robot.delay(10);
} catch (Exception e) {
if (c == '_') {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
if (c == ':') {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
}
}
robot.keyPress(KeyEvent.VK_ENTER);
} catch (Exception ex) {
logger.error(ex.getMessage());
}
According to Logs, I think there is something come with the value.
Suggest trying :
Get the changed text, do some operation, fill it back
string[] temp;
temp = (inputElement.Text).Split('/');
inputElement.Sendkeys(temp(temp.Length - 1));
I am doing batchWriteItem operation on multiple tables of DynamoDb. My code is as follows -
BatchWriteItemOutcome outcome = null;
try {
TableWriteItems userTableWriteItems = new TableWriteItems("User")
.withHashAndRangeKeysToDelete("clientAccountKey", "userKey", clientAccountKey, "xyzUserKey"); // Working for this Method
TableWriteItems PosTrackingWriteItems = new TableWriteItems("PosTracking")
.withHashOnlyKeysToDelete("userKey", "xyzUserKey"); // ** Not Working for this **
outcome = dynamoDb.batchWriteItem (
userTableWriteItems,
PosTrackingWriteItems);
}
catch(Exception e){
System.out.println("Exception in Removing User Data !!! ");
e.printStackTrace();
}
If I just specify batchWrite delete withHashAndRangeKeysToDelete method where I specify Hash and Range key both, it is working.
But its not working for withHashOnlyKeysToDelete method where I specify HashKey name and HashKey Value as paramerters. I keep getting this exception:
com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: The provided key element does not match the schema. Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException.
My PosTracking table has HashKey (String) as userKey and I am passing String from the method as well. I have a GSI also in this table with name clientAccountKey (String). I tried using addHashOnlyPrimaryKeysToDelete & .addPrimaryKeyToDelete methods also for TableWriteItems but its not working either.
What is the primary key schema for the PosTracking table? Does it have a range key? If so you need to specify both the hash key and range key. DynamoDB does not allow you to delete items using just a hash key - you must specify the complete primary key including the range key.
I have written a code to connect to this webpage: compilerjava.net
1) I found the text-area field within that page which accepts the code to compile.
2) I have found the button that compiles the code.
3) I have found the text-area which returns the result of the code.
The issue is, when I call textarea.setText( "something"), it (I think) doesn't actually change the code in the webpage. So when I click on the compile button, it compiles the default code within that page and returns the output of that default code.
I have tried to set focus to textarea, you can see all of those down below.
I called;
1) textArea.focus();
2) textArea.click();
3) I tried using textArea.setAttribute( "name", "code");
I have searched the internet and found various stackoverflow questions close to this problem, neither of them solved my issue and it just seems to work for everyone when they say textArea.setText().
Another interesting fact I should share with you is,
If I call textArea.setText( "...") and then I say;
HtmlTextArea textArea1 = form.getTextAreaByName( "code");
If I call textArea1.getText(), the value of this text will be "...". This should imply that I have actually managed to change the value of the text-area, but when I compile, it compiles the default text in the text-area and not the text that I have set it to.
Any help with this?
P.S: The reason why I put the result of the compilation on a while loop is related to network connection issues. If you try to run this code it might not work on your first try. Also note that the run-time is around 15 seconds, because it gives thousands of warnings which I blocked to print to console.
P.S2: I also looked at this page and none of these worked;
http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.html.HtmlTextArea
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
textArea.click();
textArea.focus();
// Simple code to run.
textArea.setDefaultValue( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
System.out.println( textArea.getText());
// Compiles.
button.click();
// Result of the compilation.
String str = resultArea.getText();
while ( resultArea.getText() == null || resultArea.getText().substring(0, 3).equals( "exe")) {
System.out.print( resultArea.getText());
}
System.out.println();
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
a little patience helps here
// Result of the compilation.
while (resultArea.getText() == null || resultArea.getText().startsWith("exe")) {
System.out.println(resultArea.getText());
Thread.sleep(500);
}
System.out.println();
System.out.println(resultArea.getText());
I'm working on a program that serves as a hypothetical email system in which users can be created and can send messages to other users that have been created.
The message will be stored in a "Message" class, and the text is typed in a JTextArea in a GUI. What I want to know is how I would go about storing the text typed into the JTextArea, in the exact same layout (indentations and all), within the Message class. I thought about text files but then there would have to be one for each message, potentially creating an infinite number of them, and I don't like the concept of having to make a system for coming up with unique names for each text file.
Can you please give me some advice?
Simply implement the DocumentListener interface, then do the following:
JTextArea someMessage = new JTextArea();
someMessage.getDocument().addDocumentListener(new MyDocumentListener());
someMessage.getDocument().putProperty("name", "Text Area");
Here, we assume the name of the listener you implement is called MyDocumentListener, and the implementation could be as simple as:
class MyDocumentListener implements DocumentListener {
String newline = "\n";
#Override
public void insertUpdate(DocumentEvent e) {
updateLog(e, "inserted into");
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLog(e, "removed from");
}
#Override
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
displayArea.append(
changeLength + " character" +
((changeLength == 1) ? " " : "s ") +
action + doc.getProperty("name") + "." + newline +
" Text length = " + doc.getLength() + newline);
}
}
Examples taken from Oracle website. I recommend reading the rest of that article as it goes into much depth of how to effectively listen for updates to the internal document model.
How to get text that was inserted
insertUpdate is what notifies you when new text has been typed into the textarea. You can get the freshly inserted text by calling off to the DocumentEvent#getOffset and DocumentEvent#getLength. Using both methods, you can get the offset (index) within document where the insertion happened, as well as the length of the change.
Then to get the actual text that was inserted, you call DocumentEvent#getDocument#getText and supplying the offset and length you got from the event.
How to get all the text in the textarea
You can use this similar method to get the entire text in the document by making use of Document#getStartPosition and Document#getEndPosition, then calling Document#getText.
Or even easier, JTextArea#getText
I have created a custom view on Eclipse and defined a drag and drop listener for it. When I drag items from my view onto the native Java editor (using TextTransfer as the mechanism), the text successfully gets pasted on the editor.
However, when I try to do the opposite i.e. when I select a piece of text from the Java editor and drag it to my view, then the cursor shows an invalid sign and the drop doesn't work as expected. The Drop Target is also set to accept TextTransfer instances.
When I have two Java editors open and I drag text from one to the other, it works perfectly. Why does it not work when I drag the text onto my view?
I overrode the dragEnter function of the DropTargetAdapter in my view to check if the drag was being detected and it was. After printing the event.datatypes, I can also see the CF_TEXT type being supported. When I print the event.data, however it is null. Why?
Code is below:
viewDropTargetAdapter = new DropTargetAdapter()
{
#Override
public void drop(DropTargetEvent event)
{
addCodeSnippetAction.run();
}
#Override
public void dragEnter(DropTargetEvent event)
{
System.out.println("DATATYPE: " + event.currentDataType);
System.out.println("DATA: " + event.data);
System.out.println("DETAIL: " + event.detail);
TransferData[] td = event.dataTypes;
for(int i=0; i<td.length; i++)
{
System.out.println("Datatype of " + i + " is: " + td[i].type + " and " +getNameFromId(td[i].type));
}
super.dragEnter(event);
}
};
viewDropTarget = new DropTarget(viewer.getControl(), DND.DROP_COPY);
viewDropTarget.setTransfer(new Transfer[] {TextTransfer.getInstance()});
viewDropTarget.addDropListener(viewDropTargetAdapter);
Output is below:
DATATYPE: org.eclipse.swt.dnd.TransferData#77f5c2c7
DATA: null
DETAIL: 0
Datatype of 0 is: 13 and CF_UNICODETEXT
Datatype of 1 is: 1 and CF_TEXT
After some researching, I realized that it is necessary to set the event.detail variable manually in the DragEnter function. After adding the line:
event.detail = DND.DROP_COPY;
it works now.