Replace old code samples with new ones

This commit is contained in:
konsoletyper 2014-10-05 15:45:44 +04:00
parent 4f668d4d43
commit 9e09c247e6
34 changed files with 1026 additions and 705 deletions

View File

@ -44,7 +44,6 @@
</module> </module>
<module name="UpperEll"/> <module name="UpperEll"/>
<module name="ArrayTypeStyle"/> <module name="ArrayTypeStyle"/>
<module name="TrailingComment"/>
<module name="RedundantModifier"/> <module name="RedundantModifier"/>
<module name="ClassTypeParameterName"/> <module name="ClassTypeParameterName"/>
<module name="LocalFinalVariableName"/> <module name="LocalFinalVariableName"/>

12
pom.xml
View File

@ -222,8 +222,6 @@
<id>validate</id> <id>validate</id>
<phase>validate</phase> <phase>validate</phase>
<configuration> <configuration>
<propertyExpansion>config_loc=${basedir}/..</propertyExpansion>
<configLocation>../checkstyle.xml</configLocation>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput> <consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError> <failsOnError>true</failsOnError>
@ -234,6 +232,10 @@
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration>
<propertyExpansion>config_loc=${basedir}/..</propertyExpansion>
<configLocation>../checkstyle.xml</configLocation>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
@ -266,12 +268,6 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>enable-scala</id>
<modules>
<module>teavm-scala-samples</module>
</modules>
</profile>
<profile> <profile>
<id>enable-samples</id> <id>enable-samples</id>
<modules> <modules>

View File

@ -26,6 +26,9 @@
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>TeaVM Java class library</name>
<description>TeaVM Java class library emulation</description>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@ -49,9 +52,6 @@
</dependency> </dependency>
</dependencies> </dependencies>
<name>TeaVM JCL</name>
<description>TeaVM Java class library emulation</description>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>

View File

