Skip to content

Commit

Permalink
Dev guide code style (#384)
Browse files Browse the repository at this point in the history
Replacement for #271 (merged master into the branch).
  • Loading branch information
zbynek authored Jan 22, 2025
1 parent 55d6d76 commit 8d6c5ec
Show file tree
Hide file tree
Showing 8 changed files with 113 additions and 112 deletions.
27 changes: 11 additions & 16 deletions src/main/markdown/articles/testing_methodologies_using_gwt.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public class MeetingSummaryLabelTest extends GWTTestCase {

// Add tests here
}

```

The only visible difference is that all GWTTestCases must override an abstract method called `getModuleName`, which returns a String containing the name of your GWT code module as defined in your application's module XML file.
Expand Down Expand Up @@ -111,7 +110,7 @@ public class PresenterTest extends TestCase {
verify(scheduler);
verify(view);

assertEquals("Should have updated the model's capacity", 225, meeting.getCapacity());
assertEquals("Should have updated the model's capacity", 225, meeting.getCapacity());
}
}

Expand Down Expand Up @@ -150,10 +149,10 @@ public class Presenter {
}

/**
* Callback when the view's capacity text box changes
*
* @param textField the capacity TextBox widget
*/
* Callback when the view's capacity text box changes
*
* @param textField the capacity TextBox widget
*/
public void requiredCapacityChanged(HasText textField) {
meeting.setCapacity(Integer.parseInt(textField.getText()));
if (!roomScheduler.canAcceptCapacityFor(meeting)) {
Expand All @@ -180,18 +179,17 @@ package com.google.gwt.user.client.ui;
public interface HasText {

/**
* Gets this object's text.
*/
* Gets this object's text.
*/
String getText();

/**
* Sets this object's text.
*
* @param text the object's new text
*/
* Sets this object's text.
*
* @param text the object's new text
*/
void setText(String text);
}

```

This simple interface is used by many GWT components and allows manipulation of a widget's text contents, including the TextBox in our example. This interface is extremely useful for testing because we don't need to pass in a real TextBox. Thus we avoid instantiating a text input in the DOM, requiring our test to extend GWTTestCase to run in a real browser. In this example, I've made a very simple fake implementation which wraps a String:
Expand All @@ -212,7 +210,6 @@ public class FakeTextContainer implements HasText {
this.text = text;
}
}

```

Finally, let's take a look at our view implementation:
Expand Down Expand Up @@ -250,7 +247,6 @@ public class MeetingViewWidget extends Composite implements MeetingView {
saveButton.setEnabled(false);
}
}

```

And lastly, the Meeting class code, for completeness:
Expand All @@ -267,7 +263,6 @@ public class Meeting {
this.capacity = capacity;
}
}

```

As you can see, there's not much logic here. Most of the code is involved in setting up the event listeners and configuring the display widgets. So how do we test it in a GWTTestCase?
Expand Down
26 changes: 13 additions & 13 deletions src/main/markdown/doc/latest/DevGuideCodingBasicsDelayed.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ To create a timer, create a new instance of the Timer class and then override th

```java
Timer timer = new Timer() {
public void run() {
Window.alert ("Timer expired!");
}
};
public void run() {
Window.alert("Timer expired!");
}
};

// Execute the timer to expire 2 seconds in the future
timer.schedule(2000);
// Execute the timer to expire 2 seconds in the future
timer.schedule(2000);
```

Notice that the timer will not have a chance to execute the run() method until after control returns to the JavaScript event loop.
Expand Down Expand Up @@ -169,14 +169,14 @@ it to [Scheduler.scheduleDeferred](/javadoc/latest/com/google/gwt/core/client/Sc
```java
TextBox dataEntry;

// Set the focus on the widget after setup completes.
Scheduler.get().scheduleDeferred(new Command() {
public void execute () {
dataEntry.setFocus();
}
});
// Set the focus on the widget after setup completes.
Scheduler.get().scheduleDeferred(new Command() {
public void execute () {
dataEntry.setFocus();
}
});

