My cell phone provider offers a limited number of free text messages on their website. I frequently use the service although I hate constantly having a tab open in my browser.
Does anyone know/point me in the right direction of how I could create a jar file/command line utility so I can fill out the appropriate forms on the site. I've always wanted to code up a project like this in Java, just in case anyone asks why I'm not using something else.
Kind Regards,
Lar
Try with Webdriver from Google or Selenium.
Sounds like you need a framework designed for doing functional testing. These act as browsers and can navigate web sites for testing and automation. You don't need the testing functionality, but it would still serve your needs.
Try HtmlUnit, or LiFT, which is a higher-level abstraction built on HtmlUnit.
Use Watij with the Eclipse IDE. When your done, compile as an .exe or run with a batch file.
Here is some sample code I wrote for filling in fields for a Google search, which can be adjusted for the web form you want to control :
package goog;
import junit.framework.TestCase;
import watij.runtime.ie.IE;
import static watij.finders.SymbolFactory.*;
public class GTestCases extends TestCase {
private static watij.runtime.ie.IE activeIE_m;
public static IE attachToIE(String url) throws Exception {
if (activeIE_m==null)
{
activeIE_m = new IE();
activeIE_m.start(url);
} else {
activeIE_m.goTo(url);
}
activeIE_m.bringToFront();
return (activeIE_m);
}
public static String getActiveUrl () throws Exception {
String currUrl = activeIE_m.url().toString();
return currUrl;
}
public void testGoogleLogin() throws Exception {
IE ie = attachToIE("http://google.com");
if ( ie.containsText("/Sign in/") ) {
ie.div(id,"guser").link(0).click();
if ( ie.containsText("Sign in with your") ||
ie.containsText("Sign in to iGoogle with your")) {
ie.textField(name,"Email").set("test#gmail.com");
ie.textField(name,"Passwd").set("test");
if ( ie.checkbox(name,"PersistentCookie").checked() ){
ie.checkbox(name,"PersistentCookie").click();
}
ie.button(name,"signIn").click();
}
}
System.out.println("Login finished.");
}
public void testGoogleSearch() throws Exception {
//IE ie = attachToIE( getActiveUrl() );
IE ie = attachToIE( "http://www.google.com/advanced_search?hl=en" );
ie.div(id,"opt-handle").click();
ie.textField(name,"as_q").set("Watij");
ie.selectList(name,"lr").select("English");
ie.button(value,"Advanced Search").click();
System.out.println("Search finished.");
}
public void testGoogleResult() throws Exception {
IE ie = attachToIE( getActiveUrl() );
ie.link(href,"http://groups.google.com/group/watij").click();
System.out.println("Followed link.");
}
}
It depends on how they are sending the form information.
If they are using a simple GET request, all you need to do is fill in the appropriate url parameters.
Otherwise you will need to post the form information to the target page.
You could use Watij, which provides a Java/COM interface onto Internet Explorer. Then write a small amount of Java code to navigate the form, insert values and submit.
Alternatively, if it's simple, then check out HttpClient, which is a simple Java HTTP client API.
Whatever you do, watch out that you don't contravene your terms of service (easy during testing - perhaps you should work against a mock interface initially?)
WebTest is yet another webapp testing framework that may be easier to use than the alternatives cited by others.
Check out the Apache Commons Net Package. There you can send a POSt request to a page. This is quite low level but may do what you want (if not you might check out the functional testing suites but it is probably not as easy to dig into).
As jjnguy says, you'll need to dissect the form to find out all the parameters.
With them you can form your own request using Apache's HTTP Client and fire it off.
Related
Good day, i have a Processing sketch that i want to use in a web application
i am using jsp and servlets in my web app with tomcat as a server. I am using netbeans and i tried using < applet > tag but i can't get it to work, please help.
CODE:
import processing.core.*;
public class MyProcessingSketch extends PApplet {
public static void main(String args[]) {
PApplet.main(new String[] { "MyProcessingSketch" });
}
public void setup() {
}
#Override
public void draw() {
background (200,0,0);
}
public void settings(){
size(600,240);
}
public void mousePressed(){
exit();
}
}
Applets are not really supported anymore... But you might try p5js. Your HTML page would look like this:
<html>
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>
<script>
function setup() {
createCanvas(600, 240);
background(200,0,0);
}
function draw() {
// ...
}
</script>
Like the other answer says, applets are pretty much dead. They currently require you to have a paid signed certificate or for your users to change their security settings. And even then they show a bunch of scary warning dialogs, and it's just a pain in the neck for everybody. Chrome has dropped support for applets, and they'll be deprecated in the next version of Java.
If you're using eclipse, you've got three options:
Deploy as a runnable jar.
Deploy as a packaged executable.
Deploy using webstart.
None of these are embedding an applet in a webpage.
However, if you're using the Processing editor, you can use Processing.js to write the same Processing code but have it deployed as JavaScript, which you can embed in a webpage. Processing.js does the translation for you, so you don't have to change your code into JavaScript code.
You can also use p5.js, but that will require you to completely rewrite your syntax into JavaScript syntax.
In either case, you'll no longer be able to use Java libraries in your code. You'll have to find a JavaScript library that does the same things and use that instead. If you really need to use the Java libraries, then you have to go with deploying using one of the first three options.
I need to test a webpage via desktop application, I'm trying to use
the selenium IDE, I had sucess to create the test cases, but I'm not
able to execute them on java.
I've been looking for something helpful, but I can't find any help at all.
Thank you
A framework that has been created for just this cause, (it's in Java) can be downloaded here or you can check the project out from github here.
This project was designed to be very simple, yet very effective. This type of framework is a "free version" of my interpretation of a framework that I use every day in production-type environments.
There is a sample test that is enclosed in the project named SampleFunctionalTest.java. Assuming you follow the ReadMe to the T, you should have no problem getting started.
Here is what a test would look like in this framework.
#Config(url = "http://ddavison.github.io/tests/getting-started-with-selenium.htm", browser = Browser.FIREFOX) // You are able to specify a "base url" for your test, from which you will test. You may leave `browser` blank.
public class SampleFunctionalTest extends AutomationTest {
/**
* You are able to fire this test right up and see it in action. Right click the test() method, and click "Run As... jUnit test".
*
* The purpose of this is to show you how you can continue testing, just by taking the semi colon out, and continuing with your test.
*/
#Test
public void test() {
// click / validateAttribute
click(props.get("click"))
.validateAttribute(props.get("click"), "class", "success") // validate that the class indeed added.
// setText / validateText
.setText(By.id("setTextField"), "woot!")
.validateText(By.id("setTextField"), "woot!") // validates that it indeed set.
// check / uncheck
.check(By.id("checkbox"))
.validateChecked(By.id("checkbox")) // validate that it checked
.check(props.get("radio.2")) // remember that props come from <class name>.properties, and are always CSS selectors. (why use anything else, honestly.)
.validateUnchecked(props.get("radio.1")) // since radio 1 was selected by default, check the second one, then validate that the first radio is no longer checked.
// select from dropdowns.
.selectOptionByText(By.xpath("//select[#id='select']"), "Second") // just as a proof of concept that you can select on anything. But don't use xpath!!
.validateText(By.id("select"), "2") // validateText() will actually return the value="" attr of a dropdown, so that's why 2 works but "Second" will not.
.selectOptionByValue(By.cssSelector("select#select"), "3")
.validateText(props.get("select"), "3")
// frames
.switchToFrame("frame") // the id="frame"
.validatePresent(By.cssSelector("div#frame_content"))
// windows
.switchToWindow("Getting Started with Selenium") // switch back to the test window.
.click(By.linkText("Open a new tab / window"))
.waitForWindow("Google") // waits for the url. Can also be the you are expecting. :) (regex enabled too)
.setText(By.name("q"), "google!")
.closeWindow(); // we've closed google, and back on the getting started with selenium page.
}
}
You should create an instance of a WebDriver and call methods on the instance of that object.
An easy example is shown here: http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
I hope you have created the script in webdriver.
Now in the script recorded by the selenium ide you have three methods called
setup, testSomeName and tearDown.
From the very basic: to run this script all you need to do is create a main method in the same class and in that you need to call these methods in the same order as specified above.
After that you just need to run that program.
Here is an example to make it more clear:
public class p_adjcb {
public void setUp() throws Exception {
}
public void testP_adjcb() throws Exception {
}
public void tearDown() throws Exception {
}
public static void main(String[] args) {
p_adjcb obj = new p_adjcb();
try {
obj.setUp();
obj.testP_adjcb();
obj.tearDown();
} catch (Exception ex) {
}
}
}
If you get any compiler error make sure you have downloaded the selenium-standalone-server.jar file and added it to your class path.
This is a very basic start. Later on you may need to use som framework like junit.
Hope it helps.
I've got a program that currently has a mass of code that I would like to design away. This code takes a number of text files and passes it through an interestingly written interpreter to produce a plain text file report that goes on to other systems. In theory this allows a non-programmer to be able to modify the report without having to understand the inner workings of Java and the interpreter. In practice, any minor change likely necessitates going into the interpreter and tweaking it (and the domain specific language isn't exactly friendly even to other programmers).
I would love to redesign this code. As a primarily web programmer the first thing that came to mind when thinking of "non-programmer being able to modify the report ..." I replaced report with web page and said to myself "ah ha! Jsp." This would give me a nice What You See Is Almost What You Get approach for people along with taglibs and java scriptlets (as undesirable as the later may be) rather than awkwardly written DSL statements.
While it is possible to use jspc to compile a jsp into java (another part of the application runs ejbs on a jboss server so jspc isn't too far away), the boilerplate code that it uses tries to hook up the output to the pagecontext from the servletcontext. It would involve tricking the code into thinking it was running inside a web container (not an impossibility, but a kluge) and then removing the headers.
Is there a different templateing approach (or library) for java that could be used to print to a text file? Every one that I've looked at so far appears to either be optimized for web or tightly coupled to a particular application server (and designed for web work).
So you need a slim down version of JSP.
See if this one (JSTP) works for you
http://jstp.sourceforge.net/manual.html
Give Apache Velocity a try. It is incredibly simple and does not assume it is running in the context of a web application.
This is totally subjective, but I would argue it's syntax is easier for a non-programmer to understand than JSP and tag libraries.
If you want to be a real tread setter in your company, you could create a Grails application to do it and use Groovy templating (maybe in combination with the Quartz plugin for scheduling), it might be a bit of a hard sell if there is alot of existing code to be replaced but I love it...
http://groovy.codehaus.org/Groovy+Templates
If you want the safe bet, then (the also excellent) Velocity has to be it:
http://velocity.apache.org/
Probably you want to check Rythm template engine, with good performance (2 to 3 times faster than velocity) and elegant syntax (.net Razor like) and designed specifically to Java programmer.
Template, generate a string of user names separated by "," from a list of users
#args List<User> users
#for (User user: users) {
#user.getName() #user_sep
}
Template: if-else demo
#args User user
#if (user.isAdmin()) {
<div id="admin-panel">...</div>
} else {
<div id="user-panel">...</div>
}
Invoke template using template file
// pass render args by name
Map<String, Object> renderArgs = ...
String s = Rythm.render("/path/to/my/template.txt", renderArgs);
// or pass render arguments by position
String s = Rythm.render("/path/to/my/template.txt", "arg1", 2, true, ...);
Invoke template using inline text
User user = ...;
String s = Rythm.render("#args User user;Hello #user.getName()", user);
Invoke template with String interpolation mode
User user = ...;
String s = Rythm.render("Hello #name", user.getName());
ToString mode
public class Address {
public String unitNo;
public String streetNo;
...
public String toString() {
return Rythm.toString("#_.unitNo #_.streetNo #_.street, #_.suburb, #_.state, #_.postCode", this);
}
}
Auto ToString mode (follow apache commons lang's reflectionToStringBuilder, but faster than it)
public class Address {
public String unitNo;
public String streetNo;
...
public String toString() {
return Rythm.toString(this);
}
}
Document could be found at http://www.playframework.org/modules/rythm. Full demo app running on GAE: http://play-rythm-demo.appspot.com.
Note, the demo and doc are created for play-rythm plugin for Play!Framework, but most of the content also apply to the pure rythm template engine.
Source code:
Rythm template engine: https://github.com/greenlaw110/rythm/
Play Rythm Plugin: https://github.com/greenlaw110/play-rythm
I'm trying to develop an extension for firebug. I want to call a java method in this extension but there is no html in it so I can't use the applet-html solution.
Here is my java Applet :
import java.applet.Applet;
import javax.swing.JOptionPane;
public class MyApplet extends Applet {
public void init() {
super.init();
System.out.println("init something");
}
public String jsCall(String hello) {
System.out.println("this method is called by a js function and say :"
+ hello);
Thread t = new Thread(new Runnable(){
public void run(){
JOptionPane jop1 = new JOptionPane();
jop1.showMessageDialog(null, "Message informatif", "Information", JOptionPane.INFORMATION_MESSAGE);
}
});
t.start();
return "lala";
}
}
I try this:
var applet = document.createElement("applet");
applet.setAttribute("code","file:///home/dacostam/z_test/firebug-extension-examples-0bdcf15/helloamd#janodvarko.cz/chrome/content/MyApplet.class");
applet.setAttribute("id","javaToJavascriptApplet");
applet.setAttribute("mayscript","true");
applet.jsCall("HelloWorld"); //jsCall not a function
And this:
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
dom.appendChild(applet);
dom.javaToJavascriptApplet.jsCall("HelloWorld"); //jsCall not a function
The document is not like usual there is no body or html in it.
Is there an other way to call java in javascript instead of the applet-html solution?
Or is there a way to do it with this method but otherwise?
If you need more information, I'm here.
Thanks.
Edit:
It would be to long to explain you what the program do, just keep in mind that it's inevitably in java, I just need to call a method which take a parameter string and return a string or eventually void.
Edit2:
Sorry I have not thought of that, java needs to run on the client.
If your requirement is to make a call from JavaScript to your Java application, you need to clarify where does your Java app needs to run.
If Java needs to run on the client (same machine as your Firebug), it looks like you are either stuck with an applet or you need to be building a tiny webservice in your Java so you can talk to it through a web API on localhost.
If your Java can sit on a server somewhere, you could talk to your Java application through a web API (similarly to the second option above).
Is it possible to teach HTMLUnit to ignore certain javascript scripts/files on a web page? Some of them are just out of my control (like jQuery) and I can't do anything with them. Warnings are annoying, for example:
[WARN] com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument:
getElementById(script1299254732492) did a getElementByName for Internet Explorer
Actually I'm using JSFUnit and HTMLUnit works under it.
If you want to avoid exceptions because of any JavaScript errors:
webClient.setThrowExceptionOnScriptError(false);
Well I am yet to find a way for that but I have found an effective workaround. Try implementing FalsifyingWebConnection. Look at the example code below.
public class PinConnectionWrapper extends FalsifyingWebConnection {
public PinConnectionWrapper(WebClient webClient)
throws IllegalArgumentException {
super(webClient);
}
#Override
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse res = super.getResponse(request);
if(res.getWebRequest().getUrl().toString().endsWith("/toolbar.js")) {
return createWebResponse(res.getWebRequest(), "",
"application/javascript", 200, "Ok");
}
return res;
}
}
In the above code whenever HtmlUnit will request for toolbar.js my code will simply return a fake empty response. You can plug-in your above wrapper class into HtmlUnit as below.
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
new PinConnectionWrapper(webClient);
Take a look at WebClient.setScriptPreProcessor. It will give you the opportunity to modify (or in your case, stop) a given script before it is executed.
Also, if it is just the warnings getting on your nerves I would suggest changing the log level.
If you are interested in ignoring all warning log entries you can set the log level to INFO for com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in the log4j.properties file.
LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);
Insert this code.