@ -17,9 +17,9 @@
* Represents a class model that is alternative to {@link java.lang.reflection} package. * Represents a class model that is alternative to {@link java.lang.reflection} package.
* Model is suitable for representing classes that are not in class path. Also * Model is suitable for representing classes that are not in class path. Also
* it allows to disassemble method bodies into three-address code that is very * it allows to disassemble method bodies into three-address code that is very
* close to JVM bytecode (see {@link org.teavm.instructions}. * close to JVM bytecode (see {@link org.teavm.model.instructions}.
* *
* <p>The entry point is some implementation of {@link ClassHolderSource} interface. * <p>The entry point is some implementation of {@link org.teavm.model.ClassHolderSource} interface.
* *
*/ */
package org.teavm.model; package org.teavm.model;

View File

@ -16,6 +16,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.teavm</groupId> <groupId>org.teavm</groupId>
<artifactId>teavm</artifactId> <artifactId>teavm</artifactId>
@ -23,108 +24,13 @@
</parent> </parent>
<artifactId>teavm-samples</artifactId> <artifactId>teavm-samples</artifactId>
<dependencies> <packaging>pom</packaging>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-dom</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build> <name>TeaVM samples</name>
<plugins> <description>TeaVM code samples</description>
<plugin>
<groupId>org.apache.maven.plugins</groupId> <modules>
<artifactId>maven-checkstyle-plugin</artifactId> <module>teavm-samples-hello</module>
<configuration> <module>teavm-samples-benchmark</module>
<configLocation>../checkstyle.xml</configLocation> </modules>
</configuration>
</plugin>
<plugin>
<groupId>org.teavm</groupId>
<artifactId>teavm-maven-plugin</artifactId>
<version>${project.version}</version>
<dependencies>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-classlib</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>generate-hello</id>
<goals>
<goal>build-javascript</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<minifying>false</minifying>
<mainClass>org.teavm.samples.HelloWorld</mainClass>
<mainPageIncluded>true</mainPageIncluded>
<debugInformationGenerated>true</debugInformationGenerated>
<sourceMapsGenerated>true</sourceMapsGenerated>
<sourceFilesCopied>true</sourceFilesCopied>
<targetDirectory>${project.build.directory}/javascript/hello</targetDirectory>
</configuration>
</execution>
<execution>
<id>generate-matrix</id>
<goals>
<goal>build-javascript</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<minifying>false</minifying>
<mainClass>org.teavm.samples.MatrixMultiplication</mainClass>
<mainPageIncluded>true</mainPageIncluded>
<debugInformationGenerated>true</debugInformationGenerated>
<sourceMapsGenerated>true</sourceMapsGenerated>
<targetDirectory>${project.build.directory}/javascript/matrix</targetDirectory>
</configuration>
</execution>
<execution>
<id>generate-datetime</id>
<goals>
<goal>build-javascript</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<minifying>false</minifying>
<mainClass>org.teavm.samples.DateTime</mainClass>
<targetDirectory>${project.build.directory}/javascript/datetime</targetDirectory>
<debugInformationGenerated>true</debugInformationGenerated>
<sourceMapsGenerated>true</sourceMapsGenerated>
<properties>
<java.util.Locale.available>en_US,en_GB,ru_RU,ru_UA,nl_NL,nl_BE</java.util.Locale.available>
</properties>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/teavm-demos.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -1,24 +0,0 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>teavm-demos</id>
<formats>
<format>zip</format>
</formats>
<files>
<file>
<source>src/main/resources/datetime.html</source>
<outputDirectory>/</outputDirectory>
</file>
<file>
<source>${project.build.directory}/javascript/datetime/classes.js</source>
<outputDirectory>/</outputDirectory>
<destName>datetime.js</destName>
</file>
<file>
<source>${project.build.directory}/javascript/datetime/runtime.js</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
</assembly>

View File

@ -1,167 +0,0 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import org.teavm.dom.browser.TimerHandler;
import org.teavm.dom.browser.Window;
import org.teavm.dom.events.Event;
import org.teavm.dom.events.EventListener;
import org.teavm.dom.html.HTMLDocument;
import org.teavm.dom.html.HTMLInputElement;
import org.teavm.dom.html.HTMLOptionElement;
import org.teavm.dom.html.HTMLSelectElement;
import org.teavm.jso.JS;
/**
*
* @author Alexey Andreev <konsoletyper@gmail.com>
*/
public final class DateTime {
private DateTime() {
}
private static Window window = (Window)JS.getGlobal();
private static HTMLDocument document = window.getDocument();
private static HTMLSelectElement localeElem = (HTMLSelectElement)document.getElementById("locale");
private static HTMLSelectElement formatElem = (HTMLSelectElement)document.getElementById("format");
private static HTMLSelectElement customFormatElem = (HTMLSelectElement)document.getElementById("custom-format");
private static Date currentDate = new Date();
private static Locale[] locales;
private static Locale currentLocale;
private static DateFormat dateFormat;
public static void main(String[] args) {
fillLocales();
window.setInterval(new TimerHandler() {
@Override public void onTimer() {
updateCurrentTime();
}
}, 250);
updateCurrentLocale();
updateFormat();
formatElem.addEventListener("change", new EventListener() {
@Override public void handleEvent(Event evt) {
updateFormat();
updateCurrentTimeText();
}
});
customFormatElem.addEventListener("change", new EventListener() {
@Override public void handleEvent(Event evt) {
updateFormat();
updateCurrentTimeText();
}
});
}
private static void fillLocales() {
locales = Locale.getAvailableLocales();
for (Locale locale : locales) {
HTMLOptionElement option = (HTMLOptionElement)document.createElement("option");
option.setValue(locale.toString());
option.setLabel(locale.getDisplayName(Locale.getDefault()));
localeElem.getOptions().add(option);
}
localeElem.addEventListener("change", new EventListener() {
@Override public void handleEvent(Event evt) {
updateCurrentLocale();
updateFormat();
updateCurrentTimeText();
}
});
}
private static void updateCurrentLocale() {
currentLocale = locales[localeElem.getSelectedIndex()];
GregorianCalendar calendar = new GregorianCalendar(currentLocale);
HTMLInputElement weekStartElem = (HTMLInputElement)document.getElementById("week-start");
weekStartElem.setValue(String.valueOf(calendar.getFirstDayOfWeek()));
HTMLInputElement weekLengthElem = (HTMLInputElement)document.getElementById("week-length");
weekLengthElem.setValue(String.valueOf(calendar.getMinimalDaysInFirstWeek()));
}
private static void updateCurrentTime() {
setCurrentTime(new Date());
}
private static void setCurrentTime(Date date) {
currentDate = date;
updateCurrentTimeText();
}
private static void updateCurrentTimeText() {
HTMLInputElement timeElem = (HTMLInputElement)document.getElementById("current-time");
try {
timeElem.setValue(dateFormat.format(currentDate));
} catch (RuntimeException e) {
timeElem.setValue("Error formatting date");
}
}
private static void updateFormat() {
customFormatElem.setDisabled(true);
switch (formatElem.getValue()) {
case "short-date":
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, currentLocale);
break;
case "medium-date":
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, currentLocale);
break;
case "long-date":
dateFormat = DateFormat.getDateInstance(DateFormat.LONG, currentLocale);
break;
case "full-date":
dateFormat = DateFormat.getDateInstance(DateFormat.FULL, currentLocale);
break;
case "short-time":
dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, currentLocale);
break;
case "medium-time":
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, currentLocale);
break;
case "long-time":
dateFormat = DateFormat.getTimeInstance(DateFormat.LONG, currentLocale);
break;
case "full-time":
dateFormat = DateFormat.getTimeInstance(DateFormat.FULL, currentLocale);
break;
case "short-datetime":
dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, currentLocale);
break;
case "medium-datetime":
dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, currentLocale);
break;
case "long-datetime":
dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, currentLocale);
break;
case "full-datetime":
dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, currentLocale);
break;
case "custom":
customFormatElem.setDisabled(false);
try {
dateFormat = new SimpleDateFormat(customFormatElem.getValue(), currentLocale);
} catch (IllegalArgumentException e) {
dateFormat = new SimpleDateFormat("'Invalid pattern'");
}
break;
}
}
}