dataEntry = new TextBox();
dataEntry = new TextBox();
```

## Avoiding Slow Script Warnings: the IncrementalCommand class<a id="incremental"></a>
Expand Down
46 changes: 23 additions & 23 deletions src/main/markdown/doc/latest/DevGuideCodingBasicsFormatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,36 +27,36 @@ For most cases, you probably want to use the default decimal format:

```java
NumberFormat fmt = NumberFormat.getDecimalFormat();
double value = 12345.6789;
String formatted = fmt.format(value);
// Prints 1,2345.6789 in the default locale
GWT.log("Formatted string is" + formatted, null);
double value = 12345.6789;
String formatted = fmt.format(value);
// Prints 1,2345.6789 in the default locale
GWT.log("Formatted string is" + formatted, null);
```

The class can also be used to convert a numeric string back into a double:

```java
double value = NumberFormat.getDecimalFormat().parse("12345.6789");
GWT.log("Parsed value is" + value, null);
GWT.log("Parsed value is" + value, null);
```

The `NumberFormat` class also provides defaults for scientific notation:

```java
double value = 12345.6789;
String formatted = NumberFormat.getScientificFormat().format(value);
// prints 1.2345E4 in the default locale
GWT.log("Formatted string is" + formatted, null);
String formatted = NumberFormat.getScientificFormat().format(value);
// prints 1.2345E4 in the default locale
GWT.log("Formatted string is" + formatted, null);
```

Note that you can also specify your own pattern for formatting numbers. In the example below, we want to show 6 digits of precision on the right hand side of the decimal and
format the left hand side with zeroes up to the hundred thousands place:

```java
double value = 12345.6789;
String formatted = NumberFormat.getFormat("000000.000000").format(value);
// prints 012345.678900 in the default locale
GWT.log("Formatted string is" + formatted, null);
String formatted = NumberFormat.getFormat("000000.000000").format(value);
// prints 012345.678900 in the default locale
GWT.log("Formatted string is" + formatted, null);
```

Here are the most commonly used pattern symbols for decimal formats:
Expand Down Expand Up @@ -86,23 +86,23 @@ For the `DateTimeFormat` class, there are a large number of default formats defi
```java
Date today = new Date();

// prints Tue Dec 18 12:01:26 GMT-500 2007 in the default locale.
GWT.log(today.toString(), null);
// prints Tue Dec 18 12:01:26 GMT-500 2007 in the default locale.
GWT.log(today.toString(), null);

// prints 12/18/07 in the default locale
GWT.log(DateTimeFormat.getShortDateFormat().format(today), null);
// prints 12/18/07 in the default locale
GWT.log(DateTimeFormat.getShortDateFormat().format(today), null);

// prints December 18, 2007 in the default locale
GWT.log(DateTimeFormat.getLongDateFormat().format(today), null);
// prints December 18, 2007 in the default locale
GWT.log(DateTimeFormat.getLongDateFormat().format(today), null);

// prints 12:01 PM in the default locale
GWT.log(DateTimeFormat.getShortTimeFormat().format(today), null);
// prints 12:01 PM in the default locale
GWT.log(DateTimeFormat.getShortTimeFormat().format(today), null);

// prints 12:01:26 PM GMT-05:00 in the default locale
GWT.log(DateTimeFormat.getLongTimeFormat().format(today), null);
// prints 12:01:26 PM GMT-05:00 in the default locale
GWT.log(DateTimeFormat.getLongTimeFormat().format(today), null);

// prints Dec 18, 2007 12:01:26 PM in the default locale
GWT.log(DateTimeFormat.getMediumDateTimeFormat().format(today), null);
// prints Dec 18, 2007 12:01:26 PM in the default locale
GWT.log(DateTimeFormat.getMediumDateTimeFormat().format(today), null);
```

Like the `NumberFormat` class, you can also use this class to parse a date from a `String` into a `Date` representation. You also have the option of using
Expand Down
33 changes: 16 additions & 17 deletions src/main/markdown/doc/latest/DevGuideCodingBasicsJSNI.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,14 @@ public static native int badExample() /*-{
return "Not A Number";
}-*/;

public void onClick () {
try {
int myValue = badExample();
GWT.log("Got value " + myValue, null);
} catch (Exception e) {
GWT.log("JSNI method badExample() threw an exception:", e);
}
}
public void onClick() {
try {
int myValue = badExample();
GWT.log("Got value " + myValue, null);
} catch (Exception e) {
GWT.log("JSNI method badExample() threw an exception:", e);
}
}
```

