I am trying to perform a small calculation as part of my selenium learning with Java, Sikuli using Eclipse IDE.
My Code is as below:
package webelements.concepts;
import org.sikuli.script.FindFailed;
import org.sikuli.script.ImagePath;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class DeskTopIconEx {
public static void main(String[] args) throws FindFailed, InterruptedException {
// to Perform small calculation on Calculator app which is present on screen.
ImagePath.setBundlePath("/Users/murthyinguva/Desktop/Images");
Thread.sleep(4000);
Screen screenObj = new Screen();
Pattern btnCObj = new Pattern("//Users//murthyinguva//Desktop//Images//btnC");
Pattern btn9Obj = new Pattern("//Users//murthyinguva//Desktop//Images//btn9");
Pattern btnXObj = new Pattern("//Users//murthyinguva//Desktop//Images//btnX");
Pattern btn5Obj = new Pattern("//Users//murthyinguva//Desktop//Images//btn5");
Pattern btnEqualsObj = new Pattern("//Users//murthyinguva//Desktop//Images//btnEquals");
String paths = ImagePath.getBundlePath();
System.out.println("Image path given as :" + paths);
screenObj.click(btnCObj);
screenObj.click(btn9Obj);
screenObj.click(btnXObj);
screenObj.click(btn5Obj);
screenObj.click(btnEqualsObj);
}
}
Console output is:
`Image path given as :/Users/murthyinguva/Desktop/Images
Exception in thread "main" FindFailed: btnC.png: (90x88) in R[0,0 1440x900]#S(0)
Line 2226, in file Region.java
at org.sikuli.script.Region.wait(Region.java:2226)
at org.sikuli.script.Region.wait(Region.java:2244)
at org.sikuli.script.Region.getLocationFromTarget(Region.java:3298)
at org.sikuli.script.Region.click(Region.java:3916)
at org.sikuli.script.Region.click(Region.java:3892)
at webelements.concepts.DeskTopIconEx.main(DeskTopIconEx.java:25)
`
Help required:
I would like to know your advises why i am getting this error and unable to see that Sikuli is performing any mouse actions. I have given the permissions as per:
https://github.com/RaiMan/SikuliX1/wiki/Allow-SikuliX-actions-on-macOS
Because of this difficulty I am unable to progress much, Your help is highly appreciated. Thanks in advance.
Desktop screenshot
The forward slashes in the filenames have to be single.
But since you have used
setBundlePath()
before, the Patterns can be reduced to
String btnCObj = "btnC";
All the best. RaiMan from SikuliX.
Related
I want to execute a Python function which is located in one of my python projects from java by using jython. https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/ is giving the sample code for the purpose. But in my scenario I got the following exception.
Exception in thread "main" Traceback (most recent call last): File
"", line 1, in ImportError: No module named
JythonTestModule
My scenario is as follows.
I have created a python module inside my python project(pythonDev) by using PyCharm(JythonTestModule.py) which contains the following function.
def square(value):
return value*value
Then I created a sample java class in my java project(javaDev) and called the python module.
public static void main(String[] args) throws PyException{
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from JythonTestModule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
After running this java method the aforementioned exception is generated by the java program. I want to know what is the problem with this menioned code segments.
As from the suggestions from the above comments section of this question, I have developed the solution to my question. Following code segment will demonstrate that. In this solution I have set the python.path as the directory path to my module file.
public static void main(String[] args) throws PyException{
Properties properties = new Properties();
properties.setProperty("python.path", "/path/to/the/module/directory");
PythonInterpreter.initialize(System.getProperties(), properties, new String[]{""});
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from JythonTestModule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
If you want to use multiple modules from the Jython, add the python.path as the parent directory path of all the modules in order to detect all the modules.
How can I get the latest tweet from html content through either regex or without any external libraries. I am happy to use external libraries I would just prefer not to. I just wanted to know how it would be possible. I have written the html download part in Java and if anyone wants I will post it here.
So I'll do a pit of pseudo code so that I'm not only targeting Java developers This is how my program looks so far.
1.)Load site("www.twitter.com/user123")
2.)Get initial string and write it to variable->buffer
3.)Loop start
4.) Append string->buffer
5.) If there is no more ->break
6.)print buffer
Obviously the variable buffer will now have raw html content. How can I sort this out to get the tweet. I have found a way but this is too inconsistent. The way I managed it was to find the string which held the tweets and get the content surrounded by the code. However there were too many changes in this section. What I mean is some content inside of it changes, like the font size. I could write multiple if statements but is there a neater solution?
Let me just start off by saying that jsoup is an amazing lightweight HTML parsing library. You can use things like CSS selectors and whatnot. If you ever decide to use a library jsoup will make your life a lot easier.
You can just query for the element with the class of TweetTextSize, then get the text content. This will give you all text, hashtags, and links. (The downside being pictures are also given in links)
Otherwise, you'll need to manually traverse the DOM. For example, use regex to find the beginning of the first TweetTextSize, and then just keep all text which is not between a < and a >.
Unfortunately, this second solution is volatile and may not work in the future, and you'll end up with a big glob of code which is overly complex and hard to debug.
Simple answer if you want a regex and not a sophisticated third party library.
<p[^>]+js-tweet-text[^>]*>(.*)</p>
Try the above on the "view-source" of https://twitter.com/a
Thanks.
EDIT:
Source Code:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TweetSucker {
public static void main(String[] args) throws Exception {
URLConnection urlConnection = new URL("https://twitter.com/a").openConnection();
InputStream inputStream = urlConnection.getInputStream();
String encoding = urlConnection.getContentEncoding();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
String htmlContent = null;
if (encoding != null) {
htmlContent = new String(byteArrayOutputStream.toByteArray(), encoding);
} else {
htmlContent = new String(byteArrayOutputStream.toByteArray());
}
Pattern TWEET_PATTERN = Pattern.compile("(<p[^>]+js-tweet-text[^>]*>(.*)</p>)", Pattern.CASE_INSENSITIVE);
Matcher matcher = TWEET_PATTERN.matcher(htmlContent);
while (matcher.find()) {
System.out.println("Tweet Found: " + matcher.group(2));
}
}
}
I know that you don't want any libraries but if you want something really quick this is working code in C#:
using (IE browser = new IE())
{
browser.GoTo("https://twitter.com/user");
List tweets = browser.List(Find.ById("stream-items-id"));
if (tweets != null)
{
foreach (var tweet in tweets.ListItems)
{
var tweetText = tweet.Paras.FirstOrDefault();
if (tweetText != null)
{
MessageBox.Show(tweetText.Text);
}
}
}
}
This program uses a library called WatiN (if you use Visual Studio go to Tools Menu, select "NuGet Package Manager" then select "Manage Nuget Packages for Solution" and then select "Browse" and then type "Watin" on the search box, after you find the library hit "Install", after it is installed you just add a reference in your code and then a using statement:
using WatiN.Core;
You can just copy and paste the code I wrote above in a button handler and it'll work, you need to change the twitter.com/XXXXXX user name to list all their tweets. Modify code accordingly to meet your needs.
I am trying to launch my my code and start the player. But I can not do that.
import javax.media.*;
import java.io.*;
public class MP3Player {
public static void main(String[] args) throws Exception {
File file = new File("c://player/trigger.mpg");
MediaLocator mrl = new MediaLocator(file.toURL());
Player player = Manager.createPlayer(mrl);
player.start();
}
}
[Edit by Philipp]
According to a comment by the original author, Netbeans prints the following error message:
Unable to handle format: MPEG, 160x120, FrameRate=30.0, Length=28800 Failed to realize:
com.sun.media.PlaybackEngine#131f71a Error: Unable to realize
com.sun.media.PlaybackEngine#131f71a BUILD SUCCESSFUL (total time: 1 second)
[/Edit by Philipp]
I don't know JMF player at all, but I assume the problem is that the code exits immediately after issuing the command, terminating any other threads...
I'd try inserting a Thread.sleep(1000); after player.start(); :
public class MP3Player {
public static void main(String[] args) throws Exception
{
File file = new File("c:/player/trigger.mpg");
MediaLocator mrl = new MediaLocator(file.toURL());
Player player = Manager.createPlayer(mrl);
player.start();
Thread.sleep(1000);
}
}
If now the first second of the MP3 is heard, this was the issue.
EDIT Also, someone pointed out problems with the slashes, the path should be correct too, but the slash is not missing, but there is rather one too much of it...
EDIT2 Ok, I misread mpg for mp3, and as the poster posted the error he got: the format of the video is not supported by JMF, you need a codec.
This might be of help: Tek-tips: Play MPEG-4 movie with JMF?
Unable to handle format: MPEG, 160x120, FrameRate=30.0
It is unable to play a video stream it founds. From the description and the name of your code, the file is expected to contain only audio streams of the compression format MP3 (MPEG-1 Audio Layer III). An .mpg extension may contains lot of different mpeg formats
Using java, I would like some code that could get me the paths for:
1) Start Menu for Current User
2) Start Menu for All User
I need the answer for both WinXP and Win7. So hopefully there is a general answer that can get me both.
You have no other choice but to write a DLL and call native Windows API:
SHGetFolderPath(NULL, CSIDL_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, &szPathBuffer)
SHGetFolderPath(NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, &szPathBuffer)
If you really need the root of Start menu, use CSIDL_STARTMENU and CSIDL_COMMON_STARTMENU.
The full list of known folders: CSIDL.
If you target Windows Vista and above, use SHGetKnownFolderPath function instead of SHGetFolderPath.
You can use JNA library to call native Windows API without writing native code yourself but pure Java code.
Okay, I figured out a solution, but maybe someone else has a more eligant one.
I plan on doing something like "Runtime.getRuntime().exec(command);" and the command will be a "reg query" to query the following registry keys:
Current User can referenced by: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Start Menu
All users can be referenced by: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common Start Menu
These are the same for both Win7 and WinXP. If anyone else knows of a better solution, I'll be happy to look at it too.
In my program I used a simple System.getProperty("user.home") + "/Start Menu/Programs" This gave me the user's Start Menu folder.
It worked on windows 7 and windows 10. I tried this because in order to get a user's desktop, all I had to do was call System.getProperty("user.home") + "/Desktop". SO I figured that it might work for the Start Menu as well, and seemed to have worked fine. I can delete and write files to the Start Menu just like I can with the desktop. Whether this is the right way to do something like this or not, I have no idea. But I'm just sharing what worked for me.
Another option is managing Start Menu items from vbs API.
I made a Java Wrapper for that.
// Install Start Menu
WindowsUtils.installStartMenuItem(WindowsUtils.SPECIALFOLDER_Programs,"my_start_menu", "explorer.exe", "http://www.google.es","Acceso directo a google");
// Uninstall Start Menu
WindowsUtils.uninstallStartMenuItem(WindowsUtils.SPECIALFOLDER_Programs, "my_start_menu");
i recently found this
public class VBSUtils {
public static String SF_ALLUSERSDESKTOP = "AllUsersDesktop";
public static String SF_ALLUSERSSTARTMENU = "AllUsersStartMenu";
public static String SF_ALLUSERSPROGRAMS = "AllUsersPrograms";
public static String SF_ALLUSERSSTARTUP = "AllUsersStartup";
public static String SF_DESKTOP = "Desktop";
public static String SF_FAVORITES = "Favorites";
public static String SF_MYDOCUMENT = "MyDocuments";
public static String SF_PROGRAMS = "Programs";
public static String SF_RECENT = "Recent";
public static String SF_SENDTO = "SendTo";
public static String SF_STARTMENU = "StartMenu";
private VBSUtils() { }
public static String getSpecialFolder(String folder) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n"
+ "wscript.echo WshShell.SpecialFolders(\"" + folder + "\")\n"
+ "Set WSHShell = Nothing\n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
result = input.readLine();
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args){
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_ALLUSERSSTARTMENU));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_ALLUSERSDESKTOP));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_DESKTOP));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_PROGRAMS));
//System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_STARTUP));
}
}
I've been making a program that uses a JFileChooser. I've set the application up with
UIManager.getSystemLookAndFeelClassName()
Which works just fine for pretty much everything under Ubuntu. The only problem I've run into so far is that the JFileChooser comes out looking pretty awful:
Is there a way to make this look like the default file chooser in Ubuntu? ie.
I've tried using
UIManager.getCrossPlatformLookAndFeelClassName()
Which makes the JFileChooser dialog look better, but still not native looking, and it ruins the rest off the application's feel too.
Thanks.
If I recall correctly, the stock JDK used gtk1, but ubuntu uses gtk2 currently. I forget where but i've come across gtk2 for java somewhere. Google? Probably not what you were hoping for, sorry.
You might see if FileDialog is any more appealing; here's an example.
The Nimbus look and feel has a decent file chooser. Although this will affect your entire application, you might like the look.
Also you can build your own file chooser if needed.
You can also use SWT instead of swing.
Does Swing support Windows 7-style file choosers?
The following code is from above link
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class SWTFileOpenSnippet {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
// Don't show the shell.
//shell.open ();
FileDialog dialog = new FileDialog (shell, SWT.OPEN | SWT.MULTI);
String [] filterNames = new String [] {"All Files (*)"};
String [] filterExtensions = new String [] {"*"};
String filterPath = "c:\\";
dialog.setFilterNames (filterNames);
dialog.setFilterExtensions (filterExtensions);
dialog.setFilterPath (filterPath);
dialog.open();
System.out.println ("Selected files: ");
String[] selectedFileNames = dialog.getFileNames();
for(String fileName : selectedFileNames) {
System.out.println(" " + fileName);
}
shell.close();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}