View File

@ -1,84 +0,0 @@
/*
* Copyright 2013 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples;
import org.teavm.dom.browser.Window;
import org.teavm.dom.core.Document;
import org.teavm.dom.core.Element;
import org.teavm.dom.events.Event;
import org.teavm.dom.events.EventListener;
import org.teavm.dom.events.EventTarget;
import org.teavm.jso.JS;
/**
*
* @author Alexey Andreev
*/
public final class HelloWorld {
private HelloWorld() {
}
private static Window window;
private static Document document;
private static Element body;
public static void main(String[] args) {
window = (Window)JS.getGlobal();
document = window.getDocument();
body = document.getDocumentElement().getElementsByTagName("body").item(0);
createButton();
}
private static void createButton() {
Element elem = document.createElement("div");
body.appendChild(elem);
final Element button = document.createElement("button");
button.appendChild(document.createTextNode("Click me!"));
elem.appendChild(button);
((EventTarget)button).addEventListener("click", new EventListener() {
@Override public void handleEvent(Event evt) {
button.getParentNode().removeChild(button);
printHelloWorld();
}
}, false);
}
private static void printHelloWorld() {
println("Hello, world!");
println("Here is the Fibonacci sequence:");
long a = 0;
long b = 1;
for (int i = 0; i < 70; ++i) {
println(a);
long c = a + b;
a = b;
b = c;
}
println("And so on...");
}
private static void println(Object obj) {
Element elem = document.createElement("div");
elem.appendChild(document.createTextNode(String.valueOf(obj)));
body.appendChild(elem);
}
private static void println(long val) {
Element elem = document.createElement("div");
elem.appendChild(document.createTextNode(String.valueOf(val)));
body.appendChild(elem);
}
}

View File