This example compiles as Java, and its syntax is verified by the GWT compiler
Expand Down Expand Up @@ -208,7 +208,7 @@ public class JSNIExample {
## Calling a Java Method from Handwritten JavaScript<a id="calling"></a>

Sometimes you need to access a method or constructor defined in GWT from outside JavaScript code. This code might be hand-written and included in another java script file, or
Sometimes you need to access a method or constructor defined in GWT from outside JavaScript code. This code might be hand-written and included in another JavaScript file, or
it could be a part of a third party library. In this case, the GWT compiler will not get a chance to build an interface between your JavaScript code and the GWT generated
JavaScript directly.

Expand All @@ -218,14 +218,13 @@ JavaScript code.
```java
package mypackage;

public MyUtilityClass
{
public static int computeLoanInterest(int amt, float interestRate,
int term) { ... }
public static native void exportStaticMethod() /*-{
$wnd.computeLoanInterest =
$entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
public class MyUtilityClass {
public static int computeLoanInterest(int amt, float interestRate,
int term) { ... }
public static native void exportStaticMethod() /*-{
$wnd.computeLoanInterest =
$entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
}
```

Expand Down
19 changes: 11 additions & 8 deletions src/main/markdown/doc/latest/DevGuideCodingBasicsJsInterop.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,25 @@ package com.gwt.example;
@JsType
public class MyClass {

public String name;
public String name;

public MyClass(String name) {
this.name = name;
}
public MyClass(String name) {
this.name = name;
}

public void sayHello() {
return "Hello" + this.name;
}
public String sayHello() {
return "Hello " + this.name;
}
}
```

From the JS script, the object can be used as a JS object:

```javascript
//the package name serves as a JS namespace
// Note that exporting of Java Objects to JavaScript to be accessed by their
// namespace (e.g. this sample) requires -generateJsInteropExports flag.

// the package name serves as a JS namespace
var aClass = new com.gwt.example.MyClass('World');

console.log(aClass.sayHello());
Expand Down
12 changes: 6 additions & 6 deletions src/main/markdown/doc/latest/DevGuideI18nMessages.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ The following code implements an alert dialog by substituting values into the me

```java
public interface ErrorMessages extends Messages {
String permissionDenied(int errorCode, String username);
}
ErrorMessages msgs = GWT.create(ErrorMessages.class)
String permissionDenied(int errorCode, String username);
}
ErrorMessages msgs = GWT.create(ErrorMessages.class)

void permissionDenied(int errorVal, String loginId) {
Window.alert(msgs.permissionDenied(errorVal, loginId));
}
void permissionDenied(int errorVal, String loginId) {
Window.alert(msgs.permissionDenied(errorVal, loginId));
}
```

**Caution:** Be advised that the rules for using quotes may be a bit confusing. Refer to the [MessageFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html) javadoc for more details.
Expand Down
58 changes: 31 additions & 27 deletions src/main/markdown/doc/latest/DevGuideTesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,10 @@ If you prefer not to use webAppCreator, you may create a test case suite by hand
2. **If you do not have a GWT module yet, create a [module](DevGuideOrganizingProjects.html#DevGuideModules) that causes the source for your test case to be included.** If you are adding a test case to an existing GWT app, you can just use the existing module.
3. **Implement the method [GWTTestCase.getModuleName()](/javadoc/latest/com/google/gwt/junit/client/GWTTestCase.html#getModuleName--) to return the fully-qualified name of the module.** This is the glue that tells the JUnit test case which module to instantiate.
4. **Compile your test case class to bytecode.** You can use the Java compiler directly using [javac](http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javac.html) or a Java IDE such as [Eclipse](http://eclipse.org).
5. **Run your test case.** Use the class `junit.textui.TestRunner` as your main class and pass the full name of your test class as the command line argument, e.g. `com.example.foo.client.FooTest`. When running the test case, make sure your classpath includes:
6. * Your project's `src` directory
5. **Run your test case.** Use the class `junit.textui.TestRunner` as your main
class and pass the full name of your test class as the command line argument,
e.g. `com.example.foo.client.FooTest`. When running the test case, make sure your classpath includes:
* Your project's `src` directory
* Your project's `bin` directory
* The `gwt-user.jar` library
* The `gwt-dev.jar` library
Expand Down Expand Up @@ -211,9 +213,11 @@ there are [some differences between Java and JavaScript](DevGuideCodingBasics.ht
that could cause your code to produce different results when deployed.

If you instead decide to run the JUnit TestRunner from the command line,
you need to [pass arguments](#passingTestArguments) to `JUnitShell` to get your unit tests running in (legacy) development mode
you need to [pass arguments](#passingTestArguments) to `JUnitShell` to get your unit tests running in (legacy) development mode:

`-Dgwt.args="-devMode"`
```
-Dgwt.args="-devMode"
```

### Running your test in Manual Mode<a id="Manual_Mode"></a>

Expand Down Expand Up @@ -353,32 +357,32 @@ The following example shows how to defensively cleanup the DOM before the next t

```java
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

private static native String getNodeName(Element elem) /*-{
return (elem.nodeName || "").toLowerCase();
}-*/;

/**
* Removes all elements in the body, except scripts and iframes.
*/
public void gwtSetUp () {
Element bodyElem = RootPanel.getBodyElement();

List<Element> toRemove = new ArrayList<Element>();
for (int i = 0, n = DOM.getChildCount(bodyElem); i < n; ++i) {
Element elem = DOM.getChild(bodyElem, i);
String nodeName = getNodeName(elem);
if (!"script".equals(nodeName) &amp;&amp; !"iframe".equals(nodeName)) {
toRemove.add(elem);
}
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

private static native String getNodeName(Element elem) /*-{
return (elem.nodeName || "").toLowerCase();
}-*/;

/**
* Removes all elements in the body, except scripts and iframes.
*/
public void gwtSetUp () {
Element bodyElem = RootPanel.getBodyElement();

List<Element> toRemove = new ArrayList<Element>();
for (int i = 0, n = DOM.getChildCount(bodyElem); i < n; ++i) {
Element elem = DOM.getChild(bodyElem, i);
String nodeName = getNodeName(elem);
if (!"script".equals(nodeName) && !"iframe".equals(nodeName)) {
toRemove.add(elem);
}
}

for (int i = 0, n = toRemove.size(); i < n; ++i) {
DOM.removeChild(bodyElem, toRemove.get(i));
}
for (int i = 0, n = toRemove.size(); i < n; ++i) {
DOM.removeChild(bodyElem, toRemove.get(i));
}
}
```

## Running Tests in Eclipse<a id="DevGuideRunningTestsInEclipse"></a>
Expand Down
Loading

0 comments on commit 8d6c5ec

Please sign in to comment.