@ -1,128 +0,0 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file is based on the original source code from Bck2Brwsr
/**
* Back 2 Browser Bytecode Translator
* Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://opensource.org/licenses/GPL-2.0.
*/
package org.teavm.samples;
import java.io.IOException;
import java.util.Arrays;
/**
*
* @author Alexey Andreev
*/
public class Matrix {
private final int rank;
private final float[][] data;
public Matrix(int r) {
this(r, new float[r][r]);
}
private Matrix(int r, float[][] data) {
this.rank = r;
this.data = data;
}
public void setElement(int i, int j, float value) {
data[i][j] = value;
}
public float getElement(int i, int j) {
return data[i][j];
}
public void generateData() {
//final Random rand = new Random();
//final int x = 10;
for (int i = 0; i < rank; i++) {
for (int j = 0; j < rank; j++) {
data[i][j] = 1 / (1 + i + j);
}
}
}
public Matrix multiply(Matrix m) {
if (rank != m.rank) {
throw new IllegalArgumentException("Rank doesn't match");
}
final float[][] res = new float[rank][rank];
for (int i = 0; i < rank; i++) {
for (int j = 0; j < rank; j++) {
float ij = 0;
for (int q = 0; q < rank; q++) {
ij += data[i][q] * m.data[q][j];
}
res[i][j] = ij;
}
}
return new Matrix(rank, res);
}
public void printOn(Appendable s) throws IOException {
for (int i = 0; i < rank; i++) {
String sep = "";
for (int j = 0; j < rank; j++) {
s.append(sep + data[i][j]);
sep = " ";
}
s.append("\n");
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Matrix) {
Matrix snd = (Matrix)obj;
if (snd.rank != rank) {
return false;
}
for (int i = 0; i < rank; i++) {
for (int j = 0; j < rank; j++) {
if (data[i][j] != snd.data[i][j]) {
return false;
}
}
}
return true;
}
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + this.rank;
hash = 97 * hash + Arrays.deepHashCode(this.data);
return hash;
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples;
import java.io.IOException;
/**
*
* @author Alexey Andreev
*/
public final class MatrixMultiplication {
private MatrixMultiplication() {
}
public static void main(String[] args) throws IOException {
for (int k = 0; k < 20; ++k) {
long startTime = System.currentTimeMillis();
Matrix m1 = new Matrix(5);
Matrix m2 = new Matrix(5);
m1.generateData();
m2.generateData();
Matrix res = null;
for (int i = 0; i < 10000; i++) {
res = m1.multiply(m2);
m1 = res;
}
StringBuilder sb = new StringBuilder();
res.printOn(sb);
long timeSpent = System.currentTimeMillis() - startTime;
System.out.println(sb.toString());
System.out.println("Time spent: " + timeSpent);
}
}
}

View File

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Localized date & time demo application</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="runtime.js" type="text/javascript"></script>
<script src="datetime.js" type="text/javascript"></script>
</head>
<body onload="main()">
<div>
<label for="locale">Pick a locale:</label>
<select id="locale" size="1"></select>
</div>
<div>
<label for="current-time">Current time is:</label>
<input type="text" id="current-time" readonly size="50">
</div>
<div>
<label for="week-start">Week starts at:</label>
<input type="text" id="week-start" readonly size="5">
<label for="week-length">, first week length is:</label>
<input type="text" id="week-length" readonly size="5">
</div>
<div>
<label for="format">Format:</label>
<select id="format" size="1">
<option value="short-date">Date (short)</option>
<option value="medium-date">Date (medium)</option>
<option value="long-date">Date (long)</option>
<option value="full-date">Date (full)</option>
<option value="short-time">Time (short)</option>
<option value="medium-time">Time (medium)</option>
<option value="long-time">Time (long)</option>
<option value="full-time">Time (full)</option>
<option value="short-datetime">Date and time (short)</option>
<option value="medium-datetime">Date and (medium)</option>
<option value="long-datetime">Date and time (long)</option>
<option value="full-datetime">Date and time (full)</option>
<option value="custom">Custom</option>
</select>
<input type="text" id="custom-format" disabled value="yyyy-MM-dd HH:mm:ss">
</div>
</body>
</html>

View File

@ -2,4 +2,3 @@
/.settings /.settings
/.classpath /.classpath
/.project /.project
/.cache

View File

@ -0,0 +1,136 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.teavm</groupId>
<artifactId>teavm-samples</artifactId>
<version>0.2-SNAPSHOT</version>
</parent>
<artifactId>teavm-samples-benchmark</artifactId>
<packaging>war</packaging>
<name>TeaVM performance benchmark</name>
<description>Compares performance of the JavaScript code produced by TeaVM and GWT</description>
<dependencies>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-classlib</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-jso</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-dom</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jbox2d</groupId>
<artifactId>jbox2d-library</artifactId>
<version>2.2.1.1</version>
</dependency>
<dependency>
<groupId>org.jbox2d</groupId>
<artifactId>jbox2d-library</artifactId>
<version>2.2.1.1</version>
<classifier>sources</classifier>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>2.6.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<webResources>
<resource>
<directory>${project.build.directory}/generated/js</directory>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.teavm</groupId>
<artifactId>teavm-maven-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<id>web-client</id>
<phase>prepare-package</phase>
<goals>
<goal>build-javascript</goal>
</goals>
<configuration>
<targetDirectory>${project.build.directory}/generated/js/teavm</targetDirectory>
<mainClass>org.teavm.samples.benchmark.teavm.BenchmarkStarter</mainClass>
<runtime>SEPARATE</runtime>
<minifying>true</minifying>
<debugInformationGenerated>true</debugInformationGenerated>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>2.6.1</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<optimizationLevel>9</optimizationLevel>
<compileSourcesArtifacts>
<item>org.jbox2d:jbox2d-library</item>
</compileSourcesArtifacts>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>../../checkstyle.xml</configLocation>
<propertyExpansion>config_loc=${basedir}/../..</propertyExpansion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,158 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.benchmark;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.joints.RevoluteJointDef;
/**
*
* @author Alexey Andreev <konsoletyper@gmail.com>
*/
public class Scene {
private World world;
private Body axis;
private Body reel;
private long lastCalculated;
private long startTime;
public Scene() {
world = new World(new Vec2(0, -9.8f));
initAxis();
initReel();
joinReelToAxis();
initBalls();
lastCalculated = System.currentTimeMillis();
startTime = lastCalculated;
}
private void initAxis() {
BodyDef axisDef = new BodyDef();
axisDef.type = BodyType.STATIC;
axisDef.position = new Vec2(3, 3);
axis = world.createBody(axisDef);
CircleShape axisShape = new CircleShape();
axisShape.setRadius(0.02f);
axisShape.m_p.set(0, 0);
FixtureDef axisFixture = new FixtureDef();
axisFixture.shape = axisShape;
axis.createFixture(axisFixture);
}
private void initReel() {
BodyDef reelDef = new BodyDef();
reelDef.type = BodyType.DYNAMIC;
reelDef.position = new Vec2(3, 3);
reel = world.createBody(reelDef);
FixtureDef fixture = new FixtureDef();
fixture.friction = 0.5f;
fixture.restitution = 0.4f;
fixture.density = 1;
int parts = 30;
for (int i = 0; i < parts; ++i) {
PolygonShape shape = new PolygonShape();
double angle1 = i / (double)parts * 2 * Math.PI;
double x1 = 2.7 * Math.cos(angle1);
double y1 = 2.7 * Math.sin(angle1);
double angle2 = (i + 1) / (double)parts * 2 * Math.PI;
double x2 = 2.7 * Math.cos(angle2);
double y2 = 2.7 * Math.sin(angle2);
double angle = (angle1 + angle2) / 2;
double x = 0.01 * Math.cos(angle);
double y = 0.01 * Math.sin(angle);
shape.set(new Vec2[] { new Vec2((float)x1, (float)y1), new Vec2((float)x2, (float)y2),
new Vec2((float)(x2 - x), (float)(y2 - y)), new Vec2((float)(x1 - x), (float)(y1 - y)) }, 4);
fixture.shape = shape;
reel.createFixture(fixture);
}
}
private void initBalls() {
float ballRadius = 0.15f;
BodyDef ballDef = new BodyDef();
ballDef.type = BodyType.DYNAMIC;
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.3f;
fixtureDef.density = 0.2f;
CircleShape shape = new CircleShape();
shape.m_radius = ballRadius;
fixtureDef.shape = shape;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
float x = (j + 0.5f) * (ballRadius * 2 + 0.01f);
float y = (i + 0.5f) * (ballRadius * 2 + 0.01f);
ballDef.position.x = 3 + x;
ballDef.position.y = 3 + y;
Body body = world.createBody(ballDef);
body.createFixture(fixtureDef);
ballDef.position.x = 3 - x;
ballDef.position.y = 3 + y;
body = world.createBody(ballDef);
body.createFixture(fixtureDef);
ballDef.position.x = 3 + x;
ballDef.position.y = 3 - y;
body = world.createBody(ballDef);
body.createFixture(fixtureDef);
ballDef.position.x = 3 - x;
ballDef.position.y = 3 - y;
body = world.createBody(ballDef);
body.createFixture(fixtureDef);
}
}
}
private void joinReelToAxis() {
RevoluteJointDef jointDef = new RevoluteJointDef();
jointDef.bodyA = axis;
jointDef.bodyB = reel;
world.createJoint(jointDef);
}
public void calculate() {
long currentTime = System.currentTimeMillis();
int timeToCalculate = (int)(currentTime - lastCalculated);
long relativeTime = currentTime - startTime;
while (timeToCalculate > 10) {
int period = (int)((relativeTime + 5000) / 10000);
reel.applyTorque(period % 2 == 0 ? 8f : -8f);
world.step(0.01f, 20, 40);
lastCalculated += 10;
timeToCalculate -= 10;
}
}
public int timeUntilNextStep() {
return (int)Math.max(0, lastCalculated + 10 - System.currentTimeMillis());
}
public World getWorld() {
return world;
}
}

View File

@ -0,0 +1,118 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.benchmark.gwt;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.collision.shapes.Shape;
import org.jbox2d.collision.shapes.ShapeType;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.Fixture;
import org.teavm.samples.benchmark.Scene;
public class BenchmarkStarter implements EntryPoint {
private Document document;
private CanvasElement canvas;
private Element resultTableBody;
private Scene scene = new Scene();
private static int currentSecond;
private static long startMillisecond;
private static double timeSpentCalculating;
@Override
public void onModuleLoad() {
document = RootPanel.getBodyElement().getOwnerDocument();
canvas = (CanvasElement)document.getElementById("benchmark-canvas");
resultTableBody = document.getElementById("result-table-body");
startMillisecond = System.currentTimeMillis();
makeStep();
}
private void makeStep() {
double start = Performance.now();
scene.calculate();
double end = Performance.now();
int second = (int)((System.currentTimeMillis() - startMillisecond) / 1000);
if (second > currentSecond) {
Element row = document.createElement("tr");
resultTableBody.appendChild(row);
Element secondCell = document.createElement("td");
row.appendChild(secondCell);
secondCell.appendChild(document.createTextNode(String.valueOf(second)));
Element timeCell = document.createElement("td");
row.appendChild(timeCell);
timeCell.appendChild(document.createTextNode(String.valueOf(timeSpentCalculating)));
timeSpentCalculating = 0;
currentSecond = second;
}
timeSpentCalculating += end - start;
render();
new Timer() {
@Override public void run() {
makeStep();
}
}.schedule(scene.timeUntilNextStep());
}
private void render() {
Context2d context = canvas.getContext2d();
context.setFillStyle("white");
context.setStrokeStyle("grey");
context.fillRect(0, 0, 600, 600);
context.save();
context.translate(0, 600);
context.scale(1, -1);
context.scale(100, 100);
context.setLineWidth(0.01);
for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) {
Vec2 center = body.getPosition();
context.save();
context.translate(center.x, center.y);
context.rotate(body.getAngle());
for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {
Shape shape = fixture.getShape();
if (shape.getType() == ShapeType.CIRCLE) {
CircleShape circle = (CircleShape)shape;
context.beginPath();
context.arc(circle.m_p.x, circle.m_p.y, circle.getRadius(), 0, Math.PI * 2, true);
context.closePath();
context.stroke();
} else if (shape.getType() == ShapeType.POLYGON) {
PolygonShape poly = (PolygonShape)shape;
Vec2[] vertices = poly.getVertices();
context.beginPath();
context.moveTo(vertices[0].x, vertices[0].y);
for (int i = 1; i < poly.getVertexCount(); ++i) {
context.lineTo(vertices[i].x, vertices[i].y);
}
context.closePath();
context.stroke();
}
}
context.restore();
}
context.restore();
}
}

View File

@ -0,0 +1,25 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.benchmark.gwt;
public final class Performance {
private Performance() {
}
public static native double now() /*-{
return $wnd.performance.now();
}-*/;
}

View File

@ -0,0 +1,123 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.benchmark.teavm;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.collision.shapes.Shape;
import org.jbox2d.collision.shapes.ShapeType;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.Fixture;
import org.teavm.dom.browser.TimerHandler;
import org.teavm.dom.browser.Window;
import org.teavm.dom.canvas.CanvasRenderingContext2D;
import org.teavm.dom.html.HTMLCanvasElement;
import org.teavm.dom.html.HTMLDocument;
import org.teavm.dom.html.HTMLElement;
import org.teavm.jso.JS;
import org.teavm.samples.benchmark.Scene;
/**
*
* @author Alexey Andreev <konsoletyper@gmail.com>
*/
public final class BenchmarkStarter {
private static Window window = (Window)JS.getGlobal();
private static HTMLDocument document = window.getDocument();
private static HTMLCanvasElement canvas = (HTMLCanvasElement)document.getElementById("benchmark-canvas");
private static HTMLElement resultTableBody = document.getElementById("result-table-body");
private static Performance performance = (Performance)JS.get(window, JS.wrap("performance"));
private static Scene scene = new Scene();
private static int currentSecond;
private static long startMillisecond;
private static double timeSpentCalculating;
private BenchmarkStarter() {
}
public static void main(String[] args) {
startMillisecond = System.currentTimeMillis();
makeStep();
}
private static void makeStep() {
double start = performance.now();
scene.calculate();
double end = performance.now();
int second = (int)((System.currentTimeMillis() - startMillisecond) / 1000);
if (second > currentSecond) {
HTMLElement row = document.createElement("tr");
resultTableBody.appendChild(row);
HTMLElement secondCell = document.createElement("td");
row.appendChild(secondCell);
secondCell.appendChild(document.createTextNode(String.valueOf(second)));
HTMLElement timeCell = document.createElement("td");
row.appendChild(timeCell);
timeCell.appendChild(document.createTextNode(String.valueOf(timeSpentCalculating)));
timeSpentCalculating = 0;
currentSecond = second;
}
timeSpentCalculating += end - start;
render();
window.setTimeout(new TimerHandler() {
@Override public void onTimer() {
makeStep();
}
}, scene.timeUntilNextStep());
}
private static void render() {
CanvasRenderingContext2D context = (CanvasRenderingContext2D)canvas.getContext("2d");
context.setFillStyle("white");
context.setStrokeStyle("grey");
context.fillRect(0, 0, 600, 600);
context.save();
context.translate(0, 600);
context.scale(1, -1);
context.scale(100, 100);
context.setLineWidth(0.01);
for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) {
Vec2 center = body.getPosition();
context.save();
context.translate(center.x, center.y);
context.rotate(body.getAngle());
for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {
Shape shape = fixture.getShape();
if (shape.getType() == ShapeType.CIRCLE) {
CircleShape circle = (CircleShape)shape;
context.beginPath();
context.arc(circle.m_p.x, circle.m_p.y, circle.getRadius(), 0, Math.PI * 2, true);
context.closePath();
context.stroke();
} else if (shape.getType() == ShapeType.POLYGON) {
PolygonShape poly = (PolygonShape)shape;
Vec2[] vertices = poly.getVertices();
context.beginPath();
context.moveTo(vertices[0].x, vertices[0].y);
for (int i = 1; i < poly.getVertexCount(); ++i) {
context.lineTo(vertices[i].x, vertices[i].y);
}
context.closePath();
context.stroke();
}
}
context.restore();
}
context.restore();
}
}

View File

@ -0,0 +1,22 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.benchmark.teavm;
import org.teavm.jso.JSObject;
public interface Performance extends JSObject {
double now();
}

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<module rename-to="benchmark">
<inherits name="com.google.gwt.user.User" />
<inherits name="org.jbox2d.JBox2D"/>
<source path=""/>
<source path="gwt"/>
<entry-point class="org.teavm.samples.benchmark.gwt.BenchmarkStarter"/>
</module>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>

View File

@ -0,0 +1,40 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>GWT jbox2d benchmark</title>
</head>
<body>
<script type="text/javascript" src="benchmark/benchmark.nocache.js"></script>
<iframe src="javascript:''" id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>
<h1>GWT performance</h1>
<div>
<canvas id="benchmark-canvas" width="600" height="600"></canvas>
</div>
<table>
<thead>
<tr>
<th>Second</th>
<th>Time spent computing, ms</th>
</tr>
</thead>
<tbody id="result-table-body">
</tbody>
</table>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>TeaVM vs. GWT performance comparison</title>
</head>
<body onload="main()">
<h1>TeaVM vs. GWT performance</h1>
<ul>
<li><a href="teavm.html">TeaVM</a></li>
<li><a href="gwt.html">GWT</a></li>
</ul>
</body>
</html>

View File

@ -0,0 +1,40 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>TeaVM jbox2d benchmark</title>
<script type="text/javascript" charset="utf-8" src="teavm/runtime.js"></script>
<script type="text/javascript" charset="utf-8" src="teavm/classes.js"></script>
</head>
<body onload="main()">
<h1>TeaVM performance</h1>
<div>
<canvas id="benchmark-canvas" width="600" height="600"></canvas>
</div>
<table>
<thead>
<tr>
<th>Second</th>
<th>Time spent computing, ms</th>
</tr>
</thead>
<tbody id="result-table-body">
</tbody>
</table>
</body>
</html>

View File

@ -0,0 +1,4 @@
/target
/.settings
/.classpath
/.project

View File

@ -0,0 +1,110 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.teavm</groupId>
<artifactId>teavm-samples</artifactId>
<version>0.2-SNAPSHOT</version>
</parent>
<artifactId>teavm-samples-hello</artifactId>
<packaging>war</packaging>
<name>TeaVM Hello world web application</name>
<description>A sample application that shows how TeaVM can communicate with the server</description>
<dependencies>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-classlib</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-jso</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-dom</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<webResources>
<resource>
<directory>${project.build.directory}/generated/js</directory>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.teavm</groupId>
<artifactId>teavm-maven-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<id>web-client</id>
<phase>prepare-package</phase>
<goals>
<goal>build-javascript</goal>
</goals>
<configuration>
<targetDirectory>${project.build.directory}/generated/js/teavm</targetDirectory>
<mainClass>org.teavm.samples.hello.Client</mainClass>
<runtime>SEPARATE</runtime>
<minifying>true</minifying>
<debugInformationGenerated>true</debugInformationGenerated>
<sourceMapsGenerated>true</sourceMapsGenerated>
<sourceFilesCopied>true</sourceFilesCopied>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>../../checkstyle.xml</configLocation>
<propertyExpansion>config_loc=${basedir}/../..</propertyExpansion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,68 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.hello;
import org.teavm.dom.ajax.ReadyStateChangeHandler;
import org.teavm.dom.ajax.XMLHttpRequest;
import org.teavm.dom.browser.Window;
import org.teavm.dom.events.Event;
import org.teavm.dom.events.EventListener;
import org.teavm.dom.html.HTMLButtonElement;
import org.teavm.dom.html.HTMLDocument;
import org.teavm.dom.html.HTMLElement;
import org.teavm.jso.JS;
public final class Client {
private static Window window = (Window)JS.getGlobal();
private static HTMLDocument document = window.getDocument();
private static HTMLButtonElement helloButton = (HTMLButtonElement)document.getElementById("hello-button");
private static HTMLElement responsePanel = document.getElementById("response-panel");
private static HTMLElement thinkingPanel = document.getElementById("thinking-panel");
private Client() {
}
public static void main(String[] args) {
helloButton.addEventListener("click", new EventListener() {
@Override public void handleEvent(Event evt) {
sayHello();
}
});
}
private static void sayHello() {
helloButton.setDisabled(true);
thinkingPanel.getStyle().setProperty("display", "");
final XMLHttpRequest xhr = window.createXMLHttpRequest();
xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
@Override public void stateChanged() {
if (xhr.getReadyState() == XMLHttpRequest.DONE) {
receiveResponse(xhr.getResponseText());
}
}
});
xhr.open("GET", "hello");
xhr.send();
}
private static void receiveResponse(String text) {
HTMLElement responseElem = document.createElement("div");
responseElem.appendChild(document.createTextNode(text));
responsePanel.appendChild(responseElem);
helloButton.setDisabled(false);
thinkingPanel.getStyle().setProperty("display", "none");
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.samples.hello;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class Server extends HttpServlet {
private static final long serialVersionUID = -5014505771271825585L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return;
}
String userAgent = req.getHeader("User-Agent");
resp.getWriter().println("Hello, " + userAgent);
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>

View File

@ -0,0 +1,31 @@
<!--
Copyright 2014 Alexey Andreev.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html>
<head>
<title>Hello web application</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" charset="utf-8" src="teavm/runtime.js"></script>
<script type="text/javascript" charset="utf-8" src="teavm/classes.js"></script>
</head>
<body onload="main()">
<h1>Hello web application</h1>
<button id="hello-button">Hello, server!</button>
<div id="response-panel">
</div>
<div style="display:none" id="thinking-panel"><i>Server is thinking...</i></div>
</body>
</html>

View File

@ -1,79 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.teavm</groupId>
<artifactId>teavm</artifactId>
<version>0.2-SNAPSHOT</version>
</parent>
<artifactId>teavm-scala-samples</artifactId>
<dependencies>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-dom</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.1.6</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<scalaVersion>2.10.0</scalaVersion>
</configuration>
</plugin>
<plugin>
<groupId>org.teavm</groupId>
<artifactId>teavm-maven-plugin</artifactId>
<version>${project.version}</version>
<dependencies>
<dependency>
<groupId>org.teavm</groupId>
<artifactId>teavm-classlib</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>generate-hello</id>
<goals>
<goal>build-javascript</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<minifying>false</minifying>
<mainClass>org.teavm.scala.samples.HelloWorld</mainClass>
<mainPageIncluded>true</mainPageIncluded>
<targetDirectory>${project.build.directory}/javascript</targetDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,11 +0,0 @@
package org.teavm.scala.samples
/**
*
* @author Alexey Andreev <konsoletyper@gmail.com>
*/
object HelloWorld {
def main(args : Array[String]) {
print("Hello")
